From 93660e7e53d9b44495c55210a4af22d194f3bbc1 Mon Sep 17 00:00:00 2001 From: Piratebird <141295458+Piratebird@users.noreply.github.com> Date: Sun, 1 Nov 2026 22:26:26 +0200 Subject: [PATCH 01/18] :shipit: feat(core): headless services, torrent resolution, and real stack benchmarks - Add durable job queue with isolated workers, crash recovery, and cancellation - Add download, watch, serve, files, attach, and daemon commands - Add authenticated HTTP job API with range streaming of finished files - Resolve detail pages, redirects, direct .torrent URLs, and local metadata - Isolate Lite sources in bounded subprocesses with per-source diagnostics - Add standalone uninstall.sh and rename the executable to helm-torrent - Make libtorrent an optional download extra and fix Termux DHT bootstrap - Re-login to qBittorrent on expired sessions and tag jobs for batch reconcile - Redact secrets across logs and reports, including qBittorrent temp passwords - Defer heavy CLI imports and split main into smaller handlers - Use SQLite WAL, indexed lookups, and sendfile for the queue and file server - Add Docker and Podman stack benchmarks with verified cgroup limits - Add real-socket, subprocess, tmux, and fake-engine test coverage --- .gitignore | 1 + CHANGELOG.md | 38 + README.md | 135 +- docs/BENCHMARK.md | 127 +- docs/TODO.md | 45 +- docs/benchmarks/local-loopback-workers2.json | 1711 ++ docs/benchmarks/local-loopback.json | 1541 ++ docs/benchmarks/stack-docker.json | 13838 +++++++++++++++++ docs/benchmarks/stack-podman.json | 8237 ++++++++++ pyproject.toml | 11 +- requirements.txt | 2 +- setup.sh | 8 +- src/helm/cli.py | 496 +- src/helm/core/benchmark.py | 437 + src/helm/core/config_manager.py | 24 + src/helm/core/device_profile.py | 143 + src/helm/core/http.py | 25 +- src/helm/core/init_env.py | 6 +- src/helm/core/jobs.py | 380 + src/helm/core/lite_downloader.py | 51 +- src/helm/core/lite_fetcher.py | 78 +- src/helm/core/lite_plugin_loader.py | 160 +- src/helm/core/logger.py | 100 +- src/helm/core/oneshot.py | 4 +- src/helm/core/qbittorrent_client.py | 146 +- src/helm/core/rss_fetcher.py | 40 +- src/helm/core/runtime.py | 212 + src/helm/core/search_runner.py | 174 + src/helm/core/secret_manager.py | 51 +- src/helm/core/server.py | 244 + src/helm/core/stack_benchmark.py | 560 + src/helm/core/torrent_links.py | 227 + src/helm/core/watch.py | 117 + src/helm/plugins/bitsearch.py | 10 +- src/helm/plugins/bittorrented.py | 4 +- src/helm/plugins/eztv.py | 6 +- src/helm/plugins/helpers.py | 12 + src/helm/plugins/limetorrents.py | 3 +- src/helm/plugins/novaprinter.py | 16 +- src/helm/plugins/piratebay.py | 4 +- src/helm/plugins/subsplease.py | 11 +- src/helm/plugins/torlock.py | 3 +- src/helm/plugins/torrentproject.py | 3 +- src/helm/plugins/x1337.py | 22 +- src/helm/plugins/yts.py | 7 +- src/helm/ui/tui.py | 24 +- tests/conftest.py | 18 +- tests/test_benchmark.py | 197 + tests/test_cli.py | 354 +- tests/test_device_profile.py | 124 + tests/test_headless_cli.py | 162 + tests/test_jobs.py | 452 + tests/test_lite_fetcher.py | 115 +- tests/test_lite_plugin_loader.py | 37 + tests/test_logger.py | 78 + tests/test_qbittorrent_client.py | 107 +- tests/test_rss_fetcher.py | 4 +- tests/test_runtime.py | 235 + tests/test_scraper_fixtures.py | 161 + tests/test_search_runner.py | 205 + tests/test_secret_manager.py | 32 + tests/test_server.py | 367 + tests/test_service_boundaries.py | 142 + tests/test_stack_benchmark.py | 232 + tests/test_torrent_links.py | 257 + tests/test_uninstall.py | 245 + tests/test_watch.py | 162 + uninstall.sh | 179 + 68 files changed, 32810 insertions(+), 549 deletions(-) create mode 100644 docs/benchmarks/local-loopback-workers2.json create mode 100644 docs/benchmarks/local-loopback.json create mode 100644 docs/benchmarks/stack-docker.json create mode 100644 docs/benchmarks/stack-podman.json create mode 100644 src/helm/core/benchmark.py create mode 100644 src/helm/core/device_profile.py create mode 100644 src/helm/core/jobs.py create mode 100644 src/helm/core/runtime.py create mode 100644 src/helm/core/search_runner.py create mode 100644 src/helm/core/server.py create mode 100644 src/helm/core/stack_benchmark.py create mode 100644 src/helm/core/torrent_links.py create mode 100644 src/helm/core/watch.py create mode 100644 tests/test_benchmark.py create mode 100644 tests/test_device_profile.py create mode 100644 tests/test_headless_cli.py create mode 100644 tests/test_jobs.py create mode 100644 tests/test_runtime.py create mode 100644 tests/test_scraper_fixtures.py create mode 100644 tests/test_search_runner.py create mode 100644 tests/test_server.py create mode 100644 tests/test_service_boundaries.py create mode 100644 tests/test_stack_benchmark.py create mode 100644 tests/test_torrent_links.py create mode 100644 tests/test_uninstall.py create mode 100644 tests/test_watch.py create mode 100755 uninstall.sh diff --git a/.gitignore b/.gitignore index c33aa24..63c0d90 100644 --- a/.gitignore +++ b/.gitignore @@ -42,6 +42,7 @@ downloads/ # Auto-generated launcher (machine-specific) helm.sh +helm-torrent.sh # IDEs .vscode/ .idea/ diff --git a/CHANGELOG.md b/CHANGELOG.md index 4025df4..63fa85d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,43 @@ # Changelog All notable changes to this project will be documented in this file. +## [Unreleased] + +### Changed +- Start faster by deferring heavy imports, and split the CLI entry point into separate handlers. +- Use SQLite WAL, indexed lookups, one-second cancellation polling and `sendfile` in the queue and file server. +- Install the `helm-torrent` command instead of `helm` to avoid Kubernetes Helm's executable. Python imports, configuration paths, and container names remain compatible. Source setup generates `helm-torrent.sh`. +- Make libtorrent an optional `download` extra; Lite searches and magnet retrieval work without native bindings. +- Respect the configured download directory and reject unknown flags, blank queries, and invalid content types. + +### Added +- Durable job queue with process-isolated workers, crash recovery, cancellation and a completed-file catalog. +- `helm-torrent download`, `watch`, `serve`, `files`, `attach` and `daemon`, plus `--daemon` and `--session`. +- Authenticated HTTP job API and range streaming limited to cataloged files inside the download directory. +- Resolution of HTML detail pages, redirects, direct `.torrent` URLs and local metadata, with size, depth, hop and time limits. +- Isolated Docker and Podman stack benchmarks with effective cgroup verification and `--image`/`--image-manifest` overrides. +- A device profiler that reports energy as unavailable unless discharging is verified. +- A tested Linux PSS benchmark harness, source fingerprints, raw samples and verified generated-payload loopback BitTorrent measurements, including twelve-source concurrency comparisons and configurable `--lite-workers`. +- Isolated Lite worker processes with bounded deadlines/imports, category propagation, process cleanup and fixtures for every bundled scraper. +- Per-source Lite outcomes and retained-result counts on stderr, preserving JSON stdout. +- Standalone `uninstall.sh` for raw GitHub execution, with preview-by-default, selective removal and unit tests. + +### Fixed +- Log in to qBittorrent again after a session expires, and follow URL or credential changes in long-running services. +- Remove a cancelled job's torrent from qBittorrent, and map container paths to host paths when cataloging its files. +- Allow failed or cancelled sources to be resubmitted, and keep the queue worker alive after unexpected errors. +- Stop orphaned download workers after a forced service stop. +- Reject a whole watch file when any line is invalid, and survive transient watch-directory failures. +- Close connections after rejected requests so an unread body cannot be parsed as a new request; time out stalled clients. +- Keep the working directory off child-process import paths. +- Use DHT bootstrap session settings on bindings without `add_dht_router`, including Termux. +- Preserve completed plugin results when other plugins stall or reuse worker threads. +- Clean up owned one-shot containers across failures and interrupts; Lite searches never start the stack. +- Initialize logging after path overrides, redact credentials in formatted messages and archived logs, and read bounded log tails. +- Report bundled plugin HTTP/parser errors instead of presenting every failure as an empty search. +- Preserve unknown SubsPlease swarm counts through seed filtering. +- Omit configuration from bug reports when redaction fails. +- Correct README commands and qualify historical benchmark claims; add regression coverage. + ## [0.10.0] - 2026-09-08 diff --git a/README.md b/README.md index 8fcb486..fa6febb 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# Helm - Torrent Automation Prototype +# The Helm - Torrent Automation Prototype

@@ -18,17 +18,19 @@ ## Table of Contents -- [Helm - Torrent Automation Prototype](#helm---torrent-automation-prototype) +- [The Helm - Torrent Automation Prototype](#the-helm---torrent-automation-prototype) - [Table of Contents](#table-of-contents) - [Features](#features) - [Installation](#installation) - - [Python Package (New!)](#python-package-new) + - [Python Package](#python-package) + - [Termux / Android](#termux--android) - [Container Setup (Full Mode)](#container-setup-full-mode) - [Why this exists](#why-this-exists) - [Roadmap](#roadmap) - [Changelog](#changelog) - [Configuration](#configuration) - [Usage](#usage) + - [Uninstall](#uninstall) - [Performance \& Resource Optimization](#performance--resource-optimization) - [Disclaimer](#disclaimer) - [Contributing](#contributing) @@ -36,7 +38,7 @@ - [Credits](#credits) - [License](#license) -Helm is a blazing-fast CLI-based torrent automation tool designed to fetch, filter, and send magnet links to qBittorrent. +Helm is a CLI-based torrent automation tool designed to fetch, filter, and send magnet links to qBittorrent. It completely automates its own setup, orchestrating Jackett, Prowlarr, Flaresolverr, and qBittorrent using Docker or Podman under the hood. @@ -49,25 +51,55 @@ It completely automates its own setup, orchestrating Jackett, Prowlarr, Flaresol - **Permanent Mode:** Keep the stack running 24/7 if you prefer. - **VPN Support:** Automatically route qBittorrent traffic through Gluetun (Wireguard/OpenVPN). - **Live Search & Filter:** A fast, interactive CLI interface to search indexers and select torrents. -- **Lite Mode (Zero Setup):** Search and get Magnet links instantly using built-in Python scrapers — no Docker or Jackett needed. All sources (apibay, torrents-csv, Nyaa, and the bundled search plugins) run concurrently over a connection-pooled session, so even a hung index tops out at one socket timeout. +- **Lite Mode (Zero Setup):** Search public APIs and bundled Python scrapers without Docker or Jackett. Lite sources run in isolated processes with a shared 30-second budget, including queueing, startup and network work. Six run simultaneously by default; use `--lite-workers 2` or `HELM_LITE_WORKERS=2` to reduce process concurrency (valid range: 1–12). Stalled workers are terminated and reaped, with POSIX process-group cleanup; completed source results are preserved. Each worker thread reuses its own HTTP session. - **CLI Indexer Management:** Manage both Jackett and Prowlarr indexers directly from the command line. --- ## Installation -Helm requires **Docker** (with Docker Compose) or **Podman** (with podman-compose) installed on your system. +Lite Mode needs Python 3.8+ and internet access. Full Mode additionally needs **Docker** (with Docker Compose) or **Podman** (with podman-compose). -### Python Package (New!) -You can now install Helm directly via pip to run it natively or use the new Lite Mode: +### Python Package +Install Helm for native searches and magnet retrieval: ```bash pip install helm-torrent ``` -Once installed, you can launch the CLI from anywhere using: +Once installed, launch the CLI from anywhere: ```bash -helm +helm-torrent ``` +The Helm steers torrent downloads and is unrelated to Kubernetes Helm. The executable is `helm-torrent`; Helm does not install a `helm` alias. Existing Python imports, data directories, and container names remain compatible. When upgrading from an older release, reinstall the Python package to replace its entry points. If the old installation previously overwrote Kubernetes Helm, restore Kubernetes Helm using its own installer afterward. + +When installing this checkout, use `python -m pip install -e .` to run the uncommitted changes. Public PyPI packages and raw GitHub files only include these changes after a release or push. + +The built-in downloader is optional and requires compatible libtorrent bindings: +```bash +pip install 'helm-torrent[download]' +``` +Without libtorrent, selecting a Lite result prints its magnet link for use in another torrent client. Searching and JSON output work without it. + +### Termux / Android + +Run Lite Mode directly from Termux; it does not require the container stack: +```bash +pkg install python +python -m pip install --upgrade helm-torrent +helm-torrent search "Ubuntu" --type software --lite --json +``` +For lower-memory searches, add `--lite-workers 2`; fewer workers can increase latency or exhaust the shared queue budget. + +Native libtorrent bindings may require platform-specific installation. You can use the magnet links with an Android torrent client instead. + +If a source times out (for example, `nyaa.si`), Helm keeps results from other completed sources. A timeout indicates a connection problem with that source; it does not establish that no matching torrents exist. DNS, network filtering, and source outages can affect availability. + +- Enter a nonempty, specific query. A request containing `q=` has an empty query; current Helm rejects blank interactive and CLI searches. +- Use `helm-torrent logs` for recent source errors, or `HELM_VERBOSE=true helm-torrent search "artist album" --type music --lite --json` for verbose diagnostics on stderr. +- If raw results exist but the final list is empty, check content filters and `min_seeds` in `config.json` (default: 3). Use `helm-torrent paths` to locate it. +- Content types are mapped to plugin category keys when supported (video searches movies/TV/anime); general sources fall back to `all`. Inline feeds and unsupported categories still rely on local scoring/filtering. +- A source summary on stderr distinguishes empty results from timeouts, HTTP failures, connection failures, and parse failures. Bundled plugins report swallowed failures; third-party plugins may need the `novaprinter.report_error` hook. Jobs whose queue budget expires are marked `budget_exhausted`; JSON stdout stays separate. + ### Container Setup (Full Mode) **Instant Terminal Installation:** @@ -140,34 +172,85 @@ The first run migrates any legacy secrets found in older `config.json` files int ## Usage -Helm is primarily run using the included scripts to manage the Docker containers and CLI. +Run `helm-torrent` for the interactive CLI. Use subcommands for scripted searches and administration: +```bash +# Search without containers and emit JSON (no download) +helm-torrent search "Ubuntu" --type software --lite --json + +# Configure the full container environment +helm-torrent init + +# Start the configured stack, select a download, then stop it +helm-torrent search "Ubuntu" --type software --oneshot + +# Automatically select and download the top filtered result +helm-torrent search "Ubuntu" --type software --auto -Typical workflow: +# Manage indexers or inspect the installation +helm-torrent indexers --prowlarr +helm-torrent status +helm-torrent paths +helm-torrent logs +``` + +Built-in downloads respect `--dl-dir` / `HELM_DL_DIR`. Invalid content types and unknown flags are rejected. Lite Mode never starts containers, including when `--oneshot` is passed. + +JSON search exits with status 0 when results exist, or 1 for an empty list. Normal search prompts you to choose a result; `--auto` sends the top result to the downloader. The source installer also generates a machine-specific `helm-torrent.sh` launcher for the container workflow; it is not included in the source checkout. + +### Headless and background use + +```bash +# Download a magnet, detail page, .torrent URL or local .torrent file +helm-torrent download 'magnet:?xt=urn:btih:...' + +# Queue stable .torrent, .magnet and .txt files dropped into a directory +helm-torrent --daemon watch ~/torrents/inbox + +# Accept jobs and stream finished files over an authenticated local API +helm-torrent --daemon serve --port 8765 -1. Run `./setup.sh` to configure indexers, VPN, and credentials. -2. Run `./helm.sh` to launch the interactive CLI and search for torrents. -3. Matching torrents are filtered and sent to qBittorrent automatically. +# List or stop background commands +helm-torrent daemon status +helm-torrent daemon stop -You can also pass arguments directly to the wrapper script: +# Start a tmux UI that survives SSH disconnects, then reconnect to it +helm-torrent --session main +helm-torrent attach main +``` + +`serve` and `files` require `Authorization: Bearer ` on every route. A token is generated in `secrets.env` when none is set. `files` is the read-only variant. Both bind to `127.0.0.1` by default and speak plain HTTP, so use a VPN or TLS proxy before exposing them to a network. + +If qBittorrent sees downloads at a path other than `/downloads` inside its container, set `QB_DOWNLOADS_ROOT` so finished files can be mapped back to the host. tmux is required for `--session` and `attach`. + +## Uninstall + +Download the standalone Bash script from GitHub, or run `./uninstall.sh` from a checkout. This URL becomes available after the script is pushed: ```bash -# Force one-shot mode (spins up and tears down Docker) -./helm.sh --oneshot +# Show options; this does not remove anything +bash <(curl -fsSL https://raw.githubusercontent.com/Piratebird/helm/main/uninstall.sh) --help + +# Preview removing application config and service data +bash <(curl -fsSL https://raw.githubusercontent.com/Piratebird/helm/main/uninstall.sh) --config --state --dry-run -# Auto-download the top result for a query -./helm.sh --oneshot --auto -q "Ubuntu 24.04" --type software +# Apply only the selected removal options +./uninstall.sh --config --state --yes -# Run built-in Lite Mode (without Jackett/Docker) -./helm.sh --lite +# Preview removal of this project's containers and networks +./uninstall.sh --containers --engine docker --project helm --dry-run -# Manage Jackett indexers -./helm.sh --indexers +# Preview uninstalling the Python package from a particular environment +HELM_PYTHON=/path/to/venv/bin/python ./uninstall.sh --package --dry-run ``` +Every operation previews by default; `--yes` applies it, and `--dry-run` always prevents changes. `--containers` targets exact Compose project labels. Named volumes are preserved unless you also select `--volumes`; that option deletes all contents of matching named volumes, including any downloads stored inside them. + +Host downloads, user plugins, source files, images, and Kubernetes Helm configuration are preserved. Use `--config-dir`, `--state-dir`, and `--downloads-dir` for custom locations. The script does not remove native Jackett/qBittorrent installations or system services; disable an installer-created `helm-app.service` separately before removing its stack. It never invokes the `helm` executable. + ## Performance & Resource Optimization -Helm is aggressively optimized for a minimal memory footprint. While containerized applications are usually heavy, the `setup.sh` installer strictly throttles the Docker/Podman engines using Linux cgroups (e.g., hard-capping Jackett to 256MB). +The generated Compose configuration declares per-service CPU and memory limits. Enforcement depends on the container engine and host cgroup configuration; verify the limits on your deployment. One-shot mode stops service containers after use, while the container engine, filesystem cache, and other host processes may remain active. -In our [Resource Benchmarks](docs/BENCHMARK.md), we proved that running Helm's containerized stack actually **saves RAM** compared to installing the software natively! +The [resource benchmark report](docs/BENCHMARK.md) includes a tested harness, raw PSS samples, and three verified local search/download trials at each of two concurrency settings. It separates these measurements from unverified historical container figures. Run `python -m helm.core.benchmark --help` for reproduction options. ## Disclaimer diff --git a/docs/BENCHMARK.md b/docs/BENCHMARK.md index 05b3349..5fc7411 100644 --- a/docs/BENCHMARK.md +++ b/docs/BENCHMARK.md @@ -1,6 +1,103 @@ -# Helm Engine Resource Benchmark (August 2026) +# Helm Resource Benchmarks -This benchmark directly compares the memory footprint of running the Helm core stack (**Jackett** + **qBittorrent**) across three different architectures: Docker (with strict limits), Podman (with strict limits), and Bare-Metal Native. +## Reproducible local workload (October 2026) + +The tested harness is [benchmark.py](../src/helm/core/benchmark.py). Its [raw samples](benchmarks/local-loopback.json) record three trials at six-worker concurrency, per-sample PSS, phase events, checksums, source SHA-256 fingerprints, the base Git revision and dirty-tree status, Python/kernel/CPU details, and whether engine overhead was included. + +Measured environment: **11th Gen Intel(R) Core(TM) i5-1135G7 @ 2.40GHz**, 8 logical CPUs, Linux kernel `7.2.11`, Python `3.14.8`, libtorrent `2.0.11.0`. These measurements were taken from an uncommitted working tree; source hashes identify the measured implementation. + +These local figures predate later queue and client changes, so current source hashes do not match every file recorded in the report. + +The workload consists of a warm idle process, twelve offline search plugins emitting 100 generated results each (1,200 total) through the actual isolated worker pipeline, a real loopback BitTorrent transfer of a generated **4 MiB** payload, session teardown, and process exit. Public trackers, DHT, local discovery, UPnP, and NAT-PMP are disabled for the download. Every transfer is verified by SHA-256. + +| Phase | Complete samples | Median workload PSS (MiB) | Peak workload PSS (MiB) | +| :--- | ---: | ---: | ---: | +| idle | 17 | 20.51 | 20.91 | +| search | 26 | 31.12 | 126.55 | +| download | 32 | 30.85 | 39.83 | +| teardown | 18 | 34.54 | 35.04 | +| exited | 3 | 0.00 | 0.00 | + +Median twelve-job fixture search latency: **0.498 s**, range **0.487–0.524 s**. Median loopback download phase: **0.738 s**, range **0.699–0.740 s**. Download timing includes fixture generation, torrent/session setup, transfer, flushing, and checksum verification; it is not a pure network-throughput measurement. + +Teardown retains the Python process and loaded native libraries. Only the `exited` sample reflects the reaped workload; a zero there says nothing about whole-host RAM usage. Races with exiting processes are marked incomplete and excluded from median/peak calculations rather than counted as zero. + +## Concurrency comparison + +The [two-worker samples](benchmarks/local-loopback-workers2.json) use the same twelve plugins and payload, measured sequentially after the six-worker run. Each configuration has three trials. + +| Concurrent search workers | Median search latency (s) | Peak search workload PSS (MiB) | +| ---: | ---: | ---: | +| 6 | 0.498 | 126.55 | +| 2 | 0.862 | 58.73 | + +Two workers reduced the observed peak memory at the cost of a longer fixture search. This host-only comparison does not establish an optimal Android setting. The CLI exposes `--lite-workers 2` (or `HELM_LITE_WORKERS=2`), with six as the default and a valid range of 1–12. The shared search deadline includes queueing, so fewer workers can leave more jobs unstarted when early sources stall; these are reported as `budget_exhausted`. + +## Production stack (November 2026) + +[stack_benchmark.py](../src/helm/core/stack_benchmark.py) starts Jackett, Prowlarr, qBittorrent and FlareSolverr in a disposable project, using the same image IDs on both engines. A generated indexer page is searched through Prowlarr and Jackett, then qBittorrent downloads a generated 16 MiB payload from a local seeder and its SHA-256 is verified. The raw samples are in [stack-docker.json](benchmarks/stack-docker.json) and [stack-podman.json](benchmarks/stack-podman.json). + +Each engine completed three trials. Effective cgroup limits matched the request on every service: 256 MiB and 0.5 CPU, or 512 MiB and 0.5 CPU for FlareSolverr. All containers stopped, and cleanup reported no errors. + +| Engine | Five searches, by trial (s) | Download, by trial (s) | Median idle `memory.current` (MiB) | Peak during download (MiB) | +| :--- | ---: | ---: | ---: | ---: | +| Docker | 24.40, 15.83, 11.21 | 2.07, 1.05, 1.24 | 302.6 | 332.8 | +| Podman | 8.52, 8.02, 8.02 | 1.49, 1.48, 1.48 | 316.5 | 345.0 | + +Memory figures sum the four service cgroups at each sample. They include page cache charged to those cgroups and exclude the engine daemons, so they cannot be added to the PSS figures above. + +Do not read these runs as a Docker-versus-Podman ranking. The engines ran one after the other on a host with unrelated containers active, Docker's first trial was the slowest for reasons not isolated here, and three trials cannot separate those effects. Search time also reflects 0.5 CPU limits and service overhead, not live indexer latency. + +The default image IDs exist only on the host that recorded them. Elsewhere, pass `--image-manifest images.json` or `--image service=reference`: + +```bash +PYTHONPATH=src python -m helm.core.stack_benchmark --engine docker --output docs/benchmarks/stack-docker.json --repeats 3 +``` + +## Run the harness + +```bash +python -m pip install -e '.[dev,download]' +PYTHONPATH=src python -m helm.core.benchmark --output docs/benchmarks/local-loopback.json --repeats 3 --search-workers 6 +PYTHONPATH=src python -m helm.core.benchmark --output docs/benchmarks/local-loopback-workers2.json --repeats 3 --search-workers 2 + +# Optional: sample an ALREADY RUNNING stack and shared engine processes. +# This does not start, stop, configure, or download through the attached stack. +PYTHONPATH=src python -m helm.core.benchmark --output /tmp/helm-attached.json --engine docker --project helm --include-engine + +python -m pytest tests/test_benchmark.py tests/test_search_runner.py tests/test_scraper_fixtures.py -q +``` + +The PSS sampler requires Linux `/proc/*/smaps_rollup` access. Compatible Termux devices can run it if Android permits reading those files. Install libtorrent bindings supported by the platform before running the download phase. The harness follows the [official libtorrent Python bindings](https://www.libtorrent.org/python_binding.html). + +Options control repetitions, sample interval, payload size, download timeout, fixture plugin/result counts, and search concurrency. No source searches or external downloads occur in the local benchmark. Output files contain measurements and allowlisted metadata; container environment variables and secrets are excluded. + +## Accounting and practical limits + +- Every component uses **PSS in bytes**. Workload, attached service trees, and shared engine/helper processes are disjoint PID sets; overlapping descendants are counted once. +- The benchmark observer is excluded. The local workload includes its search subprocesses; seeder and downloader sessions both live inside the measured workload. This is a reproducible two-peer exercise, not a measurement of one production downloader alone. +- Engine and attached-stack figures are separate components. The saved local run has neither enabled; their zeros mean excluded, rather than evidence of zero engine overhead. +- Optional whole-host engine costs include `dockerd`, `containerd`, `conmon`, `pasta`, `slirp4netns`, and `rootlesskit` process trees. These costs may be shared with unrelated workloads. Unreadable PSS is explicitly marked incomplete. +- PSS excludes filesystem cache and kernel/network allocations. It cannot be added to RSS or cgroup memory usage as if they were the same metric. +- Container attachment records image IDs, configured CPU/memory ceilings, engine version, and project selection. Declared limits are not proof of enforcement; verify effective cgroups separately on the target host. +- The saved download is loopback-only, and the fixture search is offline. These numbers do not predict live indexer latency, internet swarm speed, Termux performance, or a full container stack's memory footprint. + +No Helm project containers were running during this review. A real Docker/Podman stack idle/search/download/teardown comparison remains a separate measurement task; this harness supports read-only attachment and does not fabricate those figures. + +## Improvements suggested by the evidence + +1. Measure complete production stack lifecycles in an isolated Compose project, with effective cgroup limits and the same legal payload. Keep live-source availability separate from engine comparisons. +2. Track cold subprocess startup and peak memory as worker concurrency changes. Process isolation fixes unbounded exit but adds startup and memory costs; offline fixtures do not establish the best concurrency for live sources that may block for their entire timeout. +3. Add per-phase CPU and energy measurements for Termux, where six simultaneous Python workers may be expensive. +4. Exercise interrupted download recovery and native-library teardown on a real Android device. Linux fixtures cannot establish device compatibility. + +--- + +## Historical reports (unverified) + +These are historical figures reported for August and September 2026. Those original reports were not accompanied by raw samples, exact image versions, or a record of their workload and measurement commands. The figures below have not been independently reproduced in this review and should be treated as observations to validate, rather than performance guarantees. + +The August comparison covers **Jackett + qBittorrent**. The September comparison includes more services and uses a different accounting boundary; the two tables are not directly comparable. ### Test Environment * **OS:** Fedora Linux 44 (Workstation Edition) x86_64 @@ -9,7 +106,7 @@ This benchmark directly compares the memory footprint of running the Helm core s * **RAM:** 16 GB (15.41 GiB usable) > [!NOTE] -> All containerized benchmarks were run using the exact `deploy.resources.limits` constraints we just added to the `setup.sh` installer: `0.50` CPU cores and `256M` RAM. +> The original report described limits of `0.50` CPU cores and `256M` RAM. Current generated configurations vary by service: Flaresolverr declares `512M`, and Gluetun declares `128M` / `0.25` CPU cores. Limits are ceilings, not measured usage, and enforcement must be checked on the actual engine and host. ### Memory Consumption Comparison Chart @@ -21,32 +118,24 @@ This benchmark directly compares the memory footprint of running the Helm core s --- -### Analytical Conclusions +### Interpretation and limitations -#### 1. The Jackett Paradox (Containers win!) -Normally, native applications use less memory than containers because they bypass virtualization overhead. However, Jackett is a heavy `.NET` application. When run **Natively**, the .NET Garbage Collector is lazy and rapidly expands its memory footprint to consume whatever it wants (`~231.9 MB`). +The reported Docker and Podman totals are lower than the reported native total for this particular snapshot. They do not demonstrate why Jackett used less memory: runtime versions, garbage collector settings, workload, warm-up, and measurement method were not recorded. There are no search-latency measurements to support a claim that memory limits have no performance cost. -By wrapping it in Docker/Podman and strictly limiting it to `256M`, the .NET engine is forced to aggressively garbage collect, dropping its real usage down to just **`91.5 MB`** (Docker) without losing a millisecond of search speed! - -#### 2. The Engine Winner: Podman -While Docker achieves incredible compression on the application memory, you must factor in the persistent `dockerd` and `containerd` daemons running in the background of your host, which constantly consume `~100MB` of RAM even when idle. - -**Podman** is daemonless. The only overhead it requires is a microscopic `conmon` monitor process. Therefore, **Podman is the absolute most memory-efficient way to run Helm.** - -#### 3. Verdict -The optimizations we just committed to `setup.sh` are game-changing. By enforcing limits on the containers, your users will actually save *more* memory running Helm via Podman or Docker than they would if they compiled and ran the apps manually on their own host! +Podman does not require a persistent central daemon, but container monitors, networking helpers, and other host processes still consume resources. The table's `0.0 MB` daemon column must not be interpreted as zero host overhead. Docker daemon overhead can also be shared with other workloads. --- ### Update (September 2026): Full Ephemeral Stack with Prowlarr & Flaresolverr -Following the integration of **Prowlarr** and **Flaresolverr** into the one-shot stack, we re-ran the memory profiling using the exact same constraints. +The original report added the following figures after integrating **Prowlarr** and **Flaresolverr**. The container totals below sum only the listed services and CLI; unlike the August Docker total, they exclude engine overhead. Lite Mode is a search-only baseline with a different feature set, and does not include an active libtorrent download. -| Deployment Architecture | qBittorrent | Jackett | Prowlarr | Flaresolverr | CLI Runner (Python) | Total Active Memory | +| Deployment Architecture | qBittorrent | Jackett | Prowlarr | Flaresolverr | CLI Runner (Python) | Sum of Listed Components | | :--- | :--- | :--- | :--- | :--- | :--- | :--- | | **Docker** | `~17.2 MB` | `~53.1 MB`| `~67.9 MB`| `~40.2 MB` | `~31.0 MB` | **`~209.4 MB`** | | **Podman** | `~15.0 MB` | `~47.0 MB`| `~61.0 MB`| `~36.0 MB` | `~31.0 MB` | **`~190.0 MB`** | | **Native (Lite Mode)** | N/A | N/A | N/A | N/A | `~31.0 MB` | **`~31.0 MB`** | -#### 4. The Ephemeral Advantage -With Prowlarr and Flaresolverr added, a standard daemonized setup would idle at nearly ~200MB 24/7. However, because Helm utilizes the **One-Shot Ephemeral Stack**, this memory is *only* consumed during the exact moment you execute a search and download a torrent. The second you exit the TUI, the containers are spun down (`teardown_oneshot()`), and the stack's memory footprint returns to **0 MB**. +### One-shot lifecycle + +One-shot mode stops the service containers after the workflow completes. This releases their process memory, but does not imply that total host overhead returns to zero: the engine, cached pages, CLI, and other helpers may remain. Error and interruption paths also need to be tested when evaluating cleanup. diff --git a/docs/TODO.md b/docs/TODO.md index b5a2622..f704cea 100644 --- a/docs/TODO.md +++ b/docs/TODO.md @@ -1,5 +1,30 @@ # Helm Roadmap & Tasks +## Review priorities (October 2026) + +Address reliability and measurement gaps before adding the daemon or AI features. + +- [x] Preserve completed source results with one shared deadline; replace nested collection pools with isolated source jobs. +- [x] Snapshot each plugin's result collector and isolate plugin imports/execution in disposable processes. +- [x] Reject empty Lite/CLI queries, preserve other results when Nyaa times out, and explain empty sources versus results removed by filters. Add regression tests. +- [x] Configure DHT bootstrap nodes through session settings for Termux bindings without `add_dht_router`. +- [x] Make libtorrent an optional download extra so search/magnet retrieval can be installed independently of native bindings. +- [x] Omit configuration from bug reports if redaction fails, rather than copying the raw file. +- [x] Correct README commands, explain Termux Lite usage, and qualify unsupported benchmark conclusions. +- [x] **Source diagnostics:** Search-owned outcomes distinguish success, empty, HTTP failure, connection failure, timeout, and parse failure; summaries print after the spinner on stderr. +- [x] **Plugin error visibility:** Bundled plugins record swallowed HTTP/parser failures; helper fetches raise HTTP errors, challenge/changed pages are detected, and retained partial results carry failure outcomes. +- [x] **Cancellation:** Short-lived subprocess jobs share a deadline; imports, network work and queued jobs are bounded. Worker cleanup terminates/reaps POSIX process groups, with a Windows taskkill fallback. Regression tests cover hung imports, process exit, interrupts, queue exhaustion, and descendants. +- [x] **One-shot lifecycle:** Centralized teardown with `try/finally`; regression tests cover startup/search/download/wait failures, early returns, and `--oneshot --lite`. +- [x] **Machine output:** Indexer fallback and source summaries use stderr; tests exercise real `animated_search` fallback paths with `--json`. +- [x] **Logging and reports:** Configure files explicitly after path overrides; redact known/encoded secrets, credential URLs, query keys, nested settings and exception traces; stream redacted archived logs and read bounded file tails. +- [x] **Plugin/category coverage:** Offline fixtures cover every bundled scraper, failure classes and category mapping; selected categories reach isolated workers. Unknown SubsPlease swarm counts use -1 so valid results survive seed filters. +- [x] **Configuration:** Validate CLI content types and unknown arguments; respect the configured downloads directory in the built-in downloader. +- [x] **Benchmarks:** Tested Linux PSS harness and raw samples cover local idle/fixture-search/verified loopback-download/teardown/exit, with source fingerprints, consistent process-tree accounting, and two-/six-worker comparisons. `--lite-workers` exposes the memory/latency tradeoff. See [BENCHMARK.md](BENCHMARK.md). +- [x] **Real stack benchmarks:** Isolated Docker and Podman runs exercise Prowlarr, Jackett, FlareSolverr and qBittorrent with verified cgroup limits, checksummed downloads and lifecycle samples. See [BENCHMARK.md](BENCHMARK.md). +- [x] **Torrent link resolution:** Magnets, HTML detail pages, redirects, direct `.torrent` URLs and local metadata resolve with bounded size, depth, hops and time. +- [ ] **Device measurements:** Verify Android/Termux process cleanup and memory with `--lite-workers`. The profiler and CPU/energy accounting are tested locally, but no complete device run has been recorded. +- [x] **Integration coverage:** Subprocess, real-socket and fake-engine tests cover the headless CLI, HTTP API, tmux sessions, wizard and one-shot ordering. The wizard's full-automation prompts remain lightly covered. + ## Completed Tasks - [x] Create a Bash installer (`setup.sh`) - [x] Automate installation of Docker containers for Jackett, Flaresolverr, and qBittorrent @@ -20,7 +45,8 @@ - [x] **Advanced Configuration Management:** Expanded `ConfigManager` to support schema validations, OS-native paths (XDG standards), and seamless migrations when updating to newer Helm versions. ### 1. User Interface & Experience -- [ ] **Scrumptious TUI Interface:** Rewrite the CLI interface using a modern framework (like `Textual` or `Rich`) to replace raw `termios` handling. - [ ] Rewrite the interface using the `Textual` Python framework for a rich, responsive split-screen UI. +- [ ] **Scrumptious TUI Interface:** Replace raw `termios` handling with a responsive UI. + - [ ] Rewrite the interface using the `Textual` Python framework for a rich, responsive split-screen UI. - [ ] **Background Download Manager:** Upgrade the blocking `lite_downloader.py` (libtorrent) to run as an async background worker. - [ ] **Downloads Sidebar:** Users can search Jackett while simultaneously watching live progress bars, ETA, and speeds of active libtorrent downloads on the side. - [ ] **Seeding Controls:** Ability to pause/resume/delete active downloads directly from the UI. @@ -38,23 +64,24 @@ - [x] Implement API handlers for Prowlarr so users who prefer modern tracker syncing can use it seamlessly. - [x] **Improve Jackett Interaction:** - [x] Allow adding/removing indexers directly from the CLI. - - [x] Auto-inject default indexers (1337x, YTS, etc.) during `helm init` via internal API. + - [x] Auto-inject default indexers (1337x, YTS, etc.) during `helm-torrent init` via internal API. ### 3. Distribution & Installation -- [ ] **Uninstall Script (`uninstall.sh`):** - - [ ] Provide an automated script to cleanly remove Helm containers, networks, volumes, and Python packages based on user choice. +- [x] **Uninstall Script (`uninstall.sh`):** + - [x] Standalone raw-GitHub Bash script with preview-by-default removal of selected containers, networks, named volumes, app configuration/state, and the Python package; preserve host downloads and Kubernetes Helm configuration. +- [x] **Command disambiguation:** Install `helm-torrent` without a `helm` alias; update setup guidance and generated launcher name. - [x] **Publish to PyPI (`pip install helm-torrent`):** - [x] Restructure directory to standard Python package layout. - - [x] Implement `helm init` to automatically bootstrap the Docker environment on first run. + - [x] Implement `helm-torrent init` to automatically bootstrap the Docker environment on first run. - [x] **Fully Automated Setup Script:** - [x] Add a "skip-prompts" flag to `setup.sh` that auto-generates passwords and pulls Jackett API keys completely silently. - [x] Provide a curl one-liner for instant terminal installation. ### 4. Headless & Server Mode -- [ ] **Daemon Background Processes:** Add a `--daemon` flag to run operations silently in the background. -- [ ] **Watch Directory (`helm watch

`):** Automatically parse and download any `.torrent` or magnet files dropped into a specified folder. -- [ ] **HTTP Server (`helm serve` / `helm files`):** Spin up a lightweight web server to accept magnets remotely and stream finished downloads. -- [ ] **Session Attach (`helm attach`):** Allow reattaching to a running TUI session across SSH disconnects. +- [x] **Daemon Background Processes:** Add a `--daemon` flag to run operations silently in the background. +- [x] **Watch Directory (`helm-torrent watch `):** Automatically parse and download any `.torrent` or magnet files dropped into a specified folder. +- [x] **HTTP Server (`helm-torrent serve` / `helm-torrent files`):** Spin up a lightweight web server to accept magnets remotely and stream finished downloads. +- [x] **Session Attach (`helm-torrent attach`):** Allow reattaching to a running TUI session across SSH disconnects. ### 5. AI & Automation - [ ] **AI Torrent Agent (Natural Language):** Integrate an LLM (Gemini/OpenAI) so users can type natural language commands (e,g. *"Download the LOTR Extended Editions in 4K"*). The AI will autonomously map the intent to search queries, evaluate the seeders/sizes of the results, pick the optimal magnet, and send it to qBittorrent. diff --git a/docs/benchmarks/local-loopback-workers2.json b/docs/benchmarks/local-loopback-workers2.json new file mode 100644 index 0000000..7bc4b98 --- /dev/null +++ b/docs/benchmarks/local-loopback-workers2.json @@ -0,0 +1,1711 @@ +{ + "schema_version": 1, + "mode": "local_fixture_search_and_loopback_bittorrent", + "metric": "PSS bytes; same metric for every component", + "environment": { + "platform": "Linux-7.2.11-200.fc44.x86_64-x86_64-with-glibc2.43", + "python": "3.14.8 (main, Oct 1 2026, 00:00:00) [GCC 16.2.1 20260819 (Red Hat 16.2.1-2)]", + "cpu_count": 8, + "cpu_model": "11th Gen Intel(R) Core(TM) i5-1135G7 @ 2.40GHz", + "source_sha256": { + "__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "cli.py": "1d826809006ec312575cc34d3e0876b50cfae043121e83a61bbb4d6446d475d9", + "core/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "core/benchmark.py": "d3b790f5f5f3e56bac21f60c64b8a245bfaed2c9387d2f9ae142f02dd4c51518", + "core/config_manager.py": "6f71069e1544145b5ab2c324326df1f7d75250ec4bba4d5361e60c8251e5686c", + "core/config_wizard.py": "d3303501145dad0e49dd19c6e6153c19a039b0e479a14f72ead24ededfb8f6c0", + "core/http.py": "3d36d9d66e954610b0b8e925251af38959d1c7e606ebdcdbfd5501ba03c6f344", + "core/indexer_manager.py": "1435e21114ff5de6da67e084a13103b8cd25bbe91367f118d75fb5c95c130472", + "core/init_env.py": "f8eab6975fc5c7ce2b6b86658eeb7eb3feb36bd70d95f0204cd285c5ae7f330c", + "core/lite_downloader.py": "064f39174a24d6113c1cfd56f064e247ed40642ae3d080640b4f35f565c6dc63", + "core/lite_fetcher.py": "dd7505d13c6107347ec962c7e1868b79112992800b8873d47691cfdb8dbe2e36", + "core/lite_plugin_loader.py": "419dea428158a28314a7a192cabd88e54b078d8542258db243bbad2c2f141b0d", + "core/logger.py": "fba54c1264da77f2faf8fa5b6fc3df66fecd5e01d6f8be52fdd4edca202106bf", + "core/oneshot.py": "e1ac659d8e95f39c11da837d3bc6cd101a8949a7c41cfe2b322c6f6b963dac8e", + "core/qbittorrent_client.py": "7a412585b4f0b056a43b4040cba95b00e12ba0de0ae395d91590aa0bb3a36276", + "core/rss_fetcher.py": "9b3f508ab7add45b99bba9526679ae21063d75fa04728eb97ba7a8cf82e426a7", + "core/search_runner.py": "782a28401bafd86e9e38b77afd8f50cd241c2f0d2f9f30371e08f3b2efcb96fd", + "core/secret_manager.py": "2d9a15ad2483fe3976c05dccc76f9814f6df0dbeb2e9cd943f47c85f17ec02ee", + "core/torrent_filter.py": "662daedbbafbb4197ac8e9aec68b033001f9317b8745aa92741d52e7da9934a0", + "plugins/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "plugins/bitsearch.py": "4a648f04b729a6556036ca5ee830c3db4a85b492a9d6e9524e7c38864a062a4f", + "plugins/bittorrented.py": "1077d397916be8c83471db61a2733426417119109bf53694bd2dd22b34fe9873", + "plugins/eztv.py": "8576d0f09636ef1da55024fcdab7212f4c9627d339fbc6657fce573823e6e6b0", + "plugins/helpers.py": "9af508d98875f399e98ee60428153cec41140b41a0bc8c2da23ca743a4e81556", + "plugins/limetorrents.py": "60f8f6321664108875accd2585a8d51e4fbf5fb5c88d63d3ec8733a6ad1aa68a", + "plugins/novaprinter.py": "a3193175bd64d9517d368ff4ba70d2c56d85011d18d8f196c82ff308e8cc685e", + "plugins/piratebay.py": "21f760eac8d931ac25dc05a79654f14313a30d48d81f878e857a25f4e226bc3f", + "plugins/subsplease.py": "4117d2cd8f58e9ace19c5d9287f1b2307fab0d32a6fc15898f3e6ef75c37f402", + "plugins/torlock.py": "2d818ddda16c4e150878be63c0b0ff03f2e746bef73e8a86e38758366d235071", + "plugins/torrentproject.py": "1f8c5be60357f1d4baf4ba2722aa316e5bdd50324209f8b22aa902a6abad4c86", + "plugins/x1337.py": "29dbdd5c57b95e7750b20b5bd8cfdb324dc6e3db8cde5e9005e4f5295157b581", + "plugins/yts.py": "fdd2e0236aacf0e43cdf2a43abd16ee33fdb5f736de84ed357afb54a9c1df0fe", + "ui/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "ui/colors.py": "192984be5f757359e15eb93ce1cd71083d257538199d8567dd5d9501a7481f37", + "ui/tui.py": "06a59767dfdbfc55876866e2e18d471430e56055ca232a8fc7360a893ef2ee2e" + }, + "cgroup_version": 2, + "revision": "f61d816128b4c98ee012fb9981e441852b758f2d", + "dirty": true + }, + "interval_seconds": 0.05, + "payload_bytes": 4194304, + "fixture_plugins": 12, + "fixture_results_per_plugin": 100, + "search_workers": 2, + "attachment": null, + "include_engine": false, + "limitations": [ + "Fixture search is offline; not a live indexer latency measurement", + "Download uses generated content and loopback peers; not internet swarm performance", + "PSS excludes filesystem cache and kernel/container networking allocations", + "Engine processes are whole-host shared costs when included", + "Attached stack is sampled read-only; its lifecycle is not exercised" + ], + "trials": [ + { + "samples": [ + { + "elapsed_seconds": 0.06566078400283004, + "phase": "idle", + "missing_pids": [], + "workload_pss_bytes": 21517312, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 21517312, + "complete": true + }, + { + "elapsed_seconds": 0.14384482900277362, + "phase": "idle", + "missing_pids": [], + "workload_pss_bytes": 21517312, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 21517312, + "complete": true + }, + { + "elapsed_seconds": 0.22582816000067396, + "phase": "idle", + "missing_pids": [], + "workload_pss_bytes": 21517312, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 21517312, + "complete": true + }, + { + "elapsed_seconds": 0.30568986000071163, + "phase": "idle", + "missing_pids": [], + "workload_pss_bytes": 21517312, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 21517312, + "complete": true + }, + { + "elapsed_seconds": 0.38711015000080806, + "phase": "idle", + "missing_pids": [], + "workload_pss_bytes": 21517312, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 21517312, + "complete": true + }, + { + "elapsed_seconds": 0.4667847540004004, + "phase": "idle", + "missing_pids": [], + "workload_pss_bytes": 21675008, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 21675008, + "complete": true + }, + { + "elapsed_seconds": 0.488049368999782, + "phase": "search", + "missing_pids": [], + "workload_pss_bytes": 37730304, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 37730304, + "complete": true + }, + { + "elapsed_seconds": 0.5609896669993759, + "phase": "search", + "missing_pids": [], + "workload_pss_bytes": 59568128, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 59568128, + "complete": true + }, + { + "elapsed_seconds": 0.6321623639996687, + "phase": "search", + "missing_pids": [], + "workload_pss_bytes": 37929984, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 37929984, + "complete": true + }, + { + "elapsed_seconds": 0.7036465870005486, + "phase": "search", + "missing_pids": [], + "workload_pss_bytes": 61088768, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 61088768, + "complete": true + }, + { + "elapsed_seconds": 0.7745498700023745, + "phase": "search", + "missing_pids": [], + "workload_pss_bytes": 37982208, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 37982208, + "complete": true + }, + { + "elapsed_seconds": 0.8464703499994357, + "phase": "search", + "missing_pids": [], + "workload_pss_bytes": 60766208, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 60766208, + "complete": true + }, + { + "elapsed_seconds": 0.933206911002344, + "phase": "search", + "missing_pids": [], + "workload_pss_bytes": 42420224, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 42420224, + "complete": true + }, + { + "elapsed_seconds": 1.0073068990022875, + "phase": "search", + "missing_pids": [], + "workload_pss_bytes": 61462528, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 61462528, + "complete": true + }, + { + "elapsed_seconds": 1.0795298459997866, + "phase": "search", + "missing_pids": [], + "workload_pss_bytes": 44981248, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 44981248, + "complete": true + }, + { + "elapsed_seconds": 1.1537017440023192, + "phase": "search", + "missing_pids": [], + "workload_pss_bytes": 61583360, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 61583360, + "complete": true + }, + { + "elapsed_seconds": 1.2255593150002824, + "phase": "search", + "missing_pids": [], + "workload_pss_bytes": 47498240, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 47498240, + "complete": true + }, + { + "elapsed_seconds": 1.2989146540021466, + "phase": "search", + "missing_pids": [], + "workload_pss_bytes": 42148864, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 42148864, + "complete": true + }, + { + "elapsed_seconds": 1.3280569700000342, + "phase": "search", + "missing_pids": [], + "workload_pss_bytes": 22459392, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 22459392, + "complete": true + }, + { + "elapsed_seconds": 1.4080660350009566, + "phase": "search", + "missing_pids": [], + "workload_pss_bytes": 22459392, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 22459392, + "complete": true + }, + { + "elapsed_seconds": 1.4884746140014613, + "phase": "search", + "missing_pids": [], + "workload_pss_bytes": 22459392, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 22459392, + "complete": true + }, + { + "elapsed_seconds": 1.5352750769998238, + "phase": "download", + "missing_pids": [], + "workload_pss_bytes": 31659008, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 31659008, + "complete": true + }, + { + "elapsed_seconds": 1.610968277000211, + "phase": "download", + "missing_pids": [], + "workload_pss_bytes": 31806464, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 31806464, + "complete": true + }, + { + "elapsed_seconds": 1.681868186002248, + "phase": "download", + "missing_pids": [], + "workload_pss_bytes": 31806464, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 31806464, + "complete": true + }, + { + "elapsed_seconds": 1.7548216030008916, + "phase": "download", + "missing_pids": [], + "workload_pss_bytes": 31810560, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 31810560, + "complete": true + }, + { + "elapsed_seconds": 1.8302660000008473, + "phase": "download", + "missing_pids": [], + "workload_pss_bytes": 31810560, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 31810560, + "complete": true + }, + { + "elapsed_seconds": 1.9131214059998456, + "phase": "download", + "missing_pids": [], + "workload_pss_bytes": 31810560, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 31810560, + "complete": true + }, + { + "elapsed_seconds": 1.9939416740016895, + "phase": "download", + "missing_pids": [], + "workload_pss_bytes": 31810560, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 31810560, + "complete": true + }, + { + "elapsed_seconds": 2.0745049489996745, + "phase": "download", + "missing_pids": [], + "workload_pss_bytes": 36706304, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 36706304, + "complete": true + }, + { + "elapsed_seconds": 2.1542616030019417, + "phase": "download", + "missing_pids": [], + "workload_pss_bytes": 36706304, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 36706304, + "complete": true + }, + { + "elapsed_seconds": 2.227102229000593, + "phase": "download", + "missing_pids": [], + "workload_pss_bytes": 35576832, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 35576832, + "complete": true + }, + { + "elapsed_seconds": 2.247419188002823, + "phase": "teardown", + "missing_pids": [], + "workload_pss_bytes": 35576832, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 35576832, + "complete": true + }, + { + "elapsed_seconds": 2.325937582001643, + "phase": "teardown", + "missing_pids": [], + "workload_pss_bytes": 35576832, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 35576832, + "complete": true + }, + { + "elapsed_seconds": 2.4095515590015566, + "phase": "teardown", + "missing_pids": [], + "workload_pss_bytes": 35576832, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 35576832, + "complete": true + }, + { + "elapsed_seconds": 2.492360832002305, + "phase": "teardown", + "missing_pids": [], + "workload_pss_bytes": 35576832, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 35576832, + "complete": true + }, + { + "elapsed_seconds": 2.5708922970006824, + "phase": "teardown", + "missing_pids": [], + "workload_pss_bytes": 35576832, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 35576832, + "complete": true + }, + { + "elapsed_seconds": 2.648385895001411, + "phase": "teardown", + "missing_pids": [], + "workload_pss_bytes": 35576832, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 35576832, + "complete": true + }, + { + "elapsed_seconds": 2.670051468001475, + "phase": "teardown", + "missing_pids": [ + 487093 + ], + "workload_pss_bytes": 0, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 0, + "complete": false + }, + { + "elapsed_seconds": 2.670157680000557, + "phase": "exited", + "missing_pids": [], + "workload_pss_bytes": 0, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 0, + "complete": true + } + ], + "events": [ + { + "phase": "idle" + }, + { + "phase": "search" + }, + { + "phase": "search", + "search_seconds": 0.8622720989988011, + "result_count": 1200 + }, + { + "phase": "download" + }, + { + "phase": "download", + "download_seconds": 0.7026336640010413, + "payload_bytes": 4194304, + "sha256": "2b07811057df887086f06a67edc6ebf911de8b6741156e7a2eb1416a4b8b1b2e", + "libtorrent_version": "2.0.11.0" + }, + { + "phase": "teardown" + } + ], + "summary": { + "download": { + "sample_count": 10, + "incomplete_samples": 0, + "workload_pss_bytes": { + "median": 31810560.0, + "peak": 36706304 + }, + "attached_stack_pss_bytes": { + "median": 0.0, + "peak": 0 + }, + "engine_pss_bytes": { + "median": 0.0, + "peak": 0 + }, + "accounted_pss_bytes": { + "median": 31810560.0, + "peak": 36706304 + } + }, + "exited": { + "sample_count": 1, + "incomplete_samples": 0, + "workload_pss_bytes": { + "median": 0, + "peak": 0 + }, + "attached_stack_pss_bytes": { + "median": 0, + "peak": 0 + }, + "engine_pss_bytes": { + "median": 0, + "peak": 0 + }, + "accounted_pss_bytes": { + "median": 0, + "peak": 0 + } + }, + "idle": { + "sample_count": 6, + "incomplete_samples": 0, + "workload_pss_bytes": { + "median": 21517312.0, + "peak": 21675008 + }, + "attached_stack_pss_bytes": { + "median": 0.0, + "peak": 0 + }, + "engine_pss_bytes": { + "median": 0.0, + "peak": 0 + }, + "accounted_pss_bytes": { + "median": 21517312.0, + "peak": 21675008 + } + }, + "search": { + "sample_count": 15, + "incomplete_samples": 0, + "workload_pss_bytes": { + "median": 42420224, + "peak": 61583360 + }, + "attached_stack_pss_bytes": { + "median": 0, + "peak": 0 + }, + "engine_pss_bytes": { + "median": 0, + "peak": 0 + }, + "accounted_pss_bytes": { + "median": 42420224, + "peak": 61583360 + } + }, + "teardown": { + "sample_count": 7, + "incomplete_samples": 1, + "workload_pss_bytes": { + "median": 35576832.0, + "peak": 35576832 + }, + "attached_stack_pss_bytes": { + "median": 0.0, + "peak": 0 + }, + "engine_pss_bytes": { + "median": 0.0, + "peak": 0 + }, + "accounted_pss_bytes": { + "median": 35576832.0, + "peak": 35576832 + } + } + } + }, + { + "samples": [ + { + "elapsed_seconds": 0.0712286439993477, + "phase": "startup", + "missing_pids": [], + "workload_pss_bytes": 15787008, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 15787008, + "complete": true + }, + { + "elapsed_seconds": 0.1286699199990835, + "phase": "idle", + "missing_pids": [], + "workload_pss_bytes": 21502976, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 21502976, + "complete": true + }, + { + "elapsed_seconds": 0.2107391319987073, + "phase": "idle", + "missing_pids": [], + "workload_pss_bytes": 21502976, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 21502976, + "complete": true + }, + { + "elapsed_seconds": 0.2818443729993305, + "phase": "idle", + "missing_pids": [], + "workload_pss_bytes": 21502976, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 21502976, + "complete": true + }, + { + "elapsed_seconds": 0.3602309689995309, + "phase": "idle", + "missing_pids": [], + "workload_pss_bytes": 21502976, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 21502976, + "complete": true + }, + { + "elapsed_seconds": 0.4390003349981271, + "phase": "idle", + "missing_pids": [], + "workload_pss_bytes": 21502976, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 21502976, + "complete": true + }, + { + "elapsed_seconds": 0.5200478749975446, + "phase": "idle", + "missing_pids": [], + "workload_pss_bytes": 21651456, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 21651456, + "complete": true + }, + { + "elapsed_seconds": 0.5407644689985318, + "phase": "search", + "missing_pids": [], + "workload_pss_bytes": 36822016, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 36822016, + "complete": true + }, + { + "elapsed_seconds": 0.6115623500008951, + "phase": "search", + "missing_pids": [], + "workload_pss_bytes": 59002880, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 59002880, + "complete": true + }, + { + "elapsed_seconds": 0.6815234419991612, + "phase": "search", + "missing_pids": [], + "workload_pss_bytes": 37175296, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 37175296, + "complete": true + }, + { + "elapsed_seconds": 0.7532711569983803, + "phase": "search", + "missing_pids": [], + "workload_pss_bytes": 59341824, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 59341824, + "complete": true + }, + { + "elapsed_seconds": 0.8247592309999163, + "phase": "search", + "missing_pids": [], + "workload_pss_bytes": 37870592, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 37870592, + "complete": true + }, + { + "elapsed_seconds": 0.8972130639995157, + "phase": "search", + "missing_pids": [], + "workload_pss_bytes": 60341248, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 60341248, + "complete": true + }, + { + "elapsed_seconds": 0.9854637600001297, + "phase": "search", + "missing_pids": [], + "workload_pss_bytes": 42741760, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 42741760, + "complete": true + }, + { + "elapsed_seconds": 1.071560327000043, + "phase": "search", + "missing_pids": [ + 487289 + ], + "workload_pss_bytes": 41971712, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 41971712, + "complete": false + }, + { + "elapsed_seconds": 1.145116486997722, + "phase": "search", + "missing_pids": [], + "workload_pss_bytes": 46352384, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 46352384, + "complete": true + }, + { + "elapsed_seconds": 1.218326538997644, + "phase": "search", + "missing_pids": [], + "workload_pss_bytes": 42038272, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 42038272, + "complete": true + }, + { + "elapsed_seconds": 1.2918193549994612, + "phase": "search", + "missing_pids": [], + "workload_pss_bytes": 49635328, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 49635328, + "complete": true + }, + { + "elapsed_seconds": 1.3642784679977922, + "phase": "search", + "missing_pids": [], + "workload_pss_bytes": 41114624, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 41114624, + "complete": true + }, + { + "elapsed_seconds": 1.3848024899998563, + "phase": "search", + "missing_pids": [], + "workload_pss_bytes": 22443008, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 22443008, + "complete": true + }, + { + "elapsed_seconds": 1.458309019999433, + "phase": "search", + "missing_pids": [], + "workload_pss_bytes": 22443008, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 22443008, + "complete": true + }, + { + "elapsed_seconds": 1.5376905169978272, + "phase": "search", + "missing_pids": [], + "workload_pss_bytes": 22443008, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 22443008, + "complete": true + }, + { + "elapsed_seconds": 1.5910056610009633, + "phase": "download", + "missing_pids": [], + "workload_pss_bytes": 31036416, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 31036416, + "complete": true + }, + { + "elapsed_seconds": 1.6700555950010312, + "phase": "download", + "missing_pids": [], + "workload_pss_bytes": 31773696, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 31773696, + "complete": true + }, + { + "elapsed_seconds": 1.752809540997987, + "phase": "download", + "missing_pids": [], + "workload_pss_bytes": 31777792, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 31777792, + "complete": true + }, + { + "elapsed_seconds": 1.8338913269981276, + "phase": "download", + "missing_pids": [], + "workload_pss_bytes": 31777792, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 31777792, + "complete": true + }, + { + "elapsed_seconds": 1.91650424099862, + "phase": "download", + "missing_pids": [], + "workload_pss_bytes": 31777792, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 31777792, + "complete": true + }, + { + "elapsed_seconds": 1.9960613699986425, + "phase": "download", + "missing_pids": [], + "workload_pss_bytes": 31777792, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 31777792, + "complete": true + }, + { + "elapsed_seconds": 2.074894839999615, + "phase": "download", + "missing_pids": [], + "workload_pss_bytes": 31777792, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 31777792, + "complete": true + }, + { + "elapsed_seconds": 2.1458404479999444, + "phase": "download", + "missing_pids": [], + "workload_pss_bytes": 36955136, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 36955136, + "complete": true + }, + { + "elapsed_seconds": 2.227262508000422, + "phase": "download", + "missing_pids": [], + "workload_pss_bytes": 36955136, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 36955136, + "complete": true + }, + { + "elapsed_seconds": 2.284638929999346, + "phase": "download", + "missing_pids": [], + "workload_pss_bytes": 35782656, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 35782656, + "complete": true + }, + { + "elapsed_seconds": 2.304537034000532, + "phase": "teardown", + "missing_pids": [], + "workload_pss_bytes": 35782656, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 35782656, + "complete": true + }, + { + "elapsed_seconds": 2.384560872000293, + "phase": "teardown", + "missing_pids": [], + "workload_pss_bytes": 35782656, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 35782656, + "complete": true + }, + { + "elapsed_seconds": 2.464561123000749, + "phase": "teardown", + "missing_pids": [], + "workload_pss_bytes": 35782656, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 35782656, + "complete": true + }, + { + "elapsed_seconds": 2.5440147490007803, + "phase": "teardown", + "missing_pids": [], + "workload_pss_bytes": 35782656, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 35782656, + "complete": true + }, + { + "elapsed_seconds": 2.625217447999603, + "phase": "teardown", + "missing_pids": [], + "workload_pss_bytes": 35782656, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 35782656, + "complete": true + }, + { + "elapsed_seconds": 2.7036778529982257, + "phase": "teardown", + "missing_pids": [], + "workload_pss_bytes": 35782656, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 35782656, + "complete": true + }, + { + "elapsed_seconds": 2.7262317659988184, + "phase": "teardown", + "missing_pids": [ + 487276 + ], + "workload_pss_bytes": 0, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 0, + "complete": false + }, + { + "elapsed_seconds": 2.7263362310004595, + "phase": "exited", + "missing_pids": [], + "workload_pss_bytes": 0, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 0, + "complete": true + } + ], + "events": [ + { + "phase": "idle" + }, + { + "phase": "search" + }, + { + "phase": "search", + "search_seconds": 0.857438140999875, + "result_count": 1200 + }, + { + "phase": "download" + }, + { + "phase": "download", + "download_seconds": 0.6978758050026954, + "payload_bytes": 4194304, + "sha256": "2b07811057df887086f06a67edc6ebf911de8b6741156e7a2eb1416a4b8b1b2e", + "libtorrent_version": "2.0.11.0" + }, + { + "phase": "teardown" + } + ], + "summary": { + "download": { + "sample_count": 10, + "incomplete_samples": 0, + "workload_pss_bytes": { + "median": 31777792.0, + "peak": 36955136 + }, + "attached_stack_pss_bytes": { + "median": 0.0, + "peak": 0 + }, + "engine_pss_bytes": { + "median": 0.0, + "peak": 0 + }, + "accounted_pss_bytes": { + "median": 31777792.0, + "peak": 36955136 + } + }, + "exited": { + "sample_count": 1, + "incomplete_samples": 0, + "workload_pss_bytes": { + "median": 0, + "peak": 0 + }, + "attached_stack_pss_bytes": { + "median": 0, + "peak": 0 + }, + "engine_pss_bytes": { + "median": 0, + "peak": 0 + }, + "accounted_pss_bytes": { + "median": 0, + "peak": 0 + } + }, + "idle": { + "sample_count": 6, + "incomplete_samples": 0, + "workload_pss_bytes": { + "median": 21502976.0, + "peak": 21651456 + }, + "attached_stack_pss_bytes": { + "median": 0.0, + "peak": 0 + }, + "engine_pss_bytes": { + "median": 0.0, + "peak": 0 + }, + "accounted_pss_bytes": { + "median": 21502976.0, + "peak": 21651456 + } + }, + "search": { + "sample_count": 15, + "incomplete_samples": 1, + "workload_pss_bytes": { + "median": 41576448.0, + "peak": 60341248 + }, + "attached_stack_pss_bytes": { + "median": 0.0, + "peak": 0 + }, + "engine_pss_bytes": { + "median": 0.0, + "peak": 0 + }, + "accounted_pss_bytes": { + "median": 41576448.0, + "peak": 60341248 + } + }, + "startup": { + "sample_count": 1, + "incomplete_samples": 0, + "workload_pss_bytes": { + "median": 15787008, + "peak": 15787008 + }, + "attached_stack_pss_bytes": { + "median": 0, + "peak": 0 + }, + "engine_pss_bytes": { + "median": 0, + "peak": 0 + }, + "accounted_pss_bytes": { + "median": 15787008, + "peak": 15787008 + } + }, + "teardown": { + "sample_count": 7, + "incomplete_samples": 1, + "workload_pss_bytes": { + "median": 35782656.0, + "peak": 35782656 + }, + "attached_stack_pss_bytes": { + "median": 0.0, + "peak": 0 + }, + "engine_pss_bytes": { + "median": 0.0, + "peak": 0 + }, + "accounted_pss_bytes": { + "median": 35782656.0, + "peak": 35782656 + } + } + } + }, + { + "samples": [ + { + "elapsed_seconds": 0.07096441300018341, + "phase": "startup", + "missing_pids": [], + "workload_pss_bytes": 15865856, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 15865856, + "complete": true + }, + { + "elapsed_seconds": 0.12601515500136884, + "phase": "idle", + "missing_pids": [], + "workload_pss_bytes": 21513216, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 21513216, + "complete": true + }, + { + "elapsed_seconds": 0.20390585200220812, + "phase": "idle", + "missing_pids": [], + "workload_pss_bytes": 21513216, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 21513216, + "complete": true + }, + { + "elapsed_seconds": 0.281711757001176, + "phase": "idle", + "missing_pids": [], + "workload_pss_bytes": 21513216, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 21513216, + "complete": true + }, + { + "elapsed_seconds": 0.3600638220013934, + "phase": "idle", + "missing_pids": [], + "workload_pss_bytes": 21513216, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 21513216, + "complete": true + }, + { + "elapsed_seconds": 0.4399710670004424, + "phase": "idle", + "missing_pids": [], + "workload_pss_bytes": 21513216, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 21513216, + "complete": true + }, + { + "elapsed_seconds": 0.5165593929996248, + "phase": "idle", + "missing_pids": [], + "workload_pss_bytes": 21657600, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 21657600, + "complete": true + }, + { + "elapsed_seconds": 0.537156127000344, + "phase": "search", + "missing_pids": [], + "workload_pss_bytes": 36843520, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 36843520, + "complete": true + }, + { + "elapsed_seconds": 0.6097267559998727, + "phase": "search", + "missing_pids": [], + "workload_pss_bytes": 59238400, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 59238400, + "complete": true + }, + { + "elapsed_seconds": 0.6800862900017819, + "phase": "search", + "missing_pids": [], + "workload_pss_bytes": 37471232, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 37471232, + "complete": true + }, + { + "elapsed_seconds": 0.7509184129994537, + "phase": "search", + "missing_pids": [], + "workload_pss_bytes": 60387328, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 60387328, + "complete": true + }, + { + "elapsed_seconds": 0.8214912969997386, + "phase": "search", + "missing_pids": [], + "workload_pss_bytes": 38025216, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 38025216, + "complete": true + }, + { + "elapsed_seconds": 0.8937390210012381, + "phase": "search", + "missing_pids": [], + "workload_pss_bytes": 60463104, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 60463104, + "complete": true + }, + { + "elapsed_seconds": 0.9684438229996886, + "phase": "search", + "missing_pids": [], + "workload_pss_bytes": 39627776, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 39627776, + "complete": true + }, + { + "elapsed_seconds": 1.0406096680017072, + "phase": "search", + "missing_pids": [], + "workload_pss_bytes": 61414400, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 61414400, + "complete": true + }, + { + "elapsed_seconds": 1.116629455002112, + "phase": "search", + "missing_pids": [], + "workload_pss_bytes": 40635392, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 40635392, + "complete": true + }, + { + "elapsed_seconds": 1.1883584720017097, + "phase": "search", + "missing_pids": [], + "workload_pss_bytes": 61379584, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 61379584, + "complete": true + }, + { + "elapsed_seconds": 1.2591324230015744, + "phase": "search", + "missing_pids": [], + "workload_pss_bytes": 39651328, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 39651328, + "complete": true + }, + { + "elapsed_seconds": 1.3320004100023652, + "phase": "search", + "missing_pids": [], + "workload_pss_bytes": 60781568, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 60781568, + "complete": true + }, + { + "elapsed_seconds": 1.3883087400026852, + "phase": "search", + "missing_pids": [], + "workload_pss_bytes": 22449152, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 22449152, + "complete": true + }, + { + "elapsed_seconds": 1.4665419110024231, + "phase": "search", + "missing_pids": [], + "workload_pss_bytes": 22449152, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 22449152, + "complete": true + }, + { + "elapsed_seconds": 1.5471739000022353, + "phase": "search", + "missing_pids": [], + "workload_pss_bytes": 22449152, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 22449152, + "complete": true + }, + { + "elapsed_seconds": 1.594360418002907, + "phase": "download", + "missing_pids": [], + "workload_pss_bytes": 30651392, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 30651392, + "complete": true + }, + { + "elapsed_seconds": 1.6751941920010722, + "phase": "download", + "missing_pids": [], + "workload_pss_bytes": 31759360, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 31759360, + "complete": true + }, + { + "elapsed_seconds": 1.755599036001513, + "phase": "download", + "missing_pids": [], + "workload_pss_bytes": 31763456, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 31763456, + "complete": true + }, + { + "elapsed_seconds": 1.8347107610024977, + "phase": "download", + "missing_pids": [], + "workload_pss_bytes": 31763456, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 31763456, + "complete": true + }, + { + "elapsed_seconds": 1.915186303001974, + "phase": "download", + "missing_pids": [], + "workload_pss_bytes": 31763456, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 31763456, + "complete": true + }, + { + "elapsed_seconds": 1.9958517410013883, + "phase": "download", + "missing_pids": [], + "workload_pss_bytes": 31763456, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 31763456, + "complete": true + }, + { + "elapsed_seconds": 2.0769097369993688, + "phase": "download", + "missing_pids": [], + "workload_pss_bytes": 31763456, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 31763456, + "complete": true + }, + { + "elapsed_seconds": 2.1468129420027253, + "phase": "download", + "missing_pids": [], + "workload_pss_bytes": 40639488, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 40639488, + "complete": true + }, + { + "elapsed_seconds": 2.2173203420024947, + "phase": "download", + "missing_pids": [], + "workload_pss_bytes": 36772864, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 36772864, + "complete": true + }, + { + "elapsed_seconds": 2.295689038001001, + "phase": "download", + "missing_pids": [], + "workload_pss_bytes": 36772864, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 36772864, + "complete": true + }, + { + "elapsed_seconds": 2.332615777999308, + "phase": "download", + "missing_pids": [], + "workload_pss_bytes": 35615744, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 35615744, + "complete": true + }, + { + "elapsed_seconds": 2.350792301000183, + "phase": "teardown", + "missing_pids": [], + "workload_pss_bytes": 35615744, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 35615744, + "complete": true + }, + { + "elapsed_seconds": 2.429585579000559, + "phase": "teardown", + "missing_pids": [], + "workload_pss_bytes": 35615744, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 35615744, + "complete": true + }, + { + "elapsed_seconds": 2.5002585100010037, + "phase": "teardown", + "missing_pids": [], + "workload_pss_bytes": 35615744, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 35615744, + "complete": true + }, + { + "elapsed_seconds": 2.5742764380011067, + "phase": "teardown", + "missing_pids": [], + "workload_pss_bytes": 35615744, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 35615744, + "complete": true + }, + { + "elapsed_seconds": 2.643604483000672, + "phase": "teardown", + "missing_pids": [], + "workload_pss_bytes": 35615744, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 35615744, + "complete": true + }, + { + "elapsed_seconds": 2.712455823999335, + "phase": "teardown", + "missing_pids": [], + "workload_pss_bytes": 35615744, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 35615744, + "complete": true + }, + { + "elapsed_seconds": 2.7651638070019544, + "phase": "teardown", + "missing_pids": [ + 487330 + ], + "workload_pss_bytes": 0, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 0, + "complete": false + }, + { + "elapsed_seconds": 2.7652855010019266, + "phase": "exited", + "missing_pids": [], + "workload_pss_bytes": 0, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 0, + "complete": true + } + ], + "events": [ + { + "phase": "idle" + }, + { + "phase": "search" + }, + { + "phase": "search", + "search_seconds": 0.8636252059986873, + "result_count": 1200 + }, + { + "phase": "download" + }, + { + "phase": "download", + "download_seconds": 0.7427955219973228, + "payload_bytes": 4194304, + "sha256": "2b07811057df887086f06a67edc6ebf911de8b6741156e7a2eb1416a4b8b1b2e", + "libtorrent_version": "2.0.11.0" + }, + { + "phase": "teardown" + } + ], + "summary": { + "download": { + "sample_count": 11, + "incomplete_samples": 0, + "workload_pss_bytes": { + "median": 31763456, + "peak": 40639488 + }, + "attached_stack_pss_bytes": { + "median": 0, + "peak": 0 + }, + "engine_pss_bytes": { + "median": 0, + "peak": 0 + }, + "accounted_pss_bytes": { + "median": 31763456, + "peak": 40639488 + } + }, + "exited": { + "sample_count": 1, + "incomplete_samples": 0, + "workload_pss_bytes": { + "median": 0, + "peak": 0 + }, + "attached_stack_pss_bytes": { + "median": 0, + "peak": 0 + }, + "engine_pss_bytes": { + "median": 0, + "peak": 0 + }, + "accounted_pss_bytes": { + "median": 0, + "peak": 0 + } + }, + "idle": { + "sample_count": 6, + "incomplete_samples": 0, + "workload_pss_bytes": { + "median": 21513216.0, + "peak": 21657600 + }, + "attached_stack_pss_bytes": { + "median": 0.0, + "peak": 0 + }, + "engine_pss_bytes": { + "median": 0.0, + "peak": 0 + }, + "accounted_pss_bytes": { + "median": 21513216.0, + "peak": 21657600 + } + }, + "search": { + "sample_count": 15, + "incomplete_samples": 0, + "workload_pss_bytes": { + "median": 39651328, + "peak": 61414400 + }, + "attached_stack_pss_bytes": { + "median": 0, + "peak": 0 + }, + "engine_pss_bytes": { + "median": 0, + "peak": 0 + }, + "accounted_pss_bytes": { + "median": 39651328, + "peak": 61414400 + } + }, + "startup": { + "sample_count": 1, + "incomplete_samples": 0, + "workload_pss_bytes": { + "median": 15865856, + "peak": 15865856 + }, + "attached_stack_pss_bytes": { + "median": 0, + "peak": 0 + }, + "engine_pss_bytes": { + "median": 0, + "peak": 0 + }, + "accounted_pss_bytes": { + "median": 15865856, + "peak": 15865856 + } + }, + "teardown": { + "sample_count": 7, + "incomplete_samples": 1, + "workload_pss_bytes": { + "median": 35615744.0, + "peak": 35615744 + }, + "attached_stack_pss_bytes": { + "median": 0.0, + "peak": 0 + }, + "engine_pss_bytes": { + "median": 0.0, + "peak": 0 + }, + "accounted_pss_bytes": { + "median": 35615744.0, + "peak": 35615744 + } + } + } + } + ] +} diff --git a/docs/benchmarks/local-loopback.json b/docs/benchmarks/local-loopback.json new file mode 100644 index 0000000..951c146 --- /dev/null +++ b/docs/benchmarks/local-loopback.json @@ -0,0 +1,1541 @@ +{ + "schema_version": 1, + "mode": "local_fixture_search_and_loopback_bittorrent", + "metric": "PSS bytes; same metric for every component", + "environment": { + "platform": "Linux-7.2.11-200.fc44.x86_64-x86_64-with-glibc2.43", + "python": "3.14.8 (main, Oct 1 2026, 00:00:00) [GCC 16.2.1 20260819 (Red Hat 16.2.1-2)]", + "cpu_count": 8, + "cpu_model": "11th Gen Intel(R) Core(TM) i5-1135G7 @ 2.40GHz", + "source_sha256": { + "__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "cli.py": "1d826809006ec312575cc34d3e0876b50cfae043121e83a61bbb4d6446d475d9", + "core/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "core/benchmark.py": "d3b790f5f5f3e56bac21f60c64b8a245bfaed2c9387d2f9ae142f02dd4c51518", + "core/config_manager.py": "6f71069e1544145b5ab2c324326df1f7d75250ec4bba4d5361e60c8251e5686c", + "core/config_wizard.py": "d3303501145dad0e49dd19c6e6153c19a039b0e479a14f72ead24ededfb8f6c0", + "core/http.py": "3d36d9d66e954610b0b8e925251af38959d1c7e606ebdcdbfd5501ba03c6f344", + "core/indexer_manager.py": "1435e21114ff5de6da67e084a13103b8cd25bbe91367f118d75fb5c95c130472", + "core/init_env.py": "f8eab6975fc5c7ce2b6b86658eeb7eb3feb36bd70d95f0204cd285c5ae7f330c", + "core/lite_downloader.py": "064f39174a24d6113c1cfd56f064e247ed40642ae3d080640b4f35f565c6dc63", + "core/lite_fetcher.py": "dd7505d13c6107347ec962c7e1868b79112992800b8873d47691cfdb8dbe2e36", + "core/lite_plugin_loader.py": "419dea428158a28314a7a192cabd88e54b078d8542258db243bbad2c2f141b0d", + "core/logger.py": "fba54c1264da77f2faf8fa5b6fc3df66fecd5e01d6f8be52fdd4edca202106bf", + "core/oneshot.py": "e1ac659d8e95f39c11da837d3bc6cd101a8949a7c41cfe2b322c6f6b963dac8e", + "core/qbittorrent_client.py": "7a412585b4f0b056a43b4040cba95b00e12ba0de0ae395d91590aa0bb3a36276", + "core/rss_fetcher.py": "9b3f508ab7add45b99bba9526679ae21063d75fa04728eb97ba7a8cf82e426a7", + "core/search_runner.py": "782a28401bafd86e9e38b77afd8f50cd241c2f0d2f9f30371e08f3b2efcb96fd", + "core/secret_manager.py": "2d9a15ad2483fe3976c05dccc76f9814f6df0dbeb2e9cd943f47c85f17ec02ee", + "core/torrent_filter.py": "662daedbbafbb4197ac8e9aec68b033001f9317b8745aa92741d52e7da9934a0", + "plugins/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "plugins/bitsearch.py": "4a648f04b729a6556036ca5ee830c3db4a85b492a9d6e9524e7c38864a062a4f", + "plugins/bittorrented.py": "1077d397916be8c83471db61a2733426417119109bf53694bd2dd22b34fe9873", + "plugins/eztv.py": "8576d0f09636ef1da55024fcdab7212f4c9627d339fbc6657fce573823e6e6b0", + "plugins/helpers.py": "9af508d98875f399e98ee60428153cec41140b41a0bc8c2da23ca743a4e81556", + "plugins/limetorrents.py": "60f8f6321664108875accd2585a8d51e4fbf5fb5c88d63d3ec8733a6ad1aa68a", + "plugins/novaprinter.py": "a3193175bd64d9517d368ff4ba70d2c56d85011d18d8f196c82ff308e8cc685e", + "plugins/piratebay.py": "21f760eac8d931ac25dc05a79654f14313a30d48d81f878e857a25f4e226bc3f", + "plugins/subsplease.py": "4117d2cd8f58e9ace19c5d9287f1b2307fab0d32a6fc15898f3e6ef75c37f402", + "plugins/torlock.py": "2d818ddda16c4e150878be63c0b0ff03f2e746bef73e8a86e38758366d235071", + "plugins/torrentproject.py": "1f8c5be60357f1d4baf4ba2722aa316e5bdd50324209f8b22aa902a6abad4c86", + "plugins/x1337.py": "29dbdd5c57b95e7750b20b5bd8cfdb324dc6e3db8cde5e9005e4f5295157b581", + "plugins/yts.py": "fdd2e0236aacf0e43cdf2a43abd16ee33fdb5f736de84ed357afb54a9c1df0fe", + "ui/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "ui/colors.py": "192984be5f757359e15eb93ce1cd71083d257538199d8567dd5d9501a7481f37", + "ui/tui.py": "06a59767dfdbfc55876866e2e18d471430e56055ca232a8fc7360a893ef2ee2e" + }, + "cgroup_version": 2, + "revision": "f61d816128b4c98ee012fb9981e441852b758f2d", + "dirty": true + }, + "interval_seconds": 0.05, + "payload_bytes": 4194304, + "fixture_plugins": 12, + "fixture_results_per_plugin": 100, + "search_workers": 6, + "attachment": null, + "include_engine": false, + "limitations": [ + "Fixture search is offline; not a live indexer latency measurement", + "Download uses generated content and loopback peers; not internet swarm performance", + "PSS excludes filesystem cache and kernel/container networking allocations", + "Engine processes are whole-host shared costs when included", + "Attached stack is sampled read-only; its lifecycle is not exercised" + ], + "trials": [ + { + "samples": [ + { + "elapsed_seconds": 0.07038233800267335, + "phase": "idle", + "missing_pids": [], + "workload_pss_bytes": 21508096, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 21508096, + "complete": true + }, + { + "elapsed_seconds": 0.14778174499952001, + "phase": "idle", + "missing_pids": [], + "workload_pss_bytes": 21508096, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 21508096, + "complete": true + }, + { + "elapsed_seconds": 0.2286627169996791, + "phase": "idle", + "missing_pids": [], + "workload_pss_bytes": 21508096, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 21508096, + "complete": true + }, + { + "elapsed_seconds": 0.3003016780021426, + "phase": "idle", + "missing_pids": [], + "workload_pss_bytes": 21508096, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 21508096, + "complete": true + }, + { + "elapsed_seconds": 0.37721200099986163, + "phase": "idle", + "missing_pids": [], + "workload_pss_bytes": 21508096, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 21508096, + "complete": true + }, + { + "elapsed_seconds": 0.4655202920002921, + "phase": "idle", + "missing_pids": [], + "workload_pss_bytes": 21920768, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 21920768, + "complete": true + }, + { + "elapsed_seconds": 0.5093156809998618, + "phase": "search", + "missing_pids": [], + "workload_pss_bytes": 73128960, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 73128960, + "complete": true + }, + { + "elapsed_seconds": 0.6065068900024926, + "phase": "search", + "missing_pids": [], + "workload_pss_bytes": 130493440, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 130493440, + "complete": true + }, + { + "elapsed_seconds": 0.7007851300004404, + "phase": "search", + "missing_pids": [ + 486800 + ], + "workload_pss_bytes": 70177792, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 70177792, + "complete": false + }, + { + "elapsed_seconds": 0.8104036229997291, + "phase": "search", + "missing_pids": [], + "workload_pss_bytes": 97222656, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 97222656, + "complete": true + }, + { + "elapsed_seconds": 0.9141798080017907, + "phase": "search", + "missing_pids": [], + "workload_pss_bytes": 120409088, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 120409088, + "complete": true + }, + { + "elapsed_seconds": 0.9873015400007716, + "phase": "search", + "missing_pids": [], + "workload_pss_bytes": 23085056, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 23085056, + "complete": true + }, + { + "elapsed_seconds": 1.0085570660012309, + "phase": "search", + "missing_pids": [], + "workload_pss_bytes": 23085056, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 23085056, + "complete": true + }, + { + "elapsed_seconds": 1.098545720000402, + "phase": "search", + "missing_pids": [], + "workload_pss_bytes": 23085056, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 23085056, + "complete": true + }, + { + "elapsed_seconds": 1.1699812070000917, + "phase": "search", + "missing_pids": [], + "workload_pss_bytes": 23085056, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 23085056, + "complete": true + }, + { + "elapsed_seconds": 1.1900661630024842, + "phase": "download", + "missing_pids": [], + "workload_pss_bytes": 31170560, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 31170560, + "complete": true + }, + { + "elapsed_seconds": 1.2686971770017408, + "phase": "download", + "missing_pids": [], + "workload_pss_bytes": 32350208, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 32350208, + "complete": true + }, + { + "elapsed_seconds": 1.3493952540011378, + "phase": "download", + "missing_pids": [], + "workload_pss_bytes": 32350208, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 32350208, + "complete": true + }, + { + "elapsed_seconds": 1.4320330030022888, + "phase": "download", + "missing_pids": [], + "workload_pss_bytes": 32350208, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 32350208, + "complete": true + }, + { + "elapsed_seconds": 1.5117791539996688, + "phase": "download", + "missing_pids": [], + "workload_pss_bytes": 32350208, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 32350208, + "complete": true + }, + { + "elapsed_seconds": 1.590676130999782, + "phase": "download", + "missing_pids": [], + "workload_pss_bytes": 32350208, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 32350208, + "complete": true + }, + { + "elapsed_seconds": 1.6699442130011448, + "phase": "download", + "missing_pids": [], + "workload_pss_bytes": 32350208, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 32350208, + "complete": true + }, + { + "elapsed_seconds": 1.7409703260018432, + "phase": "download", + "missing_pids": [], + "workload_pss_bytes": 41086976, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 41086976, + "complete": true + }, + { + "elapsed_seconds": 1.8116160410027078, + "phase": "download", + "missing_pids": [], + "workload_pss_bytes": 37220352, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 37220352, + "complete": true + }, + { + "elapsed_seconds": 1.8904158920013288, + "phase": "download", + "missing_pids": [], + "workload_pss_bytes": 37220352, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 37220352, + "complete": true + }, + { + "elapsed_seconds": 1.9299406019999878, + "phase": "download", + "missing_pids": [], + "workload_pss_bytes": 36088832, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 36088832, + "complete": true + }, + { + "elapsed_seconds": 1.951109441000881, + "phase": "teardown", + "missing_pids": [], + "workload_pss_bytes": 36088832, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 36088832, + "complete": true + }, + { + "elapsed_seconds": 2.0309728810025263, + "phase": "teardown", + "missing_pids": [], + "workload_pss_bytes": 36088832, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 36088832, + "complete": true + }, + { + "elapsed_seconds": 2.111628995000501, + "phase": "teardown", + "missing_pids": [], + "workload_pss_bytes": 36088832, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 36088832, + "complete": true + }, + { + "elapsed_seconds": 2.1824069489994145, + "phase": "teardown", + "missing_pids": [], + "workload_pss_bytes": 36088832, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 36088832, + "complete": true + }, + { + "elapsed_seconds": 2.254395582000143, + "phase": "teardown", + "missing_pids": [], + "workload_pss_bytes": 36088832, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 36088832, + "complete": true + }, + { + "elapsed_seconds": 2.3441446640026697, + "phase": "teardown", + "missing_pids": [], + "workload_pss_bytes": 36088832, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 36088832, + "complete": true + }, + { + "elapsed_seconds": 2.3717891260021133, + "phase": "teardown", + "missing_pids": [ + 486789 + ], + "workload_pss_bytes": 0, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 0, + "complete": false + }, + { + "elapsed_seconds": 2.3719078390022332, + "phase": "exited", + "missing_pids": [], + "workload_pss_bytes": 0, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 0, + "complete": true + } + ], + "events": [ + { + "phase": "idle" + }, + { + "phase": "search" + }, + { + "phase": "search", + "search_seconds": 0.5238802590029081, + "result_count": 1200 + }, + { + "phase": "download" + }, + { + "phase": "download", + "download_seconds": 0.7401260299993737, + "payload_bytes": 4194304, + "sha256": "2b07811057df887086f06a67edc6ebf911de8b6741156e7a2eb1416a4b8b1b2e", + "libtorrent_version": "2.0.11.0" + }, + { + "phase": "teardown" + } + ], + "summary": { + "download": { + "sample_count": 11, + "incomplete_samples": 0, + "workload_pss_bytes": { + "median": 32350208, + "peak": 41086976 + }, + "attached_stack_pss_bytes": { + "median": 0, + "peak": 0 + }, + "engine_pss_bytes": { + "median": 0, + "peak": 0 + }, + "accounted_pss_bytes": { + "median": 32350208, + "peak": 41086976 + } + }, + "exited": { + "sample_count": 1, + "incomplete_samples": 0, + "workload_pss_bytes": { + "median": 0, + "peak": 0 + }, + "attached_stack_pss_bytes": { + "median": 0, + "peak": 0 + }, + "engine_pss_bytes": { + "median": 0, + "peak": 0 + }, + "accounted_pss_bytes": { + "median": 0, + "peak": 0 + } + }, + "idle": { + "sample_count": 6, + "incomplete_samples": 0, + "workload_pss_bytes": { + "median": 21508096.0, + "peak": 21920768 + }, + "attached_stack_pss_bytes": { + "median": 0.0, + "peak": 0 + }, + "engine_pss_bytes": { + "median": 0.0, + "peak": 0 + }, + "accounted_pss_bytes": { + "median": 21508096.0, + "peak": 21920768 + } + }, + "search": { + "sample_count": 9, + "incomplete_samples": 1, + "workload_pss_bytes": { + "median": 48107008.0, + "peak": 130493440 + }, + "attached_stack_pss_bytes": { + "median": 0.0, + "peak": 0 + }, + "engine_pss_bytes": { + "median": 0.0, + "peak": 0 + }, + "accounted_pss_bytes": { + "median": 48107008.0, + "peak": 130493440 + } + }, + "teardown": { + "sample_count": 7, + "incomplete_samples": 1, + "workload_pss_bytes": { + "median": 36088832.0, + "peak": 36088832 + }, + "attached_stack_pss_bytes": { + "median": 0.0, + "peak": 0 + }, + "engine_pss_bytes": { + "median": 0.0, + "peak": 0 + }, + "accounted_pss_bytes": { + "median": 36088832.0, + "peak": 36088832 + } + } + } + }, + { + "samples": [ + { + "elapsed_seconds": 0.07010188500134973, + "phase": "startup", + "missing_pids": [], + "workload_pss_bytes": 15449088, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 15449088, + "complete": true + }, + { + "elapsed_seconds": 0.12448766200031969, + "phase": "idle", + "missing_pids": [], + "workload_pss_bytes": 21510144, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 21510144, + "complete": true + }, + { + "elapsed_seconds": 0.20285765200242167, + "phase": "idle", + "missing_pids": [], + "workload_pss_bytes": 21510144, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 21510144, + "complete": true + }, + { + "elapsed_seconds": 0.28321206500186236, + "phase": "idle", + "missing_pids": [], + "workload_pss_bytes": 21510144, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 21510144, + "complete": true + }, + { + "elapsed_seconds": 0.36344261500198627, + "phase": "idle", + "missing_pids": [], + "workload_pss_bytes": 21510144, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 21510144, + "complete": true + }, + { + "elapsed_seconds": 0.4448951960002887, + "phase": "idle", + "missing_pids": [], + "workload_pss_bytes": 21510144, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 21510144, + "complete": true + }, + { + "elapsed_seconds": 0.5365223050030181, + "phase": "idle", + "missing_pids": [], + "workload_pss_bytes": 21923840, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 21923840, + "complete": true + }, + { + "elapsed_seconds": 0.5775535070024489, + "phase": "search", + "missing_pids": [], + "workload_pss_bytes": 76977152, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 76977152, + "complete": true + }, + { + "elapsed_seconds": 0.6747638400011056, + "phase": "search", + "missing_pids": [], + "workload_pss_bytes": 132692992, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 132692992, + "complete": true + }, + { + "elapsed_seconds": 0.7694636670021282, + "phase": "search", + "missing_pids": [], + "workload_pss_bytes": 42176512, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 42176512, + "complete": true + }, + { + "elapsed_seconds": 0.871314281001105, + "phase": "search", + "missing_pids": [], + "workload_pss_bytes": 112283648, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 112283648, + "complete": true + }, + { + "elapsed_seconds": 0.9494304170002579, + "phase": "search", + "missing_pids": [], + "workload_pss_bytes": 80750592, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 80750592, + "complete": true + }, + { + "elapsed_seconds": 1.0236169620002329, + "phase": "search", + "missing_pids": [], + "workload_pss_bytes": 23097344, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 23097344, + "complete": true + }, + { + "elapsed_seconds": 1.0431339720016695, + "phase": "search", + "missing_pids": [], + "workload_pss_bytes": 23097344, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 23097344, + "complete": true + }, + { + "elapsed_seconds": 1.1168462510031532, + "phase": "search", + "missing_pids": [], + "workload_pss_bytes": 23097344, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 23097344, + "complete": true + }, + { + "elapsed_seconds": 1.194869633000053, + "phase": "search", + "missing_pids": [], + "workload_pss_bytes": 23097344, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 23097344, + "complete": true + }, + { + "elapsed_seconds": 1.2263866339999367, + "phase": "download", + "missing_pids": [], + "workload_pss_bytes": 32305152, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 32305152, + "complete": true + }, + { + "elapsed_seconds": 1.3050885000011476, + "phase": "download", + "missing_pids": [], + "workload_pss_bytes": 32305152, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 32305152, + "complete": true + }, + { + "elapsed_seconds": 1.3844323700031964, + "phase": "download", + "missing_pids": [], + "workload_pss_bytes": 32305152, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 32305152, + "complete": true + }, + { + "elapsed_seconds": 1.4542761980010255, + "phase": "download", + "missing_pids": [], + "workload_pss_bytes": 32305152, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 32305152, + "complete": true + }, + { + "elapsed_seconds": 1.5265426060032041, + "phase": "download", + "missing_pids": [], + "workload_pss_bytes": 32305152, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 32305152, + "complete": true + }, + { + "elapsed_seconds": 1.5975691870007722, + "phase": "download", + "missing_pids": [], + "workload_pss_bytes": 32305152, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 32305152, + "complete": true + }, + { + "elapsed_seconds": 1.6748359630000778, + "phase": "download", + "missing_pids": [], + "workload_pss_bytes": 32305152, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 32305152, + "complete": true + }, + { + "elapsed_seconds": 1.7552270280029916, + "phase": "download", + "missing_pids": [], + "workload_pss_bytes": 37408768, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 37408768, + "complete": true + }, + { + "elapsed_seconds": 1.8357619930029614, + "phase": "download", + "missing_pids": [], + "workload_pss_bytes": 37408768, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 37408768, + "complete": true + }, + { + "elapsed_seconds": 1.914940528000443, + "phase": "download", + "missing_pids": [], + "workload_pss_bytes": 36222976, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 36222976, + "complete": true + }, + { + "elapsed_seconds": 1.935444261001976, + "phase": "teardown", + "missing_pids": [], + "workload_pss_bytes": 36222976, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 36222976, + "complete": true + }, + { + "elapsed_seconds": 2.013886499000364, + "phase": "teardown", + "missing_pids": [], + "workload_pss_bytes": 36222976, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 36222976, + "complete": true + }, + { + "elapsed_seconds": 2.085609989000659, + "phase": "teardown", + "missing_pids": [], + "workload_pss_bytes": 36222976, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 36222976, + "complete": true + }, + { + "elapsed_seconds": 2.1643509670029744, + "phase": "teardown", + "missing_pids": [], + "workload_pss_bytes": 36222976, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 36222976, + "complete": true + }, + { + "elapsed_seconds": 2.244721937000577, + "phase": "teardown", + "missing_pids": [], + "workload_pss_bytes": 36222976, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 36222976, + "complete": true + }, + { + "elapsed_seconds": 2.3160781920014415, + "phase": "teardown", + "missing_pids": [], + "workload_pss_bytes": 36222976, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 36222976, + "complete": true + }, + { + "elapsed_seconds": 2.362616837002861, + "phase": "teardown", + "missing_pids": [ + 486862 + ], + "workload_pss_bytes": 0, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 0, + "complete": false + }, + { + "elapsed_seconds": 2.3627234490013507, + "phase": "exited", + "missing_pids": [], + "workload_pss_bytes": 0, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 0, + "complete": true + } + ], + "events": [ + { + "phase": "idle" + }, + { + "phase": "search" + }, + { + "phase": "search", + "search_seconds": 0.4977558179998596, + "result_count": 1200 + }, + { + "phase": "download" + }, + { + "phase": "download", + "download_seconds": 0.6990966529992875, + "payload_bytes": 4194304, + "sha256": "2b07811057df887086f06a67edc6ebf911de8b6741156e7a2eb1416a4b8b1b2e", + "libtorrent_version": "2.0.11.0" + }, + { + "phase": "teardown" + } + ], + "summary": { + "download": { + "sample_count": 10, + "incomplete_samples": 0, + "workload_pss_bytes": { + "median": 32305152.0, + "peak": 37408768 + }, + "attached_stack_pss_bytes": { + "median": 0.0, + "peak": 0 + }, + "engine_pss_bytes": { + "median": 0.0, + "peak": 0 + }, + "accounted_pss_bytes": { + "median": 32305152.0, + "peak": 37408768 + } + }, + "exited": { + "sample_count": 1, + "incomplete_samples": 0, + "workload_pss_bytes": { + "median": 0, + "peak": 0 + }, + "attached_stack_pss_bytes": { + "median": 0, + "peak": 0 + }, + "engine_pss_bytes": { + "median": 0, + "peak": 0 + }, + "accounted_pss_bytes": { + "median": 0, + "peak": 0 + } + }, + "idle": { + "sample_count": 6, + "incomplete_samples": 0, + "workload_pss_bytes": { + "median": 21510144.0, + "peak": 21923840 + }, + "attached_stack_pss_bytes": { + "median": 0.0, + "peak": 0 + }, + "engine_pss_bytes": { + "median": 0.0, + "peak": 0 + }, + "accounted_pss_bytes": { + "median": 21510144.0, + "peak": 21923840 + } + }, + "search": { + "sample_count": 9, + "incomplete_samples": 0, + "workload_pss_bytes": { + "median": 42176512, + "peak": 132692992 + }, + "attached_stack_pss_bytes": { + "median": 0, + "peak": 0 + }, + "engine_pss_bytes": { + "median": 0, + "peak": 0 + }, + "accounted_pss_bytes": { + "median": 42176512, + "peak": 132692992 + } + }, + "startup": { + "sample_count": 1, + "incomplete_samples": 0, + "workload_pss_bytes": { + "median": 15449088, + "peak": 15449088 + }, + "attached_stack_pss_bytes": { + "median": 0, + "peak": 0 + }, + "engine_pss_bytes": { + "median": 0, + "peak": 0 + }, + "accounted_pss_bytes": { + "median": 15449088, + "peak": 15449088 + } + }, + "teardown": { + "sample_count": 7, + "incomplete_samples": 1, + "workload_pss_bytes": { + "median": 36222976.0, + "peak": 36222976 + }, + "attached_stack_pss_bytes": { + "median": 0.0, + "peak": 0 + }, + "engine_pss_bytes": { + "median": 0.0, + "peak": 0 + }, + "accounted_pss_bytes": { + "median": 36222976.0, + "peak": 36222976 + } + } + } + }, + { + "samples": [ + { + "elapsed_seconds": 0.07060354400164215, + "phase": "startup", + "missing_pids": [], + "workload_pss_bytes": 15432704, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 15432704, + "complete": true + }, + { + "elapsed_seconds": 0.14225364999947487, + "phase": "startup", + "missing_pids": [], + "workload_pss_bytes": 21507072, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 21507072, + "complete": true + }, + { + "elapsed_seconds": 0.1611938169990026, + "phase": "idle", + "missing_pids": [], + "workload_pss_bytes": 21507072, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 21507072, + "complete": true + }, + { + "elapsed_seconds": 0.24011351299850503, + "phase": "idle", + "missing_pids": [], + "workload_pss_bytes": 21507072, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 21507072, + "complete": true + }, + { + "elapsed_seconds": 0.31859744200119167, + "phase": "idle", + "missing_pids": [], + "workload_pss_bytes": 21507072, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 21507072, + "complete": true + }, + { + "elapsed_seconds": 0.39875572600067244, + "phase": "idle", + "missing_pids": [], + "workload_pss_bytes": 21507072, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 21507072, + "complete": true + }, + { + "elapsed_seconds": 0.4728452859999379, + "phase": "idle", + "missing_pids": [], + "workload_pss_bytes": 21507072, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 21507072, + "complete": true + }, + { + "elapsed_seconds": 0.5540339610015508, + "phase": "search", + "missing_pids": [], + "workload_pss_bytes": 21916672, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 21916672, + "complete": true + }, + { + "elapsed_seconds": 0.6490613360001589, + "phase": "search", + "missing_pids": [], + "workload_pss_bytes": 116733952, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 116733952, + "complete": true + }, + { + "elapsed_seconds": 0.7486974269995699, + "phase": "search", + "missing_pids": [], + "workload_pss_bytes": 100445184, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 100445184, + "complete": true + }, + { + "elapsed_seconds": 0.8415411729984044, + "phase": "search", + "missing_pids": [], + "workload_pss_bytes": 90210304, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 90210304, + "complete": true + }, + { + "elapsed_seconds": 0.9330257479996362, + "phase": "search", + "missing_pids": [], + "workload_pss_bytes": 113723392, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 113723392, + "complete": true + }, + { + "elapsed_seconds": 1.0092958610002825, + "phase": "search", + "missing_pids": [], + "workload_pss_bytes": 23094272, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 23094272, + "complete": true + }, + { + "elapsed_seconds": 1.029161098998884, + "phase": "search", + "missing_pids": [], + "workload_pss_bytes": 23094272, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 23094272, + "complete": true + }, + { + "elapsed_seconds": 1.127948691999336, + "phase": "search", + "missing_pids": [], + "workload_pss_bytes": 23094272, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 23094272, + "complete": true + }, + { + "elapsed_seconds": 1.20429703300033, + "phase": "search", + "missing_pids": [], + "workload_pss_bytes": 23094272, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 23094272, + "complete": true + }, + { + "elapsed_seconds": 1.2267869370007247, + "phase": "download", + "missing_pids": [], + "workload_pss_bytes": 31071232, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 31071232, + "complete": true + }, + { + "elapsed_seconds": 1.3048600850015646, + "phase": "download", + "missing_pids": [], + "workload_pss_bytes": 32319488, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 32319488, + "complete": true + }, + { + "elapsed_seconds": 1.3865046499995515, + "phase": "download", + "missing_pids": [], + "workload_pss_bytes": 32319488, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 32319488, + "complete": true + }, + { + "elapsed_seconds": 1.4680904699998791, + "phase": "download", + "missing_pids": [], + "workload_pss_bytes": 32319488, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 32319488, + "complete": true + }, + { + "elapsed_seconds": 1.5463095800005249, + "phase": "download", + "missing_pids": [], + "workload_pss_bytes": 32319488, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 32319488, + "complete": true + }, + { + "elapsed_seconds": 1.623929590001353, + "phase": "download", + "missing_pids": [], + "workload_pss_bytes": 32319488, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 32319488, + "complete": true + }, + { + "elapsed_seconds": 1.7037251610017847, + "phase": "download", + "missing_pids": [], + "workload_pss_bytes": 32319488, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 32319488, + "complete": true + }, + { + "elapsed_seconds": 1.7736864590006007, + "phase": "download", + "missing_pids": [], + "workload_pss_bytes": 41765888, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 41765888, + "complete": true + }, + { + "elapsed_seconds": 1.8531221140001435, + "phase": "download", + "missing_pids": [], + "workload_pss_bytes": 37915648, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 37915648, + "complete": true + }, + { + "elapsed_seconds": 1.9324016089994984, + "phase": "download", + "missing_pids": [], + "workload_pss_bytes": 37915648, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 37915648, + "complete": true + }, + { + "elapsed_seconds": 1.9674805329996161, + "phase": "download", + "missing_pids": [], + "workload_pss_bytes": 36730880, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 36730880, + "complete": true + }, + { + "elapsed_seconds": 1.9884941339987563, + "phase": "teardown", + "missing_pids": [], + "workload_pss_bytes": 36730880, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 36730880, + "complete": true + }, + { + "elapsed_seconds": 2.0661351369999466, + "phase": "teardown", + "missing_pids": [], + "workload_pss_bytes": 36730880, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 36730880, + "complete": true + }, + { + "elapsed_seconds": 2.146109373999934, + "phase": "teardown", + "missing_pids": [], + "workload_pss_bytes": 36730880, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 36730880, + "complete": true + }, + { + "elapsed_seconds": 2.2254046730013215, + "phase": "teardown", + "missing_pids": [], + "workload_pss_bytes": 36730880, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 36730880, + "complete": true + }, + { + "elapsed_seconds": 2.3056921679999505, + "phase": "teardown", + "missing_pids": [], + "workload_pss_bytes": 36730880, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 36730880, + "complete": true + }, + { + "elapsed_seconds": 2.3870249559986405, + "phase": "teardown", + "missing_pids": [], + "workload_pss_bytes": 36741120, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 36741120, + "complete": true + }, + { + "elapsed_seconds": 2.410034814998653, + "phase": "teardown", + "missing_pids": [ + 486984 + ], + "workload_pss_bytes": 0, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 0, + "complete": false + }, + { + "elapsed_seconds": 2.4101275270004408, + "phase": "exited", + "missing_pids": [], + "workload_pss_bytes": 0, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 0, + "complete": true + } + ], + "events": [ + { + "phase": "idle" + }, + { + "phase": "search" + }, + { + "phase": "search", + "search_seconds": 0.487118360997556, + "result_count": 1200 + }, + { + "phase": "download" + }, + { + "phase": "download", + "download_seconds": 0.7380511730007129, + "payload_bytes": 4194304, + "sha256": "2b07811057df887086f06a67edc6ebf911de8b6741156e7a2eb1416a4b8b1b2e", + "libtorrent_version": "2.0.11.0" + }, + { + "phase": "teardown" + } + ], + "summary": { + "download": { + "sample_count": 11, + "incomplete_samples": 0, + "workload_pss_bytes": { + "median": 32319488, + "peak": 41765888 + }, + "attached_stack_pss_bytes": { + "median": 0, + "peak": 0 + }, + "engine_pss_bytes": { + "median": 0, + "peak": 0 + }, + "accounted_pss_bytes": { + "median": 32319488, + "peak": 41765888 + } + }, + "exited": { + "sample_count": 1, + "incomplete_samples": 0, + "workload_pss_bytes": { + "median": 0, + "peak": 0 + }, + "attached_stack_pss_bytes": { + "median": 0, + "peak": 0 + }, + "engine_pss_bytes": { + "median": 0, + "peak": 0 + }, + "accounted_pss_bytes": { + "median": 0, + "peak": 0 + } + }, + "idle": { + "sample_count": 5, + "incomplete_samples": 0, + "workload_pss_bytes": { + "median": 21507072, + "peak": 21507072 + }, + "attached_stack_pss_bytes": { + "median": 0, + "peak": 0 + }, + "engine_pss_bytes": { + "median": 0, + "peak": 0 + }, + "accounted_pss_bytes": { + "median": 21507072, + "peak": 21507072 + } + }, + "search": { + "sample_count": 9, + "incomplete_samples": 0, + "workload_pss_bytes": { + "median": 23094272, + "peak": 116733952 + }, + "attached_stack_pss_bytes": { + "median": 0, + "peak": 0 + }, + "engine_pss_bytes": { + "median": 0, + "peak": 0 + }, + "accounted_pss_bytes": { + "median": 23094272, + "peak": 116733952 + } + }, + "startup": { + "sample_count": 2, + "incomplete_samples": 0, + "workload_pss_bytes": { + "median": 18469888.0, + "peak": 21507072 + }, + "attached_stack_pss_bytes": { + "median": 0.0, + "peak": 0 + }, + "engine_pss_bytes": { + "median": 0.0, + "peak": 0 + }, + "accounted_pss_bytes": { + "median": 18469888.0, + "peak": 21507072 + } + }, + "teardown": { + "sample_count": 7, + "incomplete_samples": 1, + "workload_pss_bytes": { + "median": 36730880.0, + "peak": 36741120 + }, + "attached_stack_pss_bytes": { + "median": 0.0, + "peak": 0 + }, + "engine_pss_bytes": { + "median": 0.0, + "peak": 0 + }, + "accounted_pss_bytes": { + "median": 36730880.0, + "peak": 36741120 + } + } + } + } + ] +} diff --git a/docs/benchmarks/stack-docker.json b/docs/benchmarks/stack-docker.json new file mode 100644 index 0000000..b23937c --- /dev/null +++ b/docs/benchmarks/stack-docker.json @@ -0,0 +1,13838 @@ +{ + "engine": "docker", + "samples": [ + { + "elapsed_seconds": 21.92618555700028, + "phase": "idle", + "services": { + "jackett": { + "memory_current_bytes": 86007808, + "cpu_usage_usec": 3471673 + }, + "prowlarr": { + "memory_current_bytes": 103325696, + "cpu_usage_usec": 5405661 + }, + "qbittorrent": { + "memory_current_bytes": 10231808, + "cpu_usage_usec": 328122 + }, + "flaresolverr": { + "memory_current_bytes": 76058624, + "cpu_usage_usec": 1635735 + } + } + }, + { + "elapsed_seconds": 22.027070650000496, + "phase": "idle", + "services": { + "jackett": { + "memory_current_bytes": 85499904, + "cpu_usage_usec": 3471949 + }, + "prowlarr": { + "memory_current_bytes": 103559168, + "cpu_usage_usec": 5411249 + }, + "qbittorrent": { + "memory_current_bytes": 10231808, + "cpu_usage_usec": 328419 + }, + "flaresolverr": { + "memory_current_bytes": 76058624, + "cpu_usage_usec": 1635735 + } + } + }, + { + "elapsed_seconds": 22.12797830300042, + "phase": "idle", + "services": { + "jackett": { + "memory_current_bytes": 85499904, + "cpu_usage_usec": 3471949 + }, + "prowlarr": { + "memory_current_bytes": 103559168, + "cpu_usage_usec": 5416877 + }, + "qbittorrent": { + "memory_current_bytes": 10231808, + "cpu_usage_usec": 328715 + }, + "flaresolverr": { + "memory_current_bytes": 76058624, + "cpu_usage_usec": 1635735 + } + } + }, + { + "elapsed_seconds": 22.22841726600018, + "phase": "idle", + "services": { + "jackett": { + "memory_current_bytes": 85499904, + "cpu_usage_usec": 3471949 + }, + "prowlarr": { + "memory_current_bytes": 103559168, + "cpu_usage_usec": 5422052 + }, + "qbittorrent": { + "memory_current_bytes": 10231808, + "cpu_usage_usec": 329422 + }, + "flaresolverr": { + "memory_current_bytes": 76058624, + "cpu_usage_usec": 1635735 + } + } + }, + { + "elapsed_seconds": 22.328885531000196, + "phase": "idle", + "services": { + "jackett": { + "memory_current_bytes": 85475328, + "cpu_usage_usec": 3471949 + }, + "prowlarr": { + "memory_current_bytes": 102645760, + "cpu_usage_usec": 5423964 + }, + "qbittorrent": { + "memory_current_bytes": 10219520, + "cpu_usage_usec": 329576 + }, + "flaresolverr": { + "memory_current_bytes": 76058624, + "cpu_usage_usec": 1635735 + } + } + }, + { + "elapsed_seconds": 22.42962521500067, + "phase": "idle", + "services": { + "jackett": { + "memory_current_bytes": 85475328, + "cpu_usage_usec": 3471995 + }, + "prowlarr": { + "memory_current_bytes": 102608896, + "cpu_usage_usec": 5425731 + }, + "qbittorrent": { + "memory_current_bytes": 10002432, + "cpu_usage_usec": 329576 + }, + "flaresolverr": { + "memory_current_bytes": 76058624, + "cpu_usage_usec": 1635735 + } + } + }, + { + "elapsed_seconds": 22.530203294000785, + "phase": "idle", + "services": { + "jackett": { + "memory_current_bytes": 85209088, + "cpu_usage_usec": 3471995 + }, + "prowlarr": { + "memory_current_bytes": 102608896, + "cpu_usage_usec": 5426597 + }, + "qbittorrent": { + "memory_current_bytes": 10264576, + "cpu_usage_usec": 329691 + }, + "flaresolverr": { + "memory_current_bytes": 76058624, + "cpu_usage_usec": 1635805 + } + } + }, + { + "elapsed_seconds": 22.630656944000293, + "phase": "idle", + "services": { + "jackett": { + "memory_current_bytes": 85209088, + "cpu_usage_usec": 3471995 + }, + "prowlarr": { + "memory_current_bytes": 102608896, + "cpu_usage_usec": 5426597 + }, + "qbittorrent": { + "memory_current_bytes": 10264576, + "cpu_usage_usec": 329855 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1635805 + } + } + }, + { + "elapsed_seconds": 22.731571762000385, + "phase": "idle", + "services": { + "jackett": { + "memory_current_bytes": 85209088, + "cpu_usage_usec": 3471995 + }, + "prowlarr": { + "memory_current_bytes": 102608896, + "cpu_usage_usec": 5428375 + }, + "qbittorrent": { + "memory_current_bytes": 10248192, + "cpu_usage_usec": 330177 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1635805 + } + } + }, + { + "elapsed_seconds": 22.832482549000815, + "phase": "idle", + "services": { + "jackett": { + "memory_current_bytes": 85204992, + "cpu_usage_usec": 3472110 + }, + "prowlarr": { + "memory_current_bytes": 102608896, + "cpu_usage_usec": 5429237 + }, + "qbittorrent": { + "memory_current_bytes": 10248192, + "cpu_usage_usec": 330255 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1635805 + } + } + }, + { + "elapsed_seconds": 22.933366847000798, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 85204992, + "cpu_usage_usec": 3472162 + }, + "prowlarr": { + "memory_current_bytes": 102694912, + "cpu_usage_usec": 5435626 + }, + "qbittorrent": { + "memory_current_bytes": 10248192, + "cpu_usage_usec": 330601 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1635805 + } + } + }, + { + "elapsed_seconds": 23.034441794000486, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 85204992, + "cpu_usage_usec": 3472162 + }, + "prowlarr": { + "memory_current_bytes": 102858752, + "cpu_usage_usec": 5470235 + }, + "qbittorrent": { + "memory_current_bytes": 10235904, + "cpu_usage_usec": 331077 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1635805 + } + } + }, + { + "elapsed_seconds": 23.13535848200081, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 85204992, + "cpu_usage_usec": 3472162 + }, + "prowlarr": { + "memory_current_bytes": 102854656, + "cpu_usage_usec": 5473569 + }, + "qbittorrent": { + "memory_current_bytes": 10223616, + "cpu_usage_usec": 331159 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1635805 + } + } + }, + { + "elapsed_seconds": 23.236320583000634, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 85204992, + "cpu_usage_usec": 3472162 + }, + "prowlarr": { + "memory_current_bytes": 102756352, + "cpu_usage_usec": 5474507 + }, + "qbittorrent": { + "memory_current_bytes": 10223616, + "cpu_usage_usec": 331443 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1635805 + } + } + }, + { + "elapsed_seconds": 23.337186404000022, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 85204992, + "cpu_usage_usec": 3472162 + }, + "prowlarr": { + "memory_current_bytes": 102993920, + "cpu_usage_usec": 5477665 + }, + "qbittorrent": { + "memory_current_bytes": 10223616, + "cpu_usage_usec": 331779 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1635805 + } + } + }, + { + "elapsed_seconds": 23.43822555099996, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 86097920, + "cpu_usage_usec": 3523905 + }, + "prowlarr": { + "memory_current_bytes": 102993920, + "cpu_usage_usec": 5479153 + }, + "qbittorrent": { + "memory_current_bytes": 10207232, + "cpu_usage_usec": 331879 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1635805 + } + } + }, + { + "elapsed_seconds": 23.539081649000764, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 86245376, + "cpu_usage_usec": 3573323 + }, + "prowlarr": { + "memory_current_bytes": 102993920, + "cpu_usage_usec": 5480871 + }, + "qbittorrent": { + "memory_current_bytes": 10072064, + "cpu_usage_usec": 331927 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1635886 + } + } + }, + { + "elapsed_seconds": 23.640106342000763, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 86462464, + "cpu_usage_usec": 3624136 + }, + "prowlarr": { + "memory_current_bytes": 102993920, + "cpu_usage_usec": 5483455 + }, + "qbittorrent": { + "memory_current_bytes": 10059776, + "cpu_usage_usec": 331927 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1635886 + } + } + }, + { + "elapsed_seconds": 23.740953523000826, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 86839296, + "cpu_usage_usec": 3675537 + }, + "prowlarr": { + "memory_current_bytes": 102993920, + "cpu_usage_usec": 5485639 + }, + "qbittorrent": { + "memory_current_bytes": 10059776, + "cpu_usage_usec": 331995 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1635886 + } + } + }, + { + "elapsed_seconds": 23.84187209100037, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 87007232, + "cpu_usage_usec": 3726662 + }, + "prowlarr": { + "memory_current_bytes": 102993920, + "cpu_usage_usec": 5485692 + }, + "qbittorrent": { + "memory_current_bytes": 10059776, + "cpu_usage_usec": 331995 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1635886 + } + } + }, + { + "elapsed_seconds": 23.94267166300051, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 87318528, + "cpu_usage_usec": 3777128 + }, + "prowlarr": { + "memory_current_bytes": 102928384, + "cpu_usage_usec": 5485692 + }, + "qbittorrent": { + "memory_current_bytes": 10059776, + "cpu_usage_usec": 331995 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1635886 + } + } + }, + { + "elapsed_seconds": 24.043365950000407, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 87736320, + "cpu_usage_usec": 3828609 + }, + "prowlarr": { + "memory_current_bytes": 102645760, + "cpu_usage_usec": 5485692 + }, + "qbittorrent": { + "memory_current_bytes": 10043392, + "cpu_usage_usec": 332016 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1635886 + } + } + }, + { + "elapsed_seconds": 24.144243405000452, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 87719936, + "cpu_usage_usec": 3835355 + }, + "prowlarr": { + "memory_current_bytes": 102645760, + "cpu_usage_usec": 5485692 + }, + "qbittorrent": { + "memory_current_bytes": 10043392, + "cpu_usage_usec": 332016 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1635886 + } + } + }, + { + "elapsed_seconds": 24.245180743000674, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 87719936, + "cpu_usage_usec": 3835355 + }, + "prowlarr": { + "memory_current_bytes": 102645760, + "cpu_usage_usec": 5485692 + }, + "qbittorrent": { + "memory_current_bytes": 10043392, + "cpu_usage_usec": 332016 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1635886 + } + } + }, + { + "elapsed_seconds": 24.345758661000218, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 87719936, + "cpu_usage_usec": 3835355 + }, + "prowlarr": { + "memory_current_bytes": 103854080, + "cpu_usage_usec": 5529835 + }, + "qbittorrent": { + "memory_current_bytes": 10043392, + "cpu_usage_usec": 332016 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1635886 + } + } + }, + { + "elapsed_seconds": 24.446325058000184, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 87719936, + "cpu_usage_usec": 3835355 + }, + "prowlarr": { + "memory_current_bytes": 104259584, + "cpu_usage_usec": 5581491 + }, + "qbittorrent": { + "memory_current_bytes": 10043392, + "cpu_usage_usec": 332016 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1635886 + } + } + }, + { + "elapsed_seconds": 24.54697353500069, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 87650304, + "cpu_usage_usec": 3835355 + }, + "prowlarr": { + "memory_current_bytes": 104308736, + "cpu_usage_usec": 5632092 + }, + "qbittorrent": { + "memory_current_bytes": 10043392, + "cpu_usage_usec": 332054 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1635945 + } + } + }, + { + "elapsed_seconds": 24.647522635000314, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 87625728, + "cpu_usage_usec": 3835463 + }, + "prowlarr": { + "memory_current_bytes": 104521728, + "cpu_usage_usec": 5683287 + }, + "qbittorrent": { + "memory_current_bytes": 10043392, + "cpu_usage_usec": 332054 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1635945 + } + } + }, + { + "elapsed_seconds": 24.748139109000476, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 87625728, + "cpu_usage_usec": 3835463 + }, + "prowlarr": { + "memory_current_bytes": 105201664, + "cpu_usage_usec": 5733777 + }, + "qbittorrent": { + "memory_current_bytes": 10043392, + "cpu_usage_usec": 332054 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1635945 + } + } + }, + { + "elapsed_seconds": 24.848550693000107, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 87625728, + "cpu_usage_usec": 3835566 + }, + "prowlarr": { + "memory_current_bytes": 105644032, + "cpu_usage_usec": 5784226 + }, + "qbittorrent": { + "memory_current_bytes": 10043392, + "cpu_usage_usec": 332054 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1635945 + } + } + }, + { + "elapsed_seconds": 24.94898811100029, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 87625728, + "cpu_usage_usec": 3835566 + }, + "prowlarr": { + "memory_current_bytes": 106098688, + "cpu_usage_usec": 5835082 + }, + "qbittorrent": { + "memory_current_bytes": 10043392, + "cpu_usage_usec": 332054 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1635945 + } + } + }, + { + "elapsed_seconds": 25.04959611800041, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 87625728, + "cpu_usage_usec": 3835566 + }, + "prowlarr": { + "memory_current_bytes": 106622976, + "cpu_usage_usec": 5884902 + }, + "qbittorrent": { + "memory_current_bytes": 10043392, + "cpu_usage_usec": 332073 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1635945 + } + } + }, + { + "elapsed_seconds": 25.150107266000305, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 87592960, + "cpu_usage_usec": 3835566 + }, + "prowlarr": { + "memory_current_bytes": 107134976, + "cpu_usage_usec": 5936452 + }, + "qbittorrent": { + "memory_current_bytes": 10043392, + "cpu_usage_usec": 332073 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1635945 + } + } + }, + { + "elapsed_seconds": 25.25046388100054, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 87592960, + "cpu_usage_usec": 3835566 + }, + "prowlarr": { + "memory_current_bytes": 107368448, + "cpu_usage_usec": 5985907 + }, + "qbittorrent": { + "memory_current_bytes": 10043392, + "cpu_usage_usec": 332164 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1635945 + } + } + }, + { + "elapsed_seconds": 25.351029883000592, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 87592960, + "cpu_usage_usec": 3835566 + }, + "prowlarr": { + "memory_current_bytes": 108027904, + "cpu_usage_usec": 6037817 + }, + "qbittorrent": { + "memory_current_bytes": 10043392, + "cpu_usage_usec": 332164 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1635945 + } + } + }, + { + "elapsed_seconds": 25.451543578000383, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 87592960, + "cpu_usage_usec": 3835566 + }, + "prowlarr": { + "memory_current_bytes": 108466176, + "cpu_usage_usec": 6087288 + }, + "qbittorrent": { + "memory_current_bytes": 10043392, + "cpu_usage_usec": 332164 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1635980 + } + } + }, + { + "elapsed_seconds": 25.552037533000657, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 87592960, + "cpu_usage_usec": 3835566 + }, + "prowlarr": { + "memory_current_bytes": 109416448, + "cpu_usage_usec": 6138847 + }, + "qbittorrent": { + "memory_current_bytes": 10043392, + "cpu_usage_usec": 332196 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1635980 + } + } + }, + { + "elapsed_seconds": 25.652456419000373, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 87592960, + "cpu_usage_usec": 3835566 + }, + "prowlarr": { + "memory_current_bytes": 109703168, + "cpu_usage_usec": 6188034 + }, + "qbittorrent": { + "memory_current_bytes": 10571776, + "cpu_usage_usec": 332678 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1635980 + } + } + }, + { + "elapsed_seconds": 25.752956065000035, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 87592960, + "cpu_usage_usec": 3835566 + }, + "prowlarr": { + "memory_current_bytes": 109690880, + "cpu_usage_usec": 6238420 + }, + "qbittorrent": { + "memory_current_bytes": 10571776, + "cpu_usage_usec": 332678 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1635980 + } + } + }, + { + "elapsed_seconds": 25.853314403000695, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 87592960, + "cpu_usage_usec": 3835683 + }, + "prowlarr": { + "memory_current_bytes": 109940736, + "cpu_usage_usec": 6285484 + }, + "qbittorrent": { + "memory_current_bytes": 10571776, + "cpu_usage_usec": 332678 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1635980 + } + } + }, + { + "elapsed_seconds": 25.954271110000263, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 87592960, + "cpu_usage_usec": 3835683 + }, + "prowlarr": { + "memory_current_bytes": 109936640, + "cpu_usage_usec": 6285716 + }, + "qbittorrent": { + "memory_current_bytes": 10571776, + "cpu_usage_usec": 332678 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1635980 + } + } + }, + { + "elapsed_seconds": 26.05589617000078, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 87592960, + "cpu_usage_usec": 3835683 + }, + "prowlarr": { + "memory_current_bytes": 109936640, + "cpu_usage_usec": 6285716 + }, + "qbittorrent": { + "memory_current_bytes": 10571776, + "cpu_usage_usec": 332718 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1635980 + } + } + }, + { + "elapsed_seconds": 26.1568267800003, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 87592960, + "cpu_usage_usec": 3835683 + }, + "prowlarr": { + "memory_current_bytes": 109928448, + "cpu_usage_usec": 6285716 + }, + "qbittorrent": { + "memory_current_bytes": 10571776, + "cpu_usage_usec": 332718 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1635980 + } + } + }, + { + "elapsed_seconds": 26.257729378000477, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 87592960, + "cpu_usage_usec": 3835683 + }, + "prowlarr": { + "memory_current_bytes": 109928448, + "cpu_usage_usec": 6285716 + }, + "qbittorrent": { + "memory_current_bytes": 10571776, + "cpu_usage_usec": 332718 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1635980 + } + } + }, + { + "elapsed_seconds": 26.358742022000115, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 87592960, + "cpu_usage_usec": 3835683 + }, + "prowlarr": { + "memory_current_bytes": 109928448, + "cpu_usage_usec": 6286203 + }, + "qbittorrent": { + "memory_current_bytes": 10571776, + "cpu_usage_usec": 332718 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1635980 + } + } + }, + { + "elapsed_seconds": 26.459639484000036, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 87592960, + "cpu_usage_usec": 3835683 + }, + "prowlarr": { + "memory_current_bytes": 109678592, + "cpu_usage_usec": 6286203 + }, + "qbittorrent": { + "memory_current_bytes": 10571776, + "cpu_usage_usec": 332718 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636026 + } + } + }, + { + "elapsed_seconds": 26.56089362900002, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 87592960, + "cpu_usage_usec": 3835683 + }, + "prowlarr": { + "memory_current_bytes": 109678592, + "cpu_usage_usec": 6286334 + }, + "qbittorrent": { + "memory_current_bytes": 10567680, + "cpu_usage_usec": 332768 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636026 + } + } + }, + { + "elapsed_seconds": 26.66177013000015, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 87592960, + "cpu_usage_usec": 3835683 + }, + "prowlarr": { + "memory_current_bytes": 109678592, + "cpu_usage_usec": 6286334 + }, + "qbittorrent": { + "memory_current_bytes": 10567680, + "cpu_usage_usec": 332768 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636026 + } + } + }, + { + "elapsed_seconds": 26.763397073000306, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 87592960, + "cpu_usage_usec": 3835683 + }, + "prowlarr": { + "memory_current_bytes": 109678592, + "cpu_usage_usec": 6286334 + }, + "qbittorrent": { + "memory_current_bytes": 10309632, + "cpu_usage_usec": 332823 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636026 + } + } + }, + { + "elapsed_seconds": 26.86419823000051, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 87592960, + "cpu_usage_usec": 3836443 + }, + "prowlarr": { + "memory_current_bytes": 109678592, + "cpu_usage_usec": 6301956 + }, + "qbittorrent": { + "memory_current_bytes": 10309632, + "cpu_usage_usec": 332823 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636026 + } + } + }, + { + "elapsed_seconds": 26.965161417000672, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 87592960, + "cpu_usage_usec": 3836443 + }, + "prowlarr": { + "memory_current_bytes": 110428160, + "cpu_usage_usec": 6353824 + }, + "qbittorrent": { + "memory_current_bytes": 10309632, + "cpu_usage_usec": 332823 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636026 + } + } + }, + { + "elapsed_seconds": 27.06600009000067, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 87592960, + "cpu_usage_usec": 3836443 + }, + "prowlarr": { + "memory_current_bytes": 110428160, + "cpu_usage_usec": 6353896 + }, + "qbittorrent": { + "memory_current_bytes": 10309632, + "cpu_usage_usec": 333142 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636026 + } + } + }, + { + "elapsed_seconds": 27.16650597500029, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 87592960, + "cpu_usage_usec": 3836443 + }, + "prowlarr": { + "memory_current_bytes": 110387200, + "cpu_usage_usec": 6353896 + }, + "qbittorrent": { + "memory_current_bytes": 10334208, + "cpu_usage_usec": 333448 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636026 + } + } + }, + { + "elapsed_seconds": 27.267358099000376, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 87592960, + "cpu_usage_usec": 3836443 + }, + "prowlarr": { + "memory_current_bytes": 110206976, + "cpu_usage_usec": 6353896 + }, + "qbittorrent": { + "memory_current_bytes": 10346496, + "cpu_usage_usec": 333989 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636026 + } + } + }, + { + "elapsed_seconds": 27.368234817000484, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 87592960, + "cpu_usage_usec": 3836443 + }, + "prowlarr": { + "memory_current_bytes": 110096384, + "cpu_usage_usec": 6354290 + }, + "qbittorrent": { + "memory_current_bytes": 10346496, + "cpu_usage_usec": 334080 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636026 + } + } + }, + { + "elapsed_seconds": 27.46907993000059, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 87592960, + "cpu_usage_usec": 3836443 + }, + "prowlarr": { + "memory_current_bytes": 109846528, + "cpu_usage_usec": 6354290 + }, + "qbittorrent": { + "memory_current_bytes": 10346496, + "cpu_usage_usec": 334080 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636070 + } + } + }, + { + "elapsed_seconds": 27.569907919000798, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 87592960, + "cpu_usage_usec": 3836443 + }, + "prowlarr": { + "memory_current_bytes": 110108672, + "cpu_usage_usec": 6354811 + }, + "qbittorrent": { + "memory_current_bytes": 10346496, + "cpu_usage_usec": 334135 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636070 + } + } + }, + { + "elapsed_seconds": 27.67074788300033, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 87592960, + "cpu_usage_usec": 3836443 + }, + "prowlarr": { + "memory_current_bytes": 110108672, + "cpu_usage_usec": 6354811 + }, + "qbittorrent": { + "memory_current_bytes": 10338304, + "cpu_usage_usec": 334135 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636070 + } + } + }, + { + "elapsed_seconds": 27.771576744999948, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 87592960, + "cpu_usage_usec": 3836443 + }, + "prowlarr": { + "memory_current_bytes": 110108672, + "cpu_usage_usec": 6354811 + }, + "qbittorrent": { + "memory_current_bytes": 10334208, + "cpu_usage_usec": 334135 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636070 + } + } + }, + { + "elapsed_seconds": 27.87239119900005, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 87592960, + "cpu_usage_usec": 3836556 + }, + "prowlarr": { + "memory_current_bytes": 110108672, + "cpu_usage_usec": 6354857 + }, + "qbittorrent": { + "memory_current_bytes": 10334208, + "cpu_usage_usec": 334135 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636070 + } + } + }, + { + "elapsed_seconds": 27.97333559300023, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 87592960, + "cpu_usage_usec": 3836556 + }, + "prowlarr": { + "memory_current_bytes": 110108672, + "cpu_usage_usec": 6357915 + }, + "qbittorrent": { + "memory_current_bytes": 10334208, + "cpu_usage_usec": 334135 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636070 + } + } + }, + { + "elapsed_seconds": 28.074049675000424, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 88629248, + "cpu_usage_usec": 3849439 + }, + "prowlarr": { + "memory_current_bytes": 111706112, + "cpu_usage_usec": 6436743 + }, + "qbittorrent": { + "memory_current_bytes": 10334208, + "cpu_usage_usec": 334168 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636070 + } + } + }, + { + "elapsed_seconds": 28.174847776000206, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 88629248, + "cpu_usage_usec": 3849439 + }, + "prowlarr": { + "memory_current_bytes": 111706112, + "cpu_usage_usec": 6462684 + }, + "qbittorrent": { + "memory_current_bytes": 10334208, + "cpu_usage_usec": 334168 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636070 + } + } + }, + { + "elapsed_seconds": 28.275399240000297, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 88629248, + "cpu_usage_usec": 3849439 + }, + "prowlarr": { + "memory_current_bytes": 111702016, + "cpu_usage_usec": 6462684 + }, + "qbittorrent": { + "memory_current_bytes": 10334208, + "cpu_usage_usec": 334268 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636070 + } + } + }, + { + "elapsed_seconds": 28.37630516000081, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 88588288, + "cpu_usage_usec": 3849439 + }, + "prowlarr": { + "memory_current_bytes": 110972928, + "cpu_usage_usec": 6462874 + }, + "qbittorrent": { + "memory_current_bytes": 10334208, + "cpu_usage_usec": 334268 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636070 + } + } + }, + { + "elapsed_seconds": 28.477219060000607, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 88334336, + "cpu_usage_usec": 3849439 + }, + "prowlarr": { + "memory_current_bytes": 110972928, + "cpu_usage_usec": 6462874 + }, + "qbittorrent": { + "memory_current_bytes": 10334208, + "cpu_usage_usec": 334268 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636144 + } + } + }, + { + "elapsed_seconds": 28.578071391000776, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 88334336, + "cpu_usage_usec": 3849499 + }, + "prowlarr": { + "memory_current_bytes": 111230976, + "cpu_usage_usec": 6465275 + }, + "qbittorrent": { + "memory_current_bytes": 10334208, + "cpu_usage_usec": 334310 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636144 + } + } + }, + { + "elapsed_seconds": 28.678900695000266, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 88334336, + "cpu_usage_usec": 3849499 + }, + "prowlarr": { + "memory_current_bytes": 111230976, + "cpu_usage_usec": 6465626 + }, + "qbittorrent": { + "memory_current_bytes": 10219520, + "cpu_usage_usec": 334310 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636144 + } + } + }, + { + "elapsed_seconds": 28.779730044000644, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 88080384, + "cpu_usage_usec": 3849499 + }, + "prowlarr": { + "memory_current_bytes": 111407104, + "cpu_usage_usec": 6465626 + }, + "qbittorrent": { + "memory_current_bytes": 10481664, + "cpu_usage_usec": 334310 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636144 + } + } + }, + { + "elapsed_seconds": 28.88064355000006, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 87965696, + "cpu_usage_usec": 3849604 + }, + "prowlarr": { + "memory_current_bytes": 111407104, + "cpu_usage_usec": 6465682 + }, + "qbittorrent": { + "memory_current_bytes": 10481664, + "cpu_usage_usec": 334310 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636144 + } + } + }, + { + "elapsed_seconds": 28.981495061000714, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 87965696, + "cpu_usage_usec": 3849604 + }, + "prowlarr": { + "memory_current_bytes": 111403008, + "cpu_usage_usec": 6465686 + }, + "qbittorrent": { + "memory_current_bytes": 10481664, + "cpu_usage_usec": 334310 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636144 + } + } + }, + { + "elapsed_seconds": 29.08193023700005, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 87965696, + "cpu_usage_usec": 3849683 + }, + "prowlarr": { + "memory_current_bytes": 111431680, + "cpu_usage_usec": 6465949 + }, + "qbittorrent": { + "memory_current_bytes": 10502144, + "cpu_usage_usec": 334348 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636144 + } + } + }, + { + "elapsed_seconds": 29.182783056000517, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 87965696, + "cpu_usage_usec": 3849683 + }, + "prowlarr": { + "memory_current_bytes": 111431680, + "cpu_usage_usec": 6465949 + }, + "qbittorrent": { + "memory_current_bytes": 10502144, + "cpu_usage_usec": 334376 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636144 + } + } + }, + { + "elapsed_seconds": 29.283724248, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 87965696, + "cpu_usage_usec": 3849683 + }, + "prowlarr": { + "memory_current_bytes": 111431680, + "cpu_usage_usec": 6465949 + }, + "qbittorrent": { + "memory_current_bytes": 10502144, + "cpu_usage_usec": 334376 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636144 + } + } + }, + { + "elapsed_seconds": 29.384647827000663, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 87965696, + "cpu_usage_usec": 3849683 + }, + "prowlarr": { + "memory_current_bytes": 111431680, + "cpu_usage_usec": 6466795 + }, + "qbittorrent": { + "memory_current_bytes": 10502144, + "cpu_usage_usec": 334376 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636144 + } + } + }, + { + "elapsed_seconds": 29.485074255000654, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 87965696, + "cpu_usage_usec": 3849683 + }, + "prowlarr": { + "memory_current_bytes": 111247360, + "cpu_usage_usec": 6469582 + }, + "qbittorrent": { + "memory_current_bytes": 10502144, + "cpu_usage_usec": 334376 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636200 + } + } + }, + { + "elapsed_seconds": 29.585914510000293, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 87965696, + "cpu_usage_usec": 3849683 + }, + "prowlarr": { + "memory_current_bytes": 111505408, + "cpu_usage_usec": 6469662 + }, + "qbittorrent": { + "memory_current_bytes": 10551296, + "cpu_usage_usec": 334384 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636200 + } + } + }, + { + "elapsed_seconds": 29.68686539400005, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 87965696, + "cpu_usage_usec": 3849683 + }, + "prowlarr": { + "memory_current_bytes": 111259648, + "cpu_usage_usec": 6470053 + }, + "qbittorrent": { + "memory_current_bytes": 10551296, + "cpu_usage_usec": 334497 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636200 + } + } + }, + { + "elapsed_seconds": 29.78779226900042, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 87965696, + "cpu_usage_usec": 3849683 + }, + "prowlarr": { + "memory_current_bytes": 111521792, + "cpu_usage_usec": 6471802 + }, + "qbittorrent": { + "memory_current_bytes": 10551296, + "cpu_usage_usec": 334497 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636200 + } + } + }, + { + "elapsed_seconds": 29.888747238000178, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 87965696, + "cpu_usage_usec": 3849798 + }, + "prowlarr": { + "memory_current_bytes": 111521792, + "cpu_usage_usec": 6472136 + }, + "qbittorrent": { + "memory_current_bytes": 10551296, + "cpu_usage_usec": 334497 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636200 + } + } + }, + { + "elapsed_seconds": 29.98970028000076, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 87965696, + "cpu_usage_usec": 3849798 + }, + "prowlarr": { + "memory_current_bytes": 111460352, + "cpu_usage_usec": 6472147 + }, + "qbittorrent": { + "memory_current_bytes": 10551296, + "cpu_usage_usec": 334497 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636200 + } + } + }, + { + "elapsed_seconds": 30.090209431000403, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 88514560, + "cpu_usage_usec": 3936394 + }, + "prowlarr": { + "memory_current_bytes": 111460352, + "cpu_usage_usec": 6472302 + }, + "qbittorrent": { + "memory_current_bytes": 10551296, + "cpu_usage_usec": 334509 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636200 + } + } + }, + { + "elapsed_seconds": 30.19057210400024, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 88813568, + "cpu_usage_usec": 3987901 + }, + "prowlarr": { + "memory_current_bytes": 111230976, + "cpu_usage_usec": 6472302 + }, + "qbittorrent": { + "memory_current_bytes": 10551296, + "cpu_usage_usec": 334509 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636200 + } + } + }, + { + "elapsed_seconds": 30.291002515999935, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 88842240, + "cpu_usage_usec": 4037944 + }, + "prowlarr": { + "memory_current_bytes": 111493120, + "cpu_usage_usec": 6473365 + }, + "qbittorrent": { + "memory_current_bytes": 10551296, + "cpu_usage_usec": 334509 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636200 + } + } + }, + { + "elapsed_seconds": 30.39185954000004, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 88842240, + "cpu_usage_usec": 4043146 + }, + "prowlarr": { + "memory_current_bytes": 111226880, + "cpu_usage_usec": 6474051 + }, + "qbittorrent": { + "memory_current_bytes": 10551296, + "cpu_usage_usec": 334509 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636200 + } + } + }, + { + "elapsed_seconds": 30.492745778000426, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 88842240, + "cpu_usage_usec": 4043146 + }, + "prowlarr": { + "memory_current_bytes": 111226880, + "cpu_usage_usec": 6474492 + }, + "qbittorrent": { + "memory_current_bytes": 10551296, + "cpu_usage_usec": 334509 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636270 + } + } + }, + { + "elapsed_seconds": 30.59364689300037, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 88842240, + "cpu_usage_usec": 4043146 + }, + "prowlarr": { + "memory_current_bytes": 111226880, + "cpu_usage_usec": 6476333 + }, + "qbittorrent": { + "memory_current_bytes": 10551296, + "cpu_usage_usec": 334546 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636270 + } + } + }, + { + "elapsed_seconds": 30.694449383000574, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 88842240, + "cpu_usage_usec": 4043146 + }, + "prowlarr": { + "memory_current_bytes": 111030272, + "cpu_usage_usec": 6476375 + }, + "qbittorrent": { + "memory_current_bytes": 10813440, + "cpu_usage_usec": 335585 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636270 + } + } + }, + { + "elapsed_seconds": 30.795321944000534, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 88842240, + "cpu_usage_usec": 4043146 + }, + "prowlarr": { + "memory_current_bytes": 111030272, + "cpu_usage_usec": 6476375 + }, + "qbittorrent": { + "memory_current_bytes": 10813440, + "cpu_usage_usec": 335585 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636270 + } + } + }, + { + "elapsed_seconds": 30.89617081200049, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 88842240, + "cpu_usage_usec": 4043848 + }, + "prowlarr": { + "memory_current_bytes": 111030272, + "cpu_usage_usec": 6476431 + }, + "qbittorrent": { + "memory_current_bytes": 10784768, + "cpu_usage_usec": 335585 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636270 + } + } + }, + { + "elapsed_seconds": 30.997008187000574, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 88805376, + "cpu_usage_usec": 4043848 + }, + "prowlarr": { + "memory_current_bytes": 112857088, + "cpu_usage_usec": 6527419 + }, + "qbittorrent": { + "memory_current_bytes": 10604544, + "cpu_usage_usec": 335634 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636270 + } + } + }, + { + "elapsed_seconds": 31.09783412700017, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 88805376, + "cpu_usage_usec": 4043848 + }, + "prowlarr": { + "memory_current_bytes": 113016832, + "cpu_usage_usec": 6577862 + }, + "qbittorrent": { + "memory_current_bytes": 11325440, + "cpu_usage_usec": 336640 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636270 + } + } + }, + { + "elapsed_seconds": 31.198622889000035, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 88805376, + "cpu_usage_usec": 4043848 + }, + "prowlarr": { + "memory_current_bytes": 113213440, + "cpu_usage_usec": 6627267 + }, + "qbittorrent": { + "memory_current_bytes": 11304960, + "cpu_usage_usec": 336751 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636270 + } + } + }, + { + "elapsed_seconds": 31.299525323000125, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 88805376, + "cpu_usage_usec": 4043848 + }, + "prowlarr": { + "memory_current_bytes": 113401856, + "cpu_usage_usec": 6677557 + }, + "qbittorrent": { + "memory_current_bytes": 11304960, + "cpu_usage_usec": 336865 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636270 + } + } + }, + { + "elapsed_seconds": 31.400450789000388, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 88805376, + "cpu_usage_usec": 4043848 + }, + "prowlarr": { + "memory_current_bytes": 113242112, + "cpu_usage_usec": 6727413 + }, + "qbittorrent": { + "memory_current_bytes": 10772480, + "cpu_usage_usec": 337685 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636270 + } + } + }, + { + "elapsed_seconds": 31.501294506000704, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 88805376, + "cpu_usage_usec": 4043848 + }, + "prowlarr": { + "memory_current_bytes": 113733632, + "cpu_usage_usec": 6776725 + }, + "qbittorrent": { + "memory_current_bytes": 10772480, + "cpu_usage_usec": 338365 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636309 + } + } + }, + { + "elapsed_seconds": 31.602231586000016, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 88805376, + "cpu_usage_usec": 4043848 + }, + "prowlarr": { + "memory_current_bytes": 113930240, + "cpu_usage_usec": 6828096 + }, + "qbittorrent": { + "memory_current_bytes": 10772480, + "cpu_usage_usec": 339154 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636309 + } + } + }, + { + "elapsed_seconds": 31.70314589999998, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 88805376, + "cpu_usage_usec": 4043848 + }, + "prowlarr": { + "memory_current_bytes": 113901568, + "cpu_usage_usec": 6878526 + }, + "qbittorrent": { + "memory_current_bytes": 10506240, + "cpu_usage_usec": 339981 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636309 + } + } + }, + { + "elapsed_seconds": 31.803570367000248, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 88805376, + "cpu_usage_usec": 4043848 + }, + "prowlarr": { + "memory_current_bytes": 114139136, + "cpu_usage_usec": 6929221 + }, + "qbittorrent": { + "memory_current_bytes": 10506240, + "cpu_usage_usec": 340250 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636309 + } + } + }, + { + "elapsed_seconds": 31.90454262700041, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 88805376, + "cpu_usage_usec": 4043926 + }, + "prowlarr": { + "memory_current_bytes": 114122752, + "cpu_usage_usec": 6979979 + }, + "qbittorrent": { + "memory_current_bytes": 10506240, + "cpu_usage_usec": 340385 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636309 + } + } + }, + { + "elapsed_seconds": 32.0053677650003, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 88805376, + "cpu_usage_usec": 4043926 + }, + "prowlarr": { + "memory_current_bytes": 114356224, + "cpu_usage_usec": 7030680 + }, + "qbittorrent": { + "memory_current_bytes": 10506240, + "cpu_usage_usec": 340947 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636309 + } + } + }, + { + "elapsed_seconds": 32.106167769999956, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 88805376, + "cpu_usage_usec": 4043926 + }, + "prowlarr": { + "memory_current_bytes": 114585600, + "cpu_usage_usec": 7082093 + }, + "qbittorrent": { + "memory_current_bytes": 10768384, + "cpu_usage_usec": 341381 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636309 + } + } + }, + { + "elapsed_seconds": 32.20706040100049, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 88805376, + "cpu_usage_usec": 4043926 + }, + "prowlarr": { + "memory_current_bytes": 114798592, + "cpu_usage_usec": 7122319 + }, + "qbittorrent": { + "memory_current_bytes": 10743808, + "cpu_usage_usec": 341934 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636309 + } + } + }, + { + "elapsed_seconds": 32.307586421999986, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 88805376, + "cpu_usage_usec": 4043926 + }, + "prowlarr": { + "memory_current_bytes": 114798592, + "cpu_usage_usec": 7122319 + }, + "qbittorrent": { + "memory_current_bytes": 10743808, + "cpu_usage_usec": 342258 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636309 + } + } + }, + { + "elapsed_seconds": 32.40847011999995, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 88805376, + "cpu_usage_usec": 4043926 + }, + "prowlarr": { + "memory_current_bytes": 114798592, + "cpu_usage_usec": 7122533 + }, + "qbittorrent": { + "memory_current_bytes": 10715136, + "cpu_usage_usec": 342359 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636309 + } + } + }, + { + "elapsed_seconds": 32.50936224199995, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 88805376, + "cpu_usage_usec": 4043926 + }, + "prowlarr": { + "memory_current_bytes": 114798592, + "cpu_usage_usec": 7122533 + }, + "qbittorrent": { + "memory_current_bytes": 10715136, + "cpu_usage_usec": 342737 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636389 + } + } + }, + { + "elapsed_seconds": 32.61020455000016, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 88805376, + "cpu_usage_usec": 4043926 + }, + "prowlarr": { + "memory_current_bytes": 114798592, + "cpu_usage_usec": 7123375 + }, + "qbittorrent": { + "memory_current_bytes": 10715136, + "cpu_usage_usec": 342948 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636389 + } + } + }, + { + "elapsed_seconds": 32.71061169400036, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 88805376, + "cpu_usage_usec": 4043926 + }, + "prowlarr": { + "memory_current_bytes": 114421760, + "cpu_usage_usec": 7123375 + }, + "qbittorrent": { + "memory_current_bytes": 10715136, + "cpu_usage_usec": 343277 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636389 + } + } + }, + { + "elapsed_seconds": 32.81122168300044, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 88805376, + "cpu_usage_usec": 4044093 + }, + "prowlarr": { + "memory_current_bytes": 114421760, + "cpu_usage_usec": 7123375 + }, + "qbittorrent": { + "memory_current_bytes": 10657792, + "cpu_usage_usec": 343338 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636389 + } + } + }, + { + "elapsed_seconds": 32.91183675800039, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 89067520, + "cpu_usage_usec": 4047251 + }, + "prowlarr": { + "memory_current_bytes": 114683904, + "cpu_usage_usec": 7123420 + }, + "qbittorrent": { + "memory_current_bytes": 10616832, + "cpu_usage_usec": 343338 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636389 + } + } + }, + { + "elapsed_seconds": 33.01231474500037, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 89067520, + "cpu_usage_usec": 4047251 + }, + "prowlarr": { + "memory_current_bytes": 114429952, + "cpu_usage_usec": 7123420 + }, + "qbittorrent": { + "memory_current_bytes": 10686464, + "cpu_usage_usec": 343432 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636389 + } + } + }, + { + "elapsed_seconds": 33.11284808900018, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 89067520, + "cpu_usage_usec": 4047251 + }, + "prowlarr": { + "memory_current_bytes": 114679808, + "cpu_usage_usec": 7123420 + }, + "qbittorrent": { + "memory_current_bytes": 10686464, + "cpu_usage_usec": 343558 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636389 + } + } + }, + { + "elapsed_seconds": 33.213615442000446, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 89886720, + "cpu_usage_usec": 4057847 + }, + "prowlarr": { + "memory_current_bytes": 115707904, + "cpu_usage_usec": 7138900 + }, + "qbittorrent": { + "memory_current_bytes": 10424320, + "cpu_usage_usec": 343638 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636389 + } + } + }, + { + "elapsed_seconds": 33.314046142000734, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 89636864, + "cpu_usage_usec": 4057847 + }, + "prowlarr": { + "memory_current_bytes": 115687424, + "cpu_usage_usec": 7139219 + }, + "qbittorrent": { + "memory_current_bytes": 10948608, + "cpu_usage_usec": 344172 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636389 + } + } + }, + { + "elapsed_seconds": 33.414914365000186, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 89636864, + "cpu_usage_usec": 4057847 + }, + "prowlarr": { + "memory_current_bytes": 115687424, + "cpu_usage_usec": 7139219 + }, + "qbittorrent": { + "memory_current_bytes": 10948608, + "cpu_usage_usec": 344363 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636389 + } + } + }, + { + "elapsed_seconds": 33.51582337700074, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 89632768, + "cpu_usage_usec": 4057847 + }, + "prowlarr": { + "memory_current_bytes": 115687424, + "cpu_usage_usec": 7139219 + }, + "qbittorrent": { + "memory_current_bytes": 10948608, + "cpu_usage_usec": 344597 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636454 + } + } + }, + { + "elapsed_seconds": 33.61665275300038, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 89382912, + "cpu_usage_usec": 4057847 + }, + "prowlarr": { + "memory_current_bytes": 115687424, + "cpu_usage_usec": 7140688 + }, + "qbittorrent": { + "memory_current_bytes": 10948608, + "cpu_usage_usec": 344626 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636454 + } + } + }, + { + "elapsed_seconds": 33.717349314000785, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 89382912, + "cpu_usage_usec": 4057884 + }, + "prowlarr": { + "memory_current_bytes": 115286016, + "cpu_usage_usec": 7141644 + }, + "qbittorrent": { + "memory_current_bytes": 10948608, + "cpu_usage_usec": 344626 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636454 + } + } + }, + { + "elapsed_seconds": 33.81828326200048, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 89382912, + "cpu_usage_usec": 4058012 + }, + "prowlarr": { + "memory_current_bytes": 115286016, + "cpu_usage_usec": 7146107 + }, + "qbittorrent": { + "memory_current_bytes": 10948608, + "cpu_usage_usec": 344626 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636454 + } + } + }, + { + "elapsed_seconds": 33.91916237900023, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 89124864, + "cpu_usage_usec": 4058012 + }, + "prowlarr": { + "memory_current_bytes": 115286016, + "cpu_usage_usec": 7147733 + }, + "qbittorrent": { + "memory_current_bytes": 10481664, + "cpu_usage_usec": 344626 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636454 + } + } + }, + { + "elapsed_seconds": 34.02005941100015, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 89124864, + "cpu_usage_usec": 4058012 + }, + "prowlarr": { + "memory_current_bytes": 115355648, + "cpu_usage_usec": 7148117 + }, + "qbittorrent": { + "memory_current_bytes": 10481664, + "cpu_usage_usec": 344695 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636454 + } + } + }, + { + "elapsed_seconds": 34.1208666120001, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 89120768, + "cpu_usage_usec": 4058012 + }, + "prowlarr": { + "memory_current_bytes": 114860032, + "cpu_usage_usec": 7148117 + }, + "qbittorrent": { + "memory_current_bytes": 10440704, + "cpu_usage_usec": 344695 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636454 + } + } + }, + { + "elapsed_seconds": 34.222242281000035, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 89120768, + "cpu_usage_usec": 4058080 + }, + "prowlarr": { + "memory_current_bytes": 114860032, + "cpu_usage_usec": 7148493 + }, + "qbittorrent": { + "memory_current_bytes": 10440704, + "cpu_usage_usec": 344841 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636454 + } + } + }, + { + "elapsed_seconds": 34.32309362600063, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 89120768, + "cpu_usage_usec": 4058080 + }, + "prowlarr": { + "memory_current_bytes": 115372032, + "cpu_usage_usec": 7155390 + }, + "qbittorrent": { + "memory_current_bytes": 10424320, + "cpu_usage_usec": 345053 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636454 + } + } + }, + { + "elapsed_seconds": 34.42365046300074, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 89120768, + "cpu_usage_usec": 4058080 + }, + "prowlarr": { + "memory_current_bytes": 115372032, + "cpu_usage_usec": 7156880 + }, + "qbittorrent": { + "memory_current_bytes": 10424320, + "cpu_usage_usec": 345053 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636454 + } + } + }, + { + "elapsed_seconds": 34.524242657000286, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 89120768, + "cpu_usage_usec": 4058080 + }, + "prowlarr": { + "memory_current_bytes": 117145600, + "cpu_usage_usec": 7187593 + }, + "qbittorrent": { + "memory_current_bytes": 10948608, + "cpu_usage_usec": 345443 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636541 + } + } + }, + { + "elapsed_seconds": 34.62515107700074, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 89120768, + "cpu_usage_usec": 4058080 + }, + "prowlarr": { + "memory_current_bytes": 119947264, + "cpu_usage_usec": 7248033 + }, + "qbittorrent": { + "memory_current_bytes": 10948608, + "cpu_usage_usec": 345610 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636541 + } + } + }, + { + "elapsed_seconds": 34.72617272900061, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 89120768, + "cpu_usage_usec": 4058080 + }, + "prowlarr": { + "memory_current_bytes": 119943168, + "cpu_usage_usec": 7248033 + }, + "qbittorrent": { + "memory_current_bytes": 10948608, + "cpu_usage_usec": 345690 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636541 + } + } + }, + { + "elapsed_seconds": 34.826717796000594, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 89120768, + "cpu_usage_usec": 4058202 + }, + "prowlarr": { + "memory_current_bytes": 119922688, + "cpu_usage_usec": 7248083 + }, + "qbittorrent": { + "memory_current_bytes": 10915840, + "cpu_usage_usec": 345993 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636541 + } + } + }, + { + "elapsed_seconds": 34.927548216000105, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 89120768, + "cpu_usage_usec": 4058202 + }, + "prowlarr": { + "memory_current_bytes": 119734272, + "cpu_usage_usec": 7248083 + }, + "qbittorrent": { + "memory_current_bytes": 10895360, + "cpu_usage_usec": 345993 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636541 + } + } + }, + { + "elapsed_seconds": 35.02847447900058, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 89120768, + "cpu_usage_usec": 4058202 + }, + "prowlarr": { + "memory_current_bytes": 119545856, + "cpu_usage_usec": 7248083 + }, + "qbittorrent": { + "memory_current_bytes": 10674176, + "cpu_usage_usec": 346119 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636541 + } + } + }, + { + "elapsed_seconds": 35.12892121599998, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 89120768, + "cpu_usage_usec": 4058202 + }, + "prowlarr": { + "memory_current_bytes": 119545856, + "cpu_usage_usec": 7248137 + }, + "qbittorrent": { + "memory_current_bytes": 10977280, + "cpu_usage_usec": 346900 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636541 + } + } + }, + { + "elapsed_seconds": 35.22980379500041, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91238400, + "cpu_usage_usec": 4109393 + }, + "prowlarr": { + "memory_current_bytes": 119316480, + "cpu_usage_usec": 7248153 + }, + "qbittorrent": { + "memory_current_bytes": 10977280, + "cpu_usage_usec": 347120 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636541 + } + } + }, + { + "elapsed_seconds": 35.33082831000047, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91398144, + "cpu_usage_usec": 4158899 + }, + "prowlarr": { + "memory_current_bytes": 118599680, + "cpu_usage_usec": 7249951 + }, + "qbittorrent": { + "memory_current_bytes": 10977280, + "cpu_usage_usec": 347591 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636541 + } + } + }, + { + "elapsed_seconds": 35.431690582000556, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91492352, + "cpu_usage_usec": 4181669 + }, + "prowlarr": { + "memory_current_bytes": 118599680, + "cpu_usage_usec": 7249951 + }, + "qbittorrent": { + "memory_current_bytes": 10977280, + "cpu_usage_usec": 347961 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636541 + } + } + }, + { + "elapsed_seconds": 35.53254090000064, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91492352, + "cpu_usage_usec": 4181669 + }, + "prowlarr": { + "memory_current_bytes": 118599680, + "cpu_usage_usec": 7250054 + }, + "qbittorrent": { + "memory_current_bytes": 10977280, + "cpu_usage_usec": 348800 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636599 + } + } + }, + { + "elapsed_seconds": 35.63361064400033, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91492352, + "cpu_usage_usec": 4181669 + }, + "prowlarr": { + "memory_current_bytes": 118599680, + "cpu_usage_usec": 7250054 + }, + "qbittorrent": { + "memory_current_bytes": 10702848, + "cpu_usage_usec": 349186 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636599 + } + } + }, + { + "elapsed_seconds": 35.73429462000058, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91492352, + "cpu_usage_usec": 4181669 + }, + "prowlarr": { + "memory_current_bytes": 118599680, + "cpu_usage_usec": 7250127 + }, + "qbittorrent": { + "memory_current_bytes": 10698752, + "cpu_usage_usec": 349935 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636599 + } + } + }, + { + "elapsed_seconds": 35.835172656000395, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91492352, + "cpu_usage_usec": 4185854 + }, + "prowlarr": { + "memory_current_bytes": 118595584, + "cpu_usage_usec": 7250470 + }, + "qbittorrent": { + "memory_current_bytes": 10596352, + "cpu_usage_usec": 351070 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636599 + } + } + }, + { + "elapsed_seconds": 35.93615437600056, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91492352, + "cpu_usage_usec": 4185854 + }, + "prowlarr": { + "memory_current_bytes": 118595584, + "cpu_usage_usec": 7250470 + }, + "qbittorrent": { + "memory_current_bytes": 10596352, + "cpu_usage_usec": 352025 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636599 + } + } + }, + { + "elapsed_seconds": 36.03707144800046, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91492352, + "cpu_usage_usec": 4185854 + }, + "prowlarr": { + "memory_current_bytes": 118595584, + "cpu_usage_usec": 7250470 + }, + "qbittorrent": { + "memory_current_bytes": 10858496, + "cpu_usage_usec": 352985 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636599 + } + } + }, + { + "elapsed_seconds": 36.13790958300069, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91492352, + "cpu_usage_usec": 4185854 + }, + "prowlarr": { + "memory_current_bytes": 118849536, + "cpu_usage_usec": 7256644 + }, + "qbittorrent": { + "memory_current_bytes": 10620928, + "cpu_usage_usec": 353560 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636599 + } + } + }, + { + "elapsed_seconds": 36.23841452800025, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91492352, + "cpu_usage_usec": 4185854 + }, + "prowlarr": { + "memory_current_bytes": 119066624, + "cpu_usage_usec": 7337802 + }, + "qbittorrent": { + "memory_current_bytes": 10883072, + "cpu_usage_usec": 353792 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636599 + } + } + }, + { + "elapsed_seconds": 36.33883411400075, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91402240, + "cpu_usage_usec": 4185854 + }, + "prowlarr": { + "memory_current_bytes": 119300096, + "cpu_usage_usec": 7389103 + }, + "qbittorrent": { + "memory_current_bytes": 10883072, + "cpu_usage_usec": 354506 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636599 + } + } + }, + { + "elapsed_seconds": 36.439352629000496, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91402240, + "cpu_usage_usec": 4185854 + }, + "prowlarr": { + "memory_current_bytes": 119287808, + "cpu_usage_usec": 7439018 + }, + "qbittorrent": { + "memory_current_bytes": 10883072, + "cpu_usage_usec": 354634 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636599 + } + } + }, + { + "elapsed_seconds": 36.53977437699996, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91922432, + "cpu_usage_usec": 4187649 + }, + "prowlarr": { + "memory_current_bytes": 119300096, + "cpu_usage_usec": 7489965 + }, + "qbittorrent": { + "memory_current_bytes": 11145216, + "cpu_usage_usec": 354973 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636627 + } + } + }, + { + "elapsed_seconds": 36.64021260200025, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91922432, + "cpu_usage_usec": 4187649 + }, + "prowlarr": { + "memory_current_bytes": 126062592, + "cpu_usage_usec": 7540791 + }, + "qbittorrent": { + "memory_current_bytes": 10878976, + "cpu_usage_usec": 355319 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636627 + } + } + }, + { + "elapsed_seconds": 36.74058935500034, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91922432, + "cpu_usage_usec": 4187649 + }, + "prowlarr": { + "memory_current_bytes": 126554112, + "cpu_usage_usec": 7585644 + }, + "qbittorrent": { + "memory_current_bytes": 10829824, + "cpu_usage_usec": 355814 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636627 + } + } + }, + { + "elapsed_seconds": 36.84158161400046, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91922432, + "cpu_usage_usec": 4187764 + }, + "prowlarr": { + "memory_current_bytes": 126545920, + "cpu_usage_usec": 7594408 + }, + "qbittorrent": { + "memory_current_bytes": 10817536, + "cpu_usage_usec": 356435 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636627 + } + } + }, + { + "elapsed_seconds": 36.942054868000014, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91922432, + "cpu_usage_usec": 4187764 + }, + "prowlarr": { + "memory_current_bytes": 126545920, + "cpu_usage_usec": 7594408 + }, + "qbittorrent": { + "memory_current_bytes": 10731520, + "cpu_usage_usec": 356761 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636627 + } + } + }, + { + "elapsed_seconds": 37.04295189300046, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91922432, + "cpu_usage_usec": 4187807 + }, + "prowlarr": { + "memory_current_bytes": 126545920, + "cpu_usage_usec": 7594408 + }, + "qbittorrent": { + "memory_current_bytes": 10731520, + "cpu_usage_usec": 357412 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636627 + } + } + }, + { + "elapsed_seconds": 37.1439515280008, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91922432, + "cpu_usage_usec": 4187807 + }, + "prowlarr": { + "memory_current_bytes": 126545920, + "cpu_usage_usec": 7594484 + }, + "qbittorrent": { + "memory_current_bytes": 10731520, + "cpu_usage_usec": 357412 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636627 + } + } + }, + { + "elapsed_seconds": 37.244823844000166, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91922432, + "cpu_usage_usec": 4187807 + }, + "prowlarr": { + "memory_current_bytes": 126808064, + "cpu_usage_usec": 7594542 + }, + "qbittorrent": { + "memory_current_bytes": 10731520, + "cpu_usage_usec": 357563 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636627 + } + } + }, + { + "elapsed_seconds": 37.34569165600078, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91922432, + "cpu_usage_usec": 4187807 + }, + "prowlarr": { + "memory_current_bytes": 126808064, + "cpu_usage_usec": 7596296 + }, + "qbittorrent": { + "memory_current_bytes": 10731520, + "cpu_usage_usec": 357563 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636627 + } + } + }, + { + "elapsed_seconds": 37.44654245700076, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91922432, + "cpu_usage_usec": 4187807 + }, + "prowlarr": { + "memory_current_bytes": 126808064, + "cpu_usage_usec": 7596296 + }, + "qbittorrent": { + "memory_current_bytes": 10731520, + "cpu_usage_usec": 357563 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636627 + } + } + }, + { + "elapsed_seconds": 37.5474110590003, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91922432, + "cpu_usage_usec": 4187874 + }, + "prowlarr": { + "memory_current_bytes": 126808064, + "cpu_usage_usec": 7596383 + }, + "qbittorrent": { + "memory_current_bytes": 10731520, + "cpu_usage_usec": 357621 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636709 + } + } + }, + { + "elapsed_seconds": 37.64802592700016, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91660288, + "cpu_usage_usec": 4187874 + }, + "prowlarr": { + "memory_current_bytes": 126734336, + "cpu_usage_usec": 7596383 + }, + "qbittorrent": { + "memory_current_bytes": 10690560, + "cpu_usage_usec": 357621 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636709 + } + } + }, + { + "elapsed_seconds": 37.74884017600016, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91660288, + "cpu_usage_usec": 4187874 + }, + "prowlarr": { + "memory_current_bytes": 126476288, + "cpu_usage_usec": 7596383 + }, + "qbittorrent": { + "memory_current_bytes": 10690560, + "cpu_usage_usec": 357621 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636709 + } + } + }, + { + "elapsed_seconds": 37.84982766900066, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91660288, + "cpu_usage_usec": 4187995 + }, + "prowlarr": { + "memory_current_bytes": 126476288, + "cpu_usage_usec": 7596438 + }, + "qbittorrent": { + "memory_current_bytes": 10690560, + "cpu_usage_usec": 357621 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636709 + } + } + }, + { + "elapsed_seconds": 37.95075216400073, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91422720, + "cpu_usage_usec": 4187995 + }, + "prowlarr": { + "memory_current_bytes": 126476288, + "cpu_usage_usec": 7596438 + }, + "qbittorrent": { + "memory_current_bytes": 10661888, + "cpu_usage_usec": 357621 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636709 + } + } + }, + { + "elapsed_seconds": 38.05186190400036, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91422720, + "cpu_usage_usec": 4187995 + }, + "prowlarr": { + "memory_current_bytes": 126476288, + "cpu_usage_usec": 7596438 + }, + "qbittorrent": { + "memory_current_bytes": 10661888, + "cpu_usage_usec": 357640 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636709 + } + } + }, + { + "elapsed_seconds": 38.15273774800062, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91422720, + "cpu_usage_usec": 4187995 + }, + "prowlarr": { + "memory_current_bytes": 126476288, + "cpu_usage_usec": 7596438 + }, + "qbittorrent": { + "memory_current_bytes": 10661888, + "cpu_usage_usec": 357640 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636709 + } + } + }, + { + "elapsed_seconds": 38.25317517400072, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92200960, + "cpu_usage_usec": 4195771 + }, + "prowlarr": { + "memory_current_bytes": 127746048, + "cpu_usage_usec": 7613196 + }, + "qbittorrent": { + "memory_current_bytes": 10661888, + "cpu_usage_usec": 357640 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636709 + } + } + }, + { + "elapsed_seconds": 38.35411472400028, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92200960, + "cpu_usage_usec": 4195771 + }, + "prowlarr": { + "memory_current_bytes": 127746048, + "cpu_usage_usec": 7613518 + }, + "qbittorrent": { + "memory_current_bytes": 10645504, + "cpu_usage_usec": 357640 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636709 + } + } + }, + { + "elapsed_seconds": 38.45530575200064, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92200960, + "cpu_usage_usec": 4195771 + }, + "prowlarr": { + "memory_current_bytes": 127746048, + "cpu_usage_usec": 7613518 + }, + "qbittorrent": { + "memory_current_bytes": 10645504, + "cpu_usage_usec": 357640 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636709 + } + } + }, + { + "elapsed_seconds": 38.5571296800008, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92200960, + "cpu_usage_usec": 4195776 + }, + "prowlarr": { + "memory_current_bytes": 127488000, + "cpu_usage_usec": 7613644 + }, + "qbittorrent": { + "memory_current_bytes": 10645504, + "cpu_usage_usec": 357703 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636767 + } + } + }, + { + "elapsed_seconds": 38.65811411300001, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92200960, + "cpu_usage_usec": 4195776 + }, + "prowlarr": { + "memory_current_bytes": 127488000, + "cpu_usage_usec": 7613731 + }, + "qbittorrent": { + "memory_current_bytes": 10645504, + "cpu_usage_usec": 357703 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636767 + } + } + }, + { + "elapsed_seconds": 38.759100203000344, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91938816, + "cpu_usage_usec": 4195830 + }, + "prowlarr": { + "memory_current_bytes": 127488000, + "cpu_usage_usec": 7615066 + }, + "qbittorrent": { + "memory_current_bytes": 10645504, + "cpu_usage_usec": 357876 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636767 + } + } + }, + { + "elapsed_seconds": 38.86003339400031, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91938816, + "cpu_usage_usec": 4195999 + }, + "prowlarr": { + "memory_current_bytes": 127229952, + "cpu_usage_usec": 7615066 + }, + "qbittorrent": { + "memory_current_bytes": 10645504, + "cpu_usage_usec": 357876 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636767 + } + } + }, + { + "elapsed_seconds": 38.96104226400075, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91680768, + "cpu_usage_usec": 4195999 + }, + "prowlarr": { + "memory_current_bytes": 127033344, + "cpu_usage_usec": 7615066 + }, + "qbittorrent": { + "memory_current_bytes": 10907648, + "cpu_usage_usec": 358191 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636767 + } + } + }, + { + "elapsed_seconds": 39.061980134000805, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91680768, + "cpu_usage_usec": 4195999 + }, + "prowlarr": { + "memory_current_bytes": 127033344, + "cpu_usage_usec": 7615066 + }, + "qbittorrent": { + "memory_current_bytes": 10907648, + "cpu_usage_usec": 358242 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636767 + } + } + }, + { + "elapsed_seconds": 39.16277404500033, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91426816, + "cpu_usage_usec": 4195999 + }, + "prowlarr": { + "memory_current_bytes": 126746624, + "cpu_usage_usec": 7615945 + }, + "qbittorrent": { + "memory_current_bytes": 10645504, + "cpu_usage_usec": 358242 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636767 + } + } + }, + { + "elapsed_seconds": 39.263600387000224, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91426816, + "cpu_usage_usec": 4196049 + }, + "prowlarr": { + "memory_current_bytes": 126746624, + "cpu_usage_usec": 7615979 + }, + "qbittorrent": { + "memory_current_bytes": 10645504, + "cpu_usage_usec": 358278 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636767 + } + } + }, + { + "elapsed_seconds": 39.36443882200001, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91426816, + "cpu_usage_usec": 4196049 + }, + "prowlarr": { + "memory_current_bytes": 126746624, + "cpu_usage_usec": 7616469 + }, + "qbittorrent": { + "memory_current_bytes": 10645504, + "cpu_usage_usec": 358278 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636767 + } + } + }, + { + "elapsed_seconds": 39.465325398999994, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91426816, + "cpu_usage_usec": 4196049 + }, + "prowlarr": { + "memory_current_bytes": 126746624, + "cpu_usage_usec": 7616469 + }, + "qbittorrent": { + "memory_current_bytes": 10645504, + "cpu_usage_usec": 358278 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636823 + } + } + }, + { + "elapsed_seconds": 39.56592995900064, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91963392, + "cpu_usage_usec": 4274040 + }, + "prowlarr": { + "memory_current_bytes": 126459904, + "cpu_usage_usec": 7616751 + }, + "qbittorrent": { + "memory_current_bytes": 10645504, + "cpu_usage_usec": 358311 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636823 + } + } + }, + { + "elapsed_seconds": 39.66632611500063, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91959296, + "cpu_usage_usec": 4298471 + }, + "prowlarr": { + "memory_current_bytes": 128131072, + "cpu_usage_usec": 7660820 + }, + "qbittorrent": { + "memory_current_bytes": 10645504, + "cpu_usage_usec": 358311 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636823 + } + } + }, + { + "elapsed_seconds": 39.767016360000525, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91959296, + "cpu_usage_usec": 4298471 + }, + "prowlarr": { + "memory_current_bytes": 128786432, + "cpu_usage_usec": 7720122 + }, + "qbittorrent": { + "memory_current_bytes": 10645504, + "cpu_usage_usec": 358311 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636823 + } + } + }, + { + "elapsed_seconds": 39.8678734770001, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92209152, + "cpu_usage_usec": 4298732 + }, + "prowlarr": { + "memory_current_bytes": 129191936, + "cpu_usage_usec": 7767481 + }, + "qbittorrent": { + "memory_current_bytes": 10645504, + "cpu_usage_usec": 358311 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636823 + } + } + }, + { + "elapsed_seconds": 39.968609748000745, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92209152, + "cpu_usage_usec": 4298732 + }, + "prowlarr": { + "memory_current_bytes": 129601536, + "cpu_usage_usec": 7817171 + }, + "qbittorrent": { + "memory_current_bytes": 10645504, + "cpu_usage_usec": 358311 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636823 + } + } + }, + { + "elapsed_seconds": 40.06950845300071, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92209152, + "cpu_usage_usec": 4298732 + }, + "prowlarr": { + "memory_current_bytes": 129851392, + "cpu_usage_usec": 7841035 + }, + "qbittorrent": { + "memory_current_bytes": 10645504, + "cpu_usage_usec": 358353 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636823 + } + } + }, + { + "elapsed_seconds": 40.17044907400032, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92209152, + "cpu_usage_usec": 4298756 + }, + "prowlarr": { + "memory_current_bytes": 129683456, + "cpu_usage_usec": 7841060 + }, + "qbittorrent": { + "memory_current_bytes": 10645504, + "cpu_usage_usec": 358353 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636823 + } + } + }, + { + "elapsed_seconds": 40.271359416999985, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92209152, + "cpu_usage_usec": 4298756 + }, + "prowlarr": { + "memory_current_bytes": 129806336, + "cpu_usage_usec": 7857935 + }, + "qbittorrent": { + "memory_current_bytes": 10645504, + "cpu_usage_usec": 358464 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636823 + } + } + }, + { + "elapsed_seconds": 40.37224589300058, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92209152, + "cpu_usage_usec": 4298756 + }, + "prowlarr": { + "memory_current_bytes": 129806336, + "cpu_usage_usec": 7858454 + }, + "qbittorrent": { + "memory_current_bytes": 11169792, + "cpu_usage_usec": 358815 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636823 + } + } + }, + { + "elapsed_seconds": 40.473283403000096, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92209152, + "cpu_usage_usec": 4298756 + }, + "prowlarr": { + "memory_current_bytes": 129806336, + "cpu_usage_usec": 7858454 + }, + "qbittorrent": { + "memory_current_bytes": 10903552, + "cpu_usage_usec": 359495 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636886 + } + } + }, + { + "elapsed_seconds": 40.57424375000028, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91947008, + "cpu_usage_usec": 4298756 + }, + "prowlarr": { + "memory_current_bytes": 129806336, + "cpu_usage_usec": 7859058 + }, + "qbittorrent": { + "memory_current_bytes": 10903552, + "cpu_usage_usec": 360326 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636886 + } + } + }, + { + "elapsed_seconds": 40.67505421400074, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91947008, + "cpu_usage_usec": 4298756 + }, + "prowlarr": { + "memory_current_bytes": 129622016, + "cpu_usage_usec": 7859105 + }, + "qbittorrent": { + "memory_current_bytes": 11165696, + "cpu_usage_usec": 361175 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636886 + } + } + }, + { + "elapsed_seconds": 40.776080769000146, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91947008, + "cpu_usage_usec": 4298756 + }, + "prowlarr": { + "memory_current_bytes": 129622016, + "cpu_usage_usec": 7859637 + }, + "qbittorrent": { + "memory_current_bytes": 10899456, + "cpu_usage_usec": 362015 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636886 + } + } + }, + { + "elapsed_seconds": 40.87736328200026, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91947008, + "cpu_usage_usec": 4299778 + }, + "prowlarr": { + "memory_current_bytes": 129622016, + "cpu_usage_usec": 7859637 + }, + "qbittorrent": { + "memory_current_bytes": 10797056, + "cpu_usage_usec": 362185 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636886 + } + } + }, + { + "elapsed_seconds": 40.978263053000774, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91947008, + "cpu_usage_usec": 4299778 + }, + "prowlarr": { + "memory_current_bytes": 129622016, + "cpu_usage_usec": 7860132 + }, + "qbittorrent": { + "memory_current_bytes": 11059200, + "cpu_usage_usec": 362411 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636886 + } + } + }, + { + "elapsed_seconds": 41.079162353000356, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91947008, + "cpu_usage_usec": 4299778 + }, + "prowlarr": { + "memory_current_bytes": 130146304, + "cpu_usage_usec": 7863008 + }, + "qbittorrent": { + "memory_current_bytes": 11059200, + "cpu_usage_usec": 362671 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636886 + } + } + }, + { + "elapsed_seconds": 41.179994920000354, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91934720, + "cpu_usage_usec": 4299778 + }, + "prowlarr": { + "memory_current_bytes": 130146304, + "cpu_usage_usec": 7864002 + }, + "qbittorrent": { + "memory_current_bytes": 11059200, + "cpu_usage_usec": 362903 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636886 + } + } + }, + { + "elapsed_seconds": 41.280926953000744, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92196864, + "cpu_usage_usec": 4301103 + }, + "prowlarr": { + "memory_current_bytes": 124063744, + "cpu_usage_usec": 7877227 + }, + "qbittorrent": { + "memory_current_bytes": 10739712, + "cpu_usage_usec": 363320 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636886 + } + } + }, + { + "elapsed_seconds": 41.381772778000595, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92979200, + "cpu_usage_usec": 4306927 + }, + "prowlarr": { + "memory_current_bytes": 123838464, + "cpu_usage_usec": 7887740 + }, + "qbittorrent": { + "memory_current_bytes": 11001856, + "cpu_usage_usec": 363480 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636886 + } + } + }, + { + "elapsed_seconds": 41.482719478000035, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92979200, + "cpu_usage_usec": 4306927 + }, + "prowlarr": { + "memory_current_bytes": 123838464, + "cpu_usage_usec": 7889325 + }, + "qbittorrent": { + "memory_current_bytes": 11001856, + "cpu_usage_usec": 363850 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636970 + } + } + }, + { + "elapsed_seconds": 41.58365537000009, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92979200, + "cpu_usage_usec": 4306927 + }, + "prowlarr": { + "memory_current_bytes": 123539456, + "cpu_usage_usec": 7889960 + }, + "qbittorrent": { + "memory_current_bytes": 11001856, + "cpu_usage_usec": 364139 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636970 + } + } + }, + { + "elapsed_seconds": 41.68452855100077, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92717056, + "cpu_usage_usec": 4306927 + }, + "prowlarr": { + "memory_current_bytes": 123289600, + "cpu_usage_usec": 7890024 + }, + "qbittorrent": { + "memory_current_bytes": 11264000, + "cpu_usage_usec": 364765 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636970 + } + } + }, + { + "elapsed_seconds": 41.784950545000356, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92717056, + "cpu_usage_usec": 4306966 + }, + "prowlarr": { + "memory_current_bytes": 123416576, + "cpu_usage_usec": 7890937 + }, + "qbittorrent": { + "memory_current_bytes": 11038720, + "cpu_usage_usec": 364849 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636970 + } + } + }, + { + "elapsed_seconds": 41.88563656000042, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92717056, + "cpu_usage_usec": 4307053 + }, + "prowlarr": { + "memory_current_bytes": 123416576, + "cpu_usage_usec": 7890937 + }, + "qbittorrent": { + "memory_current_bytes": 11038720, + "cpu_usage_usec": 365181 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636970 + } + } + }, + { + "elapsed_seconds": 41.98653381500026, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92196864, + "cpu_usage_usec": 4307053 + }, + "prowlarr": { + "memory_current_bytes": 123416576, + "cpu_usage_usec": 7890937 + }, + "qbittorrent": { + "memory_current_bytes": 11038720, + "cpu_usage_usec": 365181 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636970 + } + } + }, + { + "elapsed_seconds": 42.087437000000136, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92196864, + "cpu_usage_usec": 4307053 + }, + "prowlarr": { + "memory_current_bytes": 123416576, + "cpu_usage_usec": 7890937 + }, + "qbittorrent": { + "memory_current_bytes": 11038720, + "cpu_usage_usec": 365225 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636970 + } + } + }, + { + "elapsed_seconds": 42.18827947700083, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92196864, + "cpu_usage_usec": 4307053 + }, + "prowlarr": { + "memory_current_bytes": 123416576, + "cpu_usage_usec": 7891012 + }, + "qbittorrent": { + "memory_current_bytes": 11038720, + "cpu_usage_usec": 365225 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636970 + } + } + }, + { + "elapsed_seconds": 42.289285851000386, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92196864, + "cpu_usage_usec": 4307135 + }, + "prowlarr": { + "memory_current_bytes": 123416576, + "cpu_usage_usec": 7891386 + }, + "qbittorrent": { + "memory_current_bytes": 11038720, + "cpu_usage_usec": 365225 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636970 + } + } + }, + { + "elapsed_seconds": 42.390217173000565, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91938816, + "cpu_usage_usec": 4307135 + }, + "prowlarr": { + "memory_current_bytes": 123416576, + "cpu_usage_usec": 7891679 + }, + "qbittorrent": { + "memory_current_bytes": 11038720, + "cpu_usage_usec": 365225 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1636970 + } + } + }, + { + "elapsed_seconds": 42.49113616100021, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91938816, + "cpu_usage_usec": 4307135 + }, + "prowlarr": { + "memory_current_bytes": 123416576, + "cpu_usage_usec": 7891679 + }, + "qbittorrent": { + "memory_current_bytes": 11038720, + "cpu_usage_usec": 365225 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637045 + } + } + }, + { + "elapsed_seconds": 42.59203267000066, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91938816, + "cpu_usage_usec": 4307135 + }, + "prowlarr": { + "memory_current_bytes": 123416576, + "cpu_usage_usec": 7891797 + }, + "qbittorrent": { + "memory_current_bytes": 11038720, + "cpu_usage_usec": 365259 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637045 + } + } + }, + { + "elapsed_seconds": 42.692901183000686, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91938816, + "cpu_usage_usec": 4307135 + }, + "prowlarr": { + "memory_current_bytes": 123416576, + "cpu_usage_usec": 7892150 + }, + "qbittorrent": { + "memory_current_bytes": 11038720, + "cpu_usage_usec": 365259 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637045 + } + } + }, + { + "elapsed_seconds": 42.79372096700081, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91938816, + "cpu_usage_usec": 4307135 + }, + "prowlarr": { + "memory_current_bytes": 123416576, + "cpu_usage_usec": 7892150 + }, + "qbittorrent": { + "memory_current_bytes": 11038720, + "cpu_usage_usec": 365351 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637045 + } + } + }, + { + "elapsed_seconds": 42.89468349600065, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91938816, + "cpu_usage_usec": 4307224 + }, + "prowlarr": { + "memory_current_bytes": 123416576, + "cpu_usage_usec": 7892150 + }, + "qbittorrent": { + "memory_current_bytes": 11038720, + "cpu_usage_usec": 365351 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637045 + } + } + }, + { + "elapsed_seconds": 42.995500582000204, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91938816, + "cpu_usage_usec": 4307224 + }, + "prowlarr": { + "memory_current_bytes": 123183104, + "cpu_usage_usec": 7892150 + }, + "qbittorrent": { + "memory_current_bytes": 11038720, + "cpu_usage_usec": 365443 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637045 + } + } + }, + { + "elapsed_seconds": 43.09648195000045, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91938816, + "cpu_usage_usec": 4307224 + }, + "prowlarr": { + "memory_current_bytes": 123183104, + "cpu_usage_usec": 7892150 + }, + "qbittorrent": { + "memory_current_bytes": 11038720, + "cpu_usage_usec": 365497 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637045 + } + } + }, + { + "elapsed_seconds": 43.19695440100077, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91938816, + "cpu_usage_usec": 4307224 + }, + "prowlarr": { + "memory_current_bytes": 122892288, + "cpu_usage_usec": 7895264 + }, + "qbittorrent": { + "memory_current_bytes": 10997760, + "cpu_usage_usec": 365577 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637045 + } + } + }, + { + "elapsed_seconds": 43.29743428200072, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92200960, + "cpu_usage_usec": 4324012 + }, + "prowlarr": { + "memory_current_bytes": 122892288, + "cpu_usage_usec": 7895264 + }, + "qbittorrent": { + "memory_current_bytes": 10838016, + "cpu_usage_usec": 365577 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637045 + } + } + }, + { + "elapsed_seconds": 43.398017869000796, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92422144, + "cpu_usage_usec": 4406985 + }, + "prowlarr": { + "memory_current_bytes": 122707968, + "cpu_usage_usec": 7895457 + }, + "qbittorrent": { + "memory_current_bytes": 11100160, + "cpu_usage_usec": 365577 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637045 + } + } + }, + { + "elapsed_seconds": 43.49856395200004, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92393472, + "cpu_usage_usec": 4406985 + }, + "prowlarr": { + "memory_current_bytes": 123232256, + "cpu_usage_usec": 7896482 + }, + "qbittorrent": { + "memory_current_bytes": 10850304, + "cpu_usage_usec": 365577 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637091 + } + } + }, + { + "elapsed_seconds": 43.59900788400046, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92254208, + "cpu_usage_usec": 4406985 + }, + "prowlarr": { + "memory_current_bytes": 123232256, + "cpu_usage_usec": 7897065 + }, + "qbittorrent": { + "memory_current_bytes": 11374592, + "cpu_usage_usec": 365782 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637091 + } + } + }, + { + "elapsed_seconds": 43.699996256000304, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92254208, + "cpu_usage_usec": 4406985 + }, + "prowlarr": { + "memory_current_bytes": 123912192, + "cpu_usage_usec": 7898568 + }, + "qbittorrent": { + "memory_current_bytes": 11309056, + "cpu_usage_usec": 366235 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637091 + } + } + }, + { + "elapsed_seconds": 43.80077237000023, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92254208, + "cpu_usage_usec": 4406985 + }, + "prowlarr": { + "memory_current_bytes": 124067840, + "cpu_usage_usec": 7909473 + }, + "qbittorrent": { + "memory_current_bytes": 11309056, + "cpu_usage_usec": 366235 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637091 + } + } + }, + { + "elapsed_seconds": 43.90165525500015, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92254208, + "cpu_usage_usec": 4407058 + }, + "prowlarr": { + "memory_current_bytes": 124067840, + "cpu_usage_usec": 7909473 + }, + "qbittorrent": { + "memory_current_bytes": 11309056, + "cpu_usage_usec": 366235 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637091 + } + } + }, + { + "elapsed_seconds": 44.0026387150001, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92254208, + "cpu_usage_usec": 4407058 + }, + "prowlarr": { + "memory_current_bytes": 124067840, + "cpu_usage_usec": 7909473 + }, + "qbittorrent": { + "memory_current_bytes": 11124736, + "cpu_usage_usec": 366235 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637091 + } + } + }, + { + "elapsed_seconds": 44.10358874300073, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92254208, + "cpu_usage_usec": 4407058 + }, + "prowlarr": { + "memory_current_bytes": 124063744, + "cpu_usage_usec": 7909473 + }, + "qbittorrent": { + "memory_current_bytes": 11124736, + "cpu_usage_usec": 366256 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637091 + } + } + }, + { + "elapsed_seconds": 44.20441899200068, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92254208, + "cpu_usage_usec": 4407058 + }, + "prowlarr": { + "memory_current_bytes": 123813888, + "cpu_usage_usec": 7909514 + }, + "qbittorrent": { + "memory_current_bytes": 11329536, + "cpu_usage_usec": 366462 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637091 + } + } + }, + { + "elapsed_seconds": 44.30533131700031, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92254208, + "cpu_usage_usec": 4407058 + }, + "prowlarr": { + "memory_current_bytes": 123813888, + "cpu_usage_usec": 7909514 + }, + "qbittorrent": { + "memory_current_bytes": 11321344, + "cpu_usage_usec": 366462 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637091 + } + } + }, + { + "elapsed_seconds": 44.40603493600065, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92254208, + "cpu_usage_usec": 4407058 + }, + "prowlarr": { + "memory_current_bytes": 124076032, + "cpu_usage_usec": 7909937 + }, + "qbittorrent": { + "memory_current_bytes": 11321344, + "cpu_usage_usec": 366462 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637091 + } + } + }, + { + "elapsed_seconds": 44.50641681600064, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92254208, + "cpu_usage_usec": 4407058 + }, + "prowlarr": { + "memory_current_bytes": 124076032, + "cpu_usage_usec": 7910180 + }, + "qbittorrent": { + "memory_current_bytes": 11321344, + "cpu_usage_usec": 366462 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637113 + } + } + }, + { + "elapsed_seconds": 44.60687422200044, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92254208, + "cpu_usage_usec": 4407058 + }, + "prowlarr": { + "memory_current_bytes": 123822080, + "cpu_usage_usec": 7910246 + }, + "qbittorrent": { + "memory_current_bytes": 11321344, + "cpu_usage_usec": 366502 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637113 + } + } + }, + { + "elapsed_seconds": 44.707668915000795, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92254208, + "cpu_usage_usec": 4407058 + }, + "prowlarr": { + "memory_current_bytes": 123822080, + "cpu_usage_usec": 7910298 + }, + "qbittorrent": { + "memory_current_bytes": 11321344, + "cpu_usage_usec": 366625 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637113 + } + } + }, + { + "elapsed_seconds": 44.80857953400027, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92254208, + "cpu_usage_usec": 4407058 + }, + "prowlarr": { + "memory_current_bytes": 123822080, + "cpu_usage_usec": 7910298 + }, + "qbittorrent": { + "memory_current_bytes": 11321344, + "cpu_usage_usec": 366625 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637113 + } + } + }, + { + "elapsed_seconds": 44.90955245400073, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92254208, + "cpu_usage_usec": 4407149 + }, + "prowlarr": { + "memory_current_bytes": 123822080, + "cpu_usage_usec": 7910298 + }, + "qbittorrent": { + "memory_current_bytes": 11145216, + "cpu_usage_usec": 366625 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637113 + } + } + }, + { + "elapsed_seconds": 45.01051277700026, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92254208, + "cpu_usage_usec": 4407149 + }, + "prowlarr": { + "memory_current_bytes": 123822080, + "cpu_usage_usec": 7910298 + }, + "qbittorrent": { + "memory_current_bytes": 11145216, + "cpu_usage_usec": 366625 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637113 + } + } + }, + { + "elapsed_seconds": 45.111483147999934, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92254208, + "cpu_usage_usec": 4407149 + }, + "prowlarr": { + "memory_current_bytes": 123822080, + "cpu_usage_usec": 7910298 + }, + "qbittorrent": { + "memory_current_bytes": 11145216, + "cpu_usage_usec": 366655 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637113 + } + } + }, + { + "elapsed_seconds": 45.2119283840002, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92254208, + "cpu_usage_usec": 4407149 + }, + "prowlarr": { + "memory_current_bytes": 124444672, + "cpu_usage_usec": 7963027 + }, + "qbittorrent": { + "memory_current_bytes": 11145216, + "cpu_usage_usec": 366679 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637113 + } + } + }, + { + "elapsed_seconds": 45.31231441700038, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92254208, + "cpu_usage_usec": 4407149 + }, + "prowlarr": { + "memory_current_bytes": 125018112, + "cpu_usage_usec": 8015682 + }, + "qbittorrent": { + "memory_current_bytes": 11145216, + "cpu_usage_usec": 366679 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637113 + } + } + }, + { + "elapsed_seconds": 45.41296703400076, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92254208, + "cpu_usage_usec": 4407149 + }, + "prowlarr": { + "memory_current_bytes": 125116416, + "cpu_usage_usec": 8065109 + }, + "qbittorrent": { + "memory_current_bytes": 11145216, + "cpu_usage_usec": 366679 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637113 + } + } + }, + { + "elapsed_seconds": 45.51359049600069, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92254208, + "cpu_usage_usec": 4407149 + }, + "prowlarr": { + "memory_current_bytes": 125304832, + "cpu_usage_usec": 8116327 + }, + "qbittorrent": { + "memory_current_bytes": 11145216, + "cpu_usage_usec": 366679 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637167 + } + } + }, + { + "elapsed_seconds": 45.61446073500065, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92254208, + "cpu_usage_usec": 4407149 + }, + "prowlarr": { + "memory_current_bytes": 125452288, + "cpu_usage_usec": 8124148 + }, + "qbittorrent": { + "memory_current_bytes": 11243520, + "cpu_usage_usec": 366726 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637167 + } + } + }, + { + "elapsed_seconds": 45.71540908500083, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92254208, + "cpu_usage_usec": 4407149 + }, + "prowlarr": { + "memory_current_bytes": 125452288, + "cpu_usage_usec": 8124148 + }, + "qbittorrent": { + "memory_current_bytes": 11243520, + "cpu_usage_usec": 366726 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637167 + } + } + }, + { + "elapsed_seconds": 45.816366672000186, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92254208, + "cpu_usage_usec": 4407230 + }, + "prowlarr": { + "memory_current_bytes": 125698048, + "cpu_usage_usec": 8124207 + }, + "qbittorrent": { + "memory_current_bytes": 11243520, + "cpu_usage_usec": 366726 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637167 + } + } + }, + { + "elapsed_seconds": 45.91734482600077, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92254208, + "cpu_usage_usec": 4407230 + }, + "prowlarr": { + "memory_current_bytes": 125698048, + "cpu_usage_usec": 8124207 + }, + "qbittorrent": { + "memory_current_bytes": 11243520, + "cpu_usage_usec": 366726 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637167 + } + } + }, + { + "elapsed_seconds": 46.01822736000031, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92254208, + "cpu_usage_usec": 4407230 + }, + "prowlarr": { + "memory_current_bytes": 125698048, + "cpu_usage_usec": 8124207 + }, + "qbittorrent": { + "memory_current_bytes": 11243520, + "cpu_usage_usec": 366726 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637167 + } + } + }, + { + "elapsed_seconds": 46.11873378100063, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92254208, + "cpu_usage_usec": 4407230 + }, + "prowlarr": { + "memory_current_bytes": 125698048, + "cpu_usage_usec": 8124207 + }, + "qbittorrent": { + "memory_current_bytes": 11243520, + "cpu_usage_usec": 366774 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637167 + } + } + }, + { + "elapsed_seconds": 46.219644968000466, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92254208, + "cpu_usage_usec": 4407230 + }, + "prowlarr": { + "memory_current_bytes": 125698048, + "cpu_usage_usec": 8124207 + }, + "qbittorrent": { + "memory_current_bytes": 11010048, + "cpu_usage_usec": 366925 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637167 + } + } + }, + { + "elapsed_seconds": 46.32049681600074, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92512256, + "cpu_usage_usec": 4408090 + }, + "prowlarr": { + "memory_current_bytes": 125960192, + "cpu_usage_usec": 8131222 + }, + "qbittorrent": { + "memory_current_bytes": 11272192, + "cpu_usage_usec": 366925 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637167 + } + } + }, + { + "elapsed_seconds": 46.421376778000194, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92512256, + "cpu_usage_usec": 4408090 + }, + "prowlarr": { + "memory_current_bytes": 125960192, + "cpu_usage_usec": 8131222 + }, + "qbittorrent": { + "memory_current_bytes": 11272192, + "cpu_usage_usec": 366925 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637167 + } + } + }, + { + "elapsed_seconds": 46.52295797000079, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92512256, + "cpu_usage_usec": 4408090 + }, + "prowlarr": { + "memory_current_bytes": 125710336, + "cpu_usage_usec": 8133004 + }, + "qbittorrent": { + "memory_current_bytes": 11272192, + "cpu_usage_usec": 366925 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637241 + } + } + }, + { + "elapsed_seconds": 46.6235125230005, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92512256, + "cpu_usage_usec": 4408090 + }, + "prowlarr": { + "memory_current_bytes": 125755392, + "cpu_usage_usec": 8203784 + }, + "qbittorrent": { + "memory_current_bytes": 11272192, + "cpu_usage_usec": 366957 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637241 + } + } + }, + { + "elapsed_seconds": 46.7241289020003, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92512256, + "cpu_usage_usec": 4408090 + }, + "prowlarr": { + "memory_current_bytes": 128614400, + "cpu_usage_usec": 8255274 + }, + "qbittorrent": { + "memory_current_bytes": 11272192, + "cpu_usage_usec": 366957 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637241 + } + } + }, + { + "elapsed_seconds": 46.82467550199999, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92512256, + "cpu_usage_usec": 4408201 + }, + "prowlarr": { + "memory_current_bytes": 128950272, + "cpu_usage_usec": 8306831 + }, + "qbittorrent": { + "memory_current_bytes": 11649024, + "cpu_usage_usec": 367567 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637241 + } + } + }, + { + "elapsed_seconds": 46.92527518600036, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92512256, + "cpu_usage_usec": 4408201 + }, + "prowlarr": { + "memory_current_bytes": 129286144, + "cpu_usage_usec": 8357200 + }, + "qbittorrent": { + "memory_current_bytes": 11649024, + "cpu_usage_usec": 367567 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637241 + } + } + }, + { + "elapsed_seconds": 47.02568890100065, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92512256, + "cpu_usage_usec": 4408201 + }, + "prowlarr": { + "memory_current_bytes": 129437696, + "cpu_usage_usec": 8404466 + }, + "qbittorrent": { + "memory_current_bytes": 11649024, + "cpu_usage_usec": 367567 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637241 + } + } + }, + { + "elapsed_seconds": 47.12657214699993, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92512256, + "cpu_usage_usec": 4408201 + }, + "prowlarr": { + "memory_current_bytes": 129699840, + "cpu_usage_usec": 8404466 + }, + "qbittorrent": { + "memory_current_bytes": 11702272, + "cpu_usage_usec": 367638 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637241 + } + } + }, + { + "elapsed_seconds": 47.22745798200049, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92512256, + "cpu_usage_usec": 4408201 + }, + "prowlarr": { + "memory_current_bytes": 129486848, + "cpu_usage_usec": 8404466 + }, + "qbittorrent": { + "memory_current_bytes": 11702272, + "cpu_usage_usec": 367658 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637241 + } + } + }, + { + "elapsed_seconds": 47.329019977000826, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 92516352, + "cpu_usage_usec": 4415239 + }, + "prowlarr": { + "memory_current_bytes": 129703936, + "cpu_usage_usec": 8423503 + }, + "qbittorrent": { + "memory_current_bytes": 12337152, + "cpu_usage_usec": 369733 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637241 + } + } + }, + { + "elapsed_seconds": 47.42980662700029, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 92516352, + "cpu_usage_usec": 4415239 + }, + "prowlarr": { + "memory_current_bytes": 129703936, + "cpu_usage_usec": 8423503 + }, + "qbittorrent": { + "memory_current_bytes": 12615680, + "cpu_usage_usec": 371798 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637241 + } + } + }, + { + "elapsed_seconds": 47.53079873200022, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 92516352, + "cpu_usage_usec": 4415239 + }, + "prowlarr": { + "memory_current_bytes": 129699840, + "cpu_usage_usec": 8423583 + }, + "qbittorrent": { + "memory_current_bytes": 12591104, + "cpu_usage_usec": 371798 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637317 + } + } + }, + { + "elapsed_seconds": 47.631200882000485, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 92508160, + "cpu_usage_usec": 4415239 + }, + "prowlarr": { + "memory_current_bytes": 129224704, + "cpu_usage_usec": 8423583 + }, + "qbittorrent": { + "memory_current_bytes": 26578944, + "cpu_usage_usec": 462981 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637317 + } + } + }, + { + "elapsed_seconds": 47.73205830799998, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 92508160, + "cpu_usage_usec": 4415239 + }, + "prowlarr": { + "memory_current_bytes": 129261568, + "cpu_usage_usec": 8423745 + }, + "qbittorrent": { + "memory_current_bytes": 29761536, + "cpu_usage_usec": 498023 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637317 + } + } + }, + { + "elapsed_seconds": 47.83303689400054, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 92508160, + "cpu_usage_usec": 4415327 + }, + "prowlarr": { + "memory_current_bytes": 129007616, + "cpu_usage_usec": 8423797 + }, + "qbittorrent": { + "memory_current_bytes": 29827072, + "cpu_usage_usec": 499410 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637317 + } + } + }, + { + "elapsed_seconds": 47.93399803400007, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 92508160, + "cpu_usage_usec": 4415327 + }, + "prowlarr": { + "memory_current_bytes": 128790528, + "cpu_usage_usec": 8423797 + }, + "qbittorrent": { + "memory_current_bytes": 29827072, + "cpu_usage_usec": 499410 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637317 + } + } + }, + { + "elapsed_seconds": 48.034850430000006, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 92508160, + "cpu_usage_usec": 4415327 + }, + "prowlarr": { + "memory_current_bytes": 128790528, + "cpu_usage_usec": 8423797 + }, + "qbittorrent": { + "memory_current_bytes": 29388800, + "cpu_usage_usec": 500807 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637317 + } + } + }, + { + "elapsed_seconds": 48.135706744000345, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 92508160, + "cpu_usage_usec": 4415327 + }, + "prowlarr": { + "memory_current_bytes": 128790528, + "cpu_usage_usec": 8423797 + }, + "qbittorrent": { + "memory_current_bytes": 29298688, + "cpu_usage_usec": 500915 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637317 + } + } + }, + { + "elapsed_seconds": 48.23660653100069, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 92254208, + "cpu_usage_usec": 4415327 + }, + "prowlarr": { + "memory_current_bytes": 128790528, + "cpu_usage_usec": 8423797 + }, + "qbittorrent": { + "memory_current_bytes": 29700096, + "cpu_usage_usec": 502270 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637317 + } + } + }, + { + "elapsed_seconds": 48.33740880200003, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 92254208, + "cpu_usage_usec": 4415404 + }, + "prowlarr": { + "memory_current_bytes": 129048576, + "cpu_usage_usec": 8437901 + }, + "qbittorrent": { + "memory_current_bytes": 29700096, + "cpu_usage_usec": 502270 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637317 + } + } + }, + { + "elapsed_seconds": 48.43830405300014, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 92254208, + "cpu_usage_usec": 4415404 + }, + "prowlarr": { + "memory_current_bytes": 130285568, + "cpu_usage_usec": 8463237 + }, + "qbittorrent": { + "memory_current_bytes": 29413376, + "cpu_usage_usec": 503220 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637317 + } + } + }, + { + "elapsed_seconds": 48.53919155099993, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 92254208, + "cpu_usage_usec": 4415404 + }, + "prowlarr": { + "memory_current_bytes": 130908160, + "cpu_usage_usec": 8478476 + }, + "qbittorrent": { + "memory_current_bytes": 29179904, + "cpu_usage_usec": 503809 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637394 + } + } + }, + { + "elapsed_seconds": 48.64003784400029, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 92254208, + "cpu_usage_usec": 4415404 + }, + "prowlarr": { + "memory_current_bytes": 130895872, + "cpu_usage_usec": 8481342 + }, + "qbittorrent": { + "memory_current_bytes": 29257728, + "cpu_usage_usec": 505436 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637394 + } + } + }, + { + "elapsed_seconds": 48.74047323100058, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 92254208, + "cpu_usage_usec": 4415404 + }, + "prowlarr": { + "memory_current_bytes": 131911680, + "cpu_usage_usec": 8491996 + }, + "qbittorrent": { + "memory_current_bytes": 29257728, + "cpu_usage_usec": 505767 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637394 + } + } + }, + { + "elapsed_seconds": 48.84129750400007, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 92254208, + "cpu_usage_usec": 4415482 + }, + "prowlarr": { + "memory_current_bytes": 132214784, + "cpu_usage_usec": 8503105 + }, + "qbittorrent": { + "memory_current_bytes": 29708288, + "cpu_usage_usec": 507362 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637394 + } + } + }, + { + "elapsed_seconds": 48.94224372000008, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 92254208, + "cpu_usage_usec": 4415482 + }, + "prowlarr": { + "memory_current_bytes": 132214784, + "cpu_usage_usec": 8504652 + }, + "qbittorrent": { + "memory_current_bytes": 29741056, + "cpu_usage_usec": 508640 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637394 + } + } + }, + { + "elapsed_seconds": 49.0431337630007, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 92254208, + "cpu_usage_usec": 4415482 + }, + "prowlarr": { + "memory_current_bytes": 132214784, + "cpu_usage_usec": 8507599 + }, + "qbittorrent": { + "memory_current_bytes": 29544448, + "cpu_usage_usec": 510801 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637394 + } + } + }, + { + "elapsed_seconds": 49.1440771890002, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 92254208, + "cpu_usage_usec": 4415482 + }, + "prowlarr": { + "memory_current_bytes": 132472832, + "cpu_usage_usec": 8510017 + }, + "qbittorrent": { + "memory_current_bytes": 29396992, + "cpu_usage_usec": 511181 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637394 + } + } + }, + { + "elapsed_seconds": 49.24492585700045, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 92254208, + "cpu_usage_usec": 4415482 + }, + "prowlarr": { + "memory_current_bytes": 132464640, + "cpu_usage_usec": 8511039 + }, + "qbittorrent": { + "memory_current_bytes": 29720576, + "cpu_usage_usec": 512673 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637394 + } + } + }, + { + "elapsed_seconds": 49.345361453000805, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 92516352, + "cpu_usage_usec": 4452711 + }, + "prowlarr": { + "memory_current_bytes": 134971392, + "cpu_usage_usec": 8613151 + }, + "qbittorrent": { + "memory_current_bytes": 29573120, + "cpu_usage_usec": 513777 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637394 + } + } + }, + { + "elapsed_seconds": 49.44578186700073, + "phase": "idle", + "services": { + "jackett": { + "memory_current_bytes": 92680192, + "cpu_usage_usec": 4503250 + }, + "prowlarr": { + "memory_current_bytes": 136781824, + "cpu_usage_usec": 8652131 + }, + "qbittorrent": { + "memory_current_bytes": 12906496, + "cpu_usage_usec": 516341 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637394 + } + } + }, + { + "elapsed_seconds": 49.54637791599998, + "phase": "idle", + "services": { + "jackett": { + "memory_current_bytes": 92680192, + "cpu_usage_usec": 4508427 + }, + "prowlarr": { + "memory_current_bytes": 137043968, + "cpu_usage_usec": 8652253 + }, + "qbittorrent": { + "memory_current_bytes": 12902400, + "cpu_usage_usec": 516985 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637449 + } + } + }, + { + "elapsed_seconds": 49.64681378900059, + "phase": "idle", + "services": { + "jackett": { + "memory_current_bytes": 92655616, + "cpu_usage_usec": 4508427 + }, + "prowlarr": { + "memory_current_bytes": 136323072, + "cpu_usage_usec": 8652253 + }, + "qbittorrent": { + "memory_current_bytes": 12242944, + "cpu_usage_usec": 517507 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637449 + } + } + }, + { + "elapsed_seconds": 49.74769694299994, + "phase": "idle", + "services": { + "jackett": { + "memory_current_bytes": 92655616, + "cpu_usage_usec": 4508427 + }, + "prowlarr": { + "memory_current_bytes": 136581120, + "cpu_usage_usec": 8654803 + }, + "qbittorrent": { + "memory_current_bytes": 12242944, + "cpu_usage_usec": 517507 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637449 + } + } + }, + { + "elapsed_seconds": 49.84863754200069, + "phase": "idle", + "services": { + "jackett": { + "memory_current_bytes": 92655616, + "cpu_usage_usec": 4508496 + }, + "prowlarr": { + "memory_current_bytes": 136327168, + "cpu_usage_usec": 8654835 + }, + "qbittorrent": { + "memory_current_bytes": 12242944, + "cpu_usage_usec": 517647 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637449 + } + } + }, + { + "elapsed_seconds": 49.94954403200063, + "phase": "idle", + "services": { + "jackett": { + "memory_current_bytes": 92655616, + "cpu_usage_usec": 4508496 + }, + "prowlarr": { + "memory_current_bytes": 136327168, + "cpu_usage_usec": 8655128 + }, + "qbittorrent": { + "memory_current_bytes": 12193792, + "cpu_usage_usec": 517818 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637449 + } + } + }, + { + "elapsed_seconds": 50.050597112000105, + "phase": "idle", + "services": { + "jackett": { + "memory_current_bytes": 92655616, + "cpu_usage_usec": 4508496 + }, + "prowlarr": { + "memory_current_bytes": 136327168, + "cpu_usage_usec": 8655472 + }, + "qbittorrent": { + "memory_current_bytes": 12193792, + "cpu_usage_usec": 517957 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637449 + } + } + }, + { + "elapsed_seconds": 50.151463186, + "phase": "idle", + "services": { + "jackett": { + "memory_current_bytes": 92655616, + "cpu_usage_usec": 4508496 + }, + "prowlarr": { + "memory_current_bytes": 136318976, + "cpu_usage_usec": 8655472 + }, + "qbittorrent": { + "memory_current_bytes": 12193792, + "cpu_usage_usec": 518225 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637449 + } + } + }, + { + "elapsed_seconds": 50.25236928600043, + "phase": "idle", + "services": { + "jackett": { + "memory_current_bytes": 92655616, + "cpu_usage_usec": 4508535 + }, + "prowlarr": { + "memory_current_bytes": 136318976, + "cpu_usage_usec": 8655472 + }, + "qbittorrent": { + "memory_current_bytes": 12193792, + "cpu_usage_usec": 518574 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637449 + } + } + }, + { + "elapsed_seconds": 50.353402159000325, + "phase": "idle", + "services": { + "jackett": { + "memory_current_bytes": 92655616, + "cpu_usage_usec": 4508535 + }, + "prowlarr": { + "memory_current_bytes": 136318976, + "cpu_usage_usec": 8656194 + }, + "qbittorrent": { + "memory_current_bytes": 12193792, + "cpu_usage_usec": 518747 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637449 + } + } + }, + { + "elapsed_seconds": 50.45439069300028, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92655616, + "cpu_usage_usec": 4508535 + }, + "prowlarr": { + "memory_current_bytes": 137105408, + "cpu_usage_usec": 8659485 + }, + "qbittorrent": { + "memory_current_bytes": 12242944, + "cpu_usage_usec": 519103 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637449 + } + } + }, + { + "elapsed_seconds": 50.55511130100058, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92655616, + "cpu_usage_usec": 4508535 + }, + "prowlarr": { + "memory_current_bytes": 137105408, + "cpu_usage_usec": 8659576 + }, + "qbittorrent": { + "memory_current_bytes": 12242944, + "cpu_usage_usec": 519162 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637521 + } + } + }, + { + "elapsed_seconds": 50.655795234000834, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92610560, + "cpu_usage_usec": 4508535 + }, + "prowlarr": { + "memory_current_bytes": 137105408, + "cpu_usage_usec": 8659576 + }, + "qbittorrent": { + "memory_current_bytes": 12242944, + "cpu_usage_usec": 519162 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637521 + } + } + }, + { + "elapsed_seconds": 50.75679486200079, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92610560, + "cpu_usage_usec": 4508535 + }, + "prowlarr": { + "memory_current_bytes": 137035776, + "cpu_usage_usec": 8659576 + }, + "qbittorrent": { + "memory_current_bytes": 12242944, + "cpu_usage_usec": 519305 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637521 + } + } + }, + { + "elapsed_seconds": 50.8577339200001, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92610560, + "cpu_usage_usec": 4511806 + }, + "prowlarr": { + "memory_current_bytes": 137035776, + "cpu_usage_usec": 8659631 + }, + "qbittorrent": { + "memory_current_bytes": 12242944, + "cpu_usage_usec": 519305 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637521 + } + } + }, + { + "elapsed_seconds": 50.95874104900031, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92610560, + "cpu_usage_usec": 4511806 + }, + "prowlarr": { + "memory_current_bytes": 137035776, + "cpu_usage_usec": 8659631 + }, + "qbittorrent": { + "memory_current_bytes": 12242944, + "cpu_usage_usec": 519305 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637521 + } + } + }, + { + "elapsed_seconds": 51.05965429400021, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92610560, + "cpu_usage_usec": 4511806 + }, + "prowlarr": { + "memory_current_bytes": 137035776, + "cpu_usage_usec": 8659631 + }, + "qbittorrent": { + "memory_current_bytes": 12242944, + "cpu_usage_usec": 519338 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637521 + } + } + }, + { + "elapsed_seconds": 51.1606782960007, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92610560, + "cpu_usage_usec": 4511806 + }, + "prowlarr": { + "memory_current_bytes": 137035776, + "cpu_usage_usec": 8659631 + }, + "qbittorrent": { + "memory_current_bytes": 12242944, + "cpu_usage_usec": 519338 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637521 + } + } + }, + { + "elapsed_seconds": 51.26164067400077, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92610560, + "cpu_usage_usec": 4511806 + }, + "prowlarr": { + "memory_current_bytes": 137035776, + "cpu_usage_usec": 8659631 + }, + "qbittorrent": { + "memory_current_bytes": 12242944, + "cpu_usage_usec": 519379 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637521 + } + } + }, + { + "elapsed_seconds": 51.362492186000054, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92610560, + "cpu_usage_usec": 4511806 + }, + "prowlarr": { + "memory_current_bytes": 137281536, + "cpu_usage_usec": 8663445 + }, + "qbittorrent": { + "memory_current_bytes": 12242944, + "cpu_usage_usec": 519421 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637521 + } + } + }, + { + "elapsed_seconds": 51.46337475400014, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92610560, + "cpu_usage_usec": 4511806 + }, + "prowlarr": { + "memory_current_bytes": 137019392, + "cpu_usage_usec": 8663493 + }, + "qbittorrent": { + "memory_current_bytes": 12242944, + "cpu_usage_usec": 519644 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637521 + } + } + }, + { + "elapsed_seconds": 51.56427250300021, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93388800, + "cpu_usage_usec": 4517506 + }, + "prowlarr": { + "memory_current_bytes": 136826880, + "cpu_usage_usec": 8663584 + }, + "qbittorrent": { + "memory_current_bytes": 12316672, + "cpu_usage_usec": 519709 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637596 + } + } + }, + { + "elapsed_seconds": 51.665173564000725, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93388800, + "cpu_usage_usec": 4517506 + }, + "prowlarr": { + "memory_current_bytes": 136826880, + "cpu_usage_usec": 8663584 + }, + "qbittorrent": { + "memory_current_bytes": 12316672, + "cpu_usage_usec": 519709 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637596 + } + } + }, + { + "elapsed_seconds": 51.766518316000656, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93388800, + "cpu_usage_usec": 4517506 + }, + "prowlarr": { + "memory_current_bytes": 136560640, + "cpu_usage_usec": 8663584 + }, + "qbittorrent": { + "memory_current_bytes": 12316672, + "cpu_usage_usec": 519709 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637596 + } + } + }, + { + "elapsed_seconds": 51.86744598700079, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93388800, + "cpu_usage_usec": 4517601 + }, + "prowlarr": { + "memory_current_bytes": 136351744, + "cpu_usage_usec": 8664310 + }, + "qbittorrent": { + "memory_current_bytes": 12316672, + "cpu_usage_usec": 519709 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637596 + } + } + }, + { + "elapsed_seconds": 51.96843630800049, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93384704, + "cpu_usage_usec": 4517601 + }, + "prowlarr": { + "memory_current_bytes": 136351744, + "cpu_usage_usec": 8664310 + }, + "qbittorrent": { + "memory_current_bytes": 12283904, + "cpu_usage_usec": 519709 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637596 + } + } + }, + { + "elapsed_seconds": 52.069332148000285, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93384704, + "cpu_usage_usec": 4517661 + }, + "prowlarr": { + "memory_current_bytes": 136351744, + "cpu_usage_usec": 8664310 + }, + "qbittorrent": { + "memory_current_bytes": 12042240, + "cpu_usage_usec": 519767 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637596 + } + } + }, + { + "elapsed_seconds": 52.17054841500067, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93384704, + "cpu_usage_usec": 4517661 + }, + "prowlarr": { + "memory_current_bytes": 136351744, + "cpu_usage_usec": 8664310 + }, + "qbittorrent": { + "memory_current_bytes": 12042240, + "cpu_usage_usec": 519767 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637596 + } + } + }, + { + "elapsed_seconds": 52.270969164000235, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93380608, + "cpu_usage_usec": 4517661 + }, + "prowlarr": { + "memory_current_bytes": 136347648, + "cpu_usage_usec": 8664310 + }, + "qbittorrent": { + "memory_current_bytes": 12042240, + "cpu_usage_usec": 519905 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637596 + } + } + }, + { + "elapsed_seconds": 52.37184129400066, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93380608, + "cpu_usage_usec": 4517661 + }, + "prowlarr": { + "memory_current_bytes": 136347648, + "cpu_usage_usec": 8664676 + }, + "qbittorrent": { + "memory_current_bytes": 12042240, + "cpu_usage_usec": 519905 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637596 + } + } + }, + { + "elapsed_seconds": 52.47233417700045, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93380608, + "cpu_usage_usec": 4517688 + }, + "prowlarr": { + "memory_current_bytes": 136769536, + "cpu_usage_usec": 8715910 + }, + "qbittorrent": { + "memory_current_bytes": 12042240, + "cpu_usage_usec": 520099 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637596 + } + } + }, + { + "elapsed_seconds": 52.57331243099998, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93380608, + "cpu_usage_usec": 4517688 + }, + "prowlarr": { + "memory_current_bytes": 136761344, + "cpu_usage_usec": 8737769 + }, + "qbittorrent": { + "memory_current_bytes": 12042240, + "cpu_usage_usec": 520131 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637636 + } + } + }, + { + "elapsed_seconds": 52.67461109500073, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93380608, + "cpu_usage_usec": 4517688 + }, + "prowlarr": { + "memory_current_bytes": 136761344, + "cpu_usage_usec": 8737769 + }, + "qbittorrent": { + "memory_current_bytes": 12288000, + "cpu_usage_usec": 521081 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637636 + } + } + }, + { + "elapsed_seconds": 52.77565532100016, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93380608, + "cpu_usage_usec": 4517688 + }, + "prowlarr": { + "memory_current_bytes": 136761344, + "cpu_usage_usec": 8737769 + }, + "qbittorrent": { + "memory_current_bytes": 12288000, + "cpu_usage_usec": 521081 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637636 + } + } + }, + { + "elapsed_seconds": 52.876542598000015, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93380608, + "cpu_usage_usec": 4517767 + }, + "prowlarr": { + "memory_current_bytes": 136761344, + "cpu_usage_usec": 8737820 + }, + "qbittorrent": { + "memory_current_bytes": 12288000, + "cpu_usage_usec": 521081 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637636 + } + } + }, + { + "elapsed_seconds": 52.977449085000444, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93380608, + "cpu_usage_usec": 4517767 + }, + "prowlarr": { + "memory_current_bytes": 136581120, + "cpu_usage_usec": 8737892 + }, + "qbittorrent": { + "memory_current_bytes": 12288000, + "cpu_usage_usec": 521081 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637636 + } + } + }, + { + "elapsed_seconds": 53.07849958400038, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93380608, + "cpu_usage_usec": 4517767 + }, + "prowlarr": { + "memory_current_bytes": 136581120, + "cpu_usage_usec": 8737892 + }, + "qbittorrent": { + "memory_current_bytes": 12288000, + "cpu_usage_usec": 521114 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637636 + } + } + }, + { + "elapsed_seconds": 53.17959720500039, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93380608, + "cpu_usage_usec": 4517767 + }, + "prowlarr": { + "memory_current_bytes": 136544256, + "cpu_usage_usec": 8737892 + }, + "qbittorrent": { + "memory_current_bytes": 12288000, + "cpu_usage_usec": 521114 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637636 + } + } + }, + { + "elapsed_seconds": 53.28049691100023, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93380608, + "cpu_usage_usec": 4517767 + }, + "prowlarr": { + "memory_current_bytes": 136544256, + "cpu_usage_usec": 8737892 + }, + "qbittorrent": { + "memory_current_bytes": 12288000, + "cpu_usage_usec": 521145 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637636 + } + } + }, + { + "elapsed_seconds": 53.38139906700053, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93380608, + "cpu_usage_usec": 4517767 + }, + "prowlarr": { + "memory_current_bytes": 136540160, + "cpu_usage_usec": 8738365 + }, + "qbittorrent": { + "memory_current_bytes": 12288000, + "cpu_usage_usec": 521145 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637636 + } + } + }, + { + "elapsed_seconds": 53.48230301500007, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93380608, + "cpu_usage_usec": 4517767 + }, + "prowlarr": { + "memory_current_bytes": 136540160, + "cpu_usage_usec": 8738365 + }, + "qbittorrent": { + "memory_current_bytes": 12038144, + "cpu_usage_usec": 521298 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637723 + } + } + }, + { + "elapsed_seconds": 53.583295216000806, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93122560, + "cpu_usage_usec": 4517767 + }, + "prowlarr": { + "memory_current_bytes": 136388608, + "cpu_usage_usec": 8739229 + }, + "qbittorrent": { + "memory_current_bytes": 12038144, + "cpu_usage_usec": 521344 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637723 + } + } + }, + { + "elapsed_seconds": 53.683722137000586, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92872704, + "cpu_usage_usec": 4517767 + }, + "prowlarr": { + "memory_current_bytes": 136388608, + "cpu_usage_usec": 8739229 + }, + "qbittorrent": { + "memory_current_bytes": 12038144, + "cpu_usage_usec": 521428 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637723 + } + } + }, + { + "elapsed_seconds": 53.78419412600033, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92872704, + "cpu_usage_usec": 4517767 + }, + "prowlarr": { + "memory_current_bytes": 136388608, + "cpu_usage_usec": 8739229 + }, + "qbittorrent": { + "memory_current_bytes": 12038144, + "cpu_usage_usec": 521428 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637723 + } + } + }, + { + "elapsed_seconds": 53.88465373700001, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93134848, + "cpu_usage_usec": 4518012 + }, + "prowlarr": { + "memory_current_bytes": 136388608, + "cpu_usage_usec": 8739266 + }, + "qbittorrent": { + "memory_current_bytes": 12038144, + "cpu_usage_usec": 521428 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637723 + } + } + }, + { + "elapsed_seconds": 53.98514964900005, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93134848, + "cpu_usage_usec": 4518012 + }, + "prowlarr": { + "memory_current_bytes": 136388608, + "cpu_usage_usec": 8739266 + }, + "qbittorrent": { + "memory_current_bytes": 12038144, + "cpu_usage_usec": 521428 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637723 + } + } + }, + { + "elapsed_seconds": 54.0859912320002, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93134848, + "cpu_usage_usec": 4518012 + }, + "prowlarr": { + "memory_current_bytes": 136388608, + "cpu_usage_usec": 8739266 + }, + "qbittorrent": { + "memory_current_bytes": 12038144, + "cpu_usage_usec": 521453 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637723 + } + } + }, + { + "elapsed_seconds": 54.18684321500041, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93134848, + "cpu_usage_usec": 4518012 + }, + "prowlarr": { + "memory_current_bytes": 136388608, + "cpu_usage_usec": 8739266 + }, + "qbittorrent": { + "memory_current_bytes": 12038144, + "cpu_usage_usec": 521453 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637723 + } + } + }, + { + "elapsed_seconds": 54.28738717500073, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92651520, + "cpu_usage_usec": 4518012 + }, + "prowlarr": { + "memory_current_bytes": 136388608, + "cpu_usage_usec": 8739266 + }, + "qbittorrent": { + "memory_current_bytes": 12038144, + "cpu_usage_usec": 521453 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637723 + } + } + }, + { + "elapsed_seconds": 54.387764138999955, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92651520, + "cpu_usage_usec": 4518012 + }, + "prowlarr": { + "memory_current_bytes": 136388608, + "cpu_usage_usec": 8739463 + }, + "qbittorrent": { + "memory_current_bytes": 12038144, + "cpu_usage_usec": 521453 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637723 + } + } + }, + { + "elapsed_seconds": 54.48868355600007, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92651520, + "cpu_usage_usec": 4518012 + }, + "prowlarr": { + "memory_current_bytes": 136650752, + "cpu_usage_usec": 8739487 + }, + "qbittorrent": { + "memory_current_bytes": 12038144, + "cpu_usage_usec": 521472 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637786 + } + } + }, + { + "elapsed_seconds": 54.589581309000096, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92651520, + "cpu_usage_usec": 4518012 + }, + "prowlarr": { + "memory_current_bytes": 136650752, + "cpu_usage_usec": 8739575 + }, + "qbittorrent": { + "memory_current_bytes": 12812288, + "cpu_usage_usec": 522541 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637786 + } + } + }, + { + "elapsed_seconds": 54.690000908, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92651520, + "cpu_usage_usec": 4518012 + }, + "prowlarr": { + "memory_current_bytes": 136392704, + "cpu_usage_usec": 8739575 + }, + "qbittorrent": { + "memory_current_bytes": 12812288, + "cpu_usage_usec": 522685 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637786 + } + } + }, + { + "elapsed_seconds": 54.790958585000226, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92651520, + "cpu_usage_usec": 4518012 + }, + "prowlarr": { + "memory_current_bytes": 136392704, + "cpu_usage_usec": 8739575 + }, + "qbittorrent": { + "memory_current_bytes": 12812288, + "cpu_usage_usec": 523220 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637786 + } + } + }, + { + "elapsed_seconds": 54.89177432300039, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92651520, + "cpu_usage_usec": 4518089 + }, + "prowlarr": { + "memory_current_bytes": 136392704, + "cpu_usage_usec": 8739631 + }, + "qbittorrent": { + "memory_current_bytes": 12554240, + "cpu_usage_usec": 523805 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637786 + } + } + }, + { + "elapsed_seconds": 54.992402769000364, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92651520, + "cpu_usage_usec": 4518089 + }, + "prowlarr": { + "memory_current_bytes": 136392704, + "cpu_usage_usec": 8739631 + }, + "qbittorrent": { + "memory_current_bytes": 12320768, + "cpu_usage_usec": 524571 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637786 + } + } + }, + { + "elapsed_seconds": 55.09352810400014, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92651520, + "cpu_usage_usec": 4518089 + }, + "prowlarr": { + "memory_current_bytes": 136892416, + "cpu_usage_usec": 8742769 + }, + "qbittorrent": { + "memory_current_bytes": 12320768, + "cpu_usage_usec": 524929 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637786 + } + } + }, + { + "elapsed_seconds": 55.19443868899998, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94220288, + "cpu_usage_usec": 4526738 + }, + "prowlarr": { + "memory_current_bytes": 137576448, + "cpu_usage_usec": 8815296 + }, + "qbittorrent": { + "memory_current_bytes": 12554240, + "cpu_usage_usec": 525253 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637786 + } + } + }, + { + "elapsed_seconds": 55.29485927400037, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93753344, + "cpu_usage_usec": 4526738 + }, + "prowlarr": { + "memory_current_bytes": 137101312, + "cpu_usage_usec": 8850194 + }, + "qbittorrent": { + "memory_current_bytes": 12562432, + "cpu_usage_usec": 525429 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637786 + } + } + }, + { + "elapsed_seconds": 55.39589401400008, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93237248, + "cpu_usage_usec": 4526738 + }, + "prowlarr": { + "memory_current_bytes": 137101312, + "cpu_usage_usec": 8851952 + }, + "qbittorrent": { + "memory_current_bytes": 12824576, + "cpu_usage_usec": 525865 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637786 + } + } + }, + { + "elapsed_seconds": 55.496734334000394, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93237248, + "cpu_usage_usec": 4526738 + }, + "prowlarr": { + "memory_current_bytes": 137101312, + "cpu_usage_usec": 8851952 + }, + "qbittorrent": { + "memory_current_bytes": 12824576, + "cpu_usage_usec": 525865 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637881 + } + } + }, + { + "elapsed_seconds": 55.597922407000624, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93237248, + "cpu_usage_usec": 4526738 + }, + "prowlarr": { + "memory_current_bytes": 137101312, + "cpu_usage_usec": 8852050 + }, + "qbittorrent": { + "memory_current_bytes": 12558336, + "cpu_usage_usec": 526367 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637881 + } + } + }, + { + "elapsed_seconds": 55.698701473000256, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92725248, + "cpu_usage_usec": 4526799 + }, + "prowlarr": { + "memory_current_bytes": 137363456, + "cpu_usage_usec": 8855606 + }, + "qbittorrent": { + "memory_current_bytes": 12558336, + "cpu_usage_usec": 526367 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637881 + } + } + }, + { + "elapsed_seconds": 55.7995757890003, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92725248, + "cpu_usage_usec": 4526799 + }, + "prowlarr": { + "memory_current_bytes": 137363456, + "cpu_usage_usec": 8855606 + }, + "qbittorrent": { + "memory_current_bytes": 12558336, + "cpu_usage_usec": 526367 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637881 + } + } + }, + { + "elapsed_seconds": 55.90041052600009, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92725248, + "cpu_usage_usec": 4526870 + }, + "prowlarr": { + "memory_current_bytes": 137363456, + "cpu_usage_usec": 8855663 + }, + "qbittorrent": { + "memory_current_bytes": 12541952, + "cpu_usage_usec": 526367 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637881 + } + } + }, + { + "elapsed_seconds": 56.001309818000664, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92725248, + "cpu_usage_usec": 4526870 + }, + "prowlarr": { + "memory_current_bytes": 137314304, + "cpu_usage_usec": 8863368 + }, + "qbittorrent": { + "memory_current_bytes": 12541952, + "cpu_usage_usec": 526367 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637881 + } + } + }, + { + "elapsed_seconds": 56.1021494280003, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92725248, + "cpu_usage_usec": 4526870 + }, + "prowlarr": { + "memory_current_bytes": 137314304, + "cpu_usage_usec": 8863368 + }, + "qbittorrent": { + "memory_current_bytes": 12541952, + "cpu_usage_usec": 526410 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637881 + } + } + }, + { + "elapsed_seconds": 56.20257654700072, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93163520, + "cpu_usage_usec": 4602117 + }, + "prowlarr": { + "memory_current_bytes": 137314304, + "cpu_usage_usec": 8863695 + }, + "qbittorrent": { + "memory_current_bytes": 12390400, + "cpu_usage_usec": 526410 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637881 + } + } + }, + { + "elapsed_seconds": 56.30353072100024, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93163520, + "cpu_usage_usec": 4602117 + }, + "prowlarr": { + "memory_current_bytes": 137314304, + "cpu_usage_usec": 8863695 + }, + "qbittorrent": { + "memory_current_bytes": 12652544, + "cpu_usage_usec": 526410 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637881 + } + } + }, + { + "elapsed_seconds": 56.40438899400033, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93163520, + "cpu_usage_usec": 4602117 + }, + "prowlarr": { + "memory_current_bytes": 137314304, + "cpu_usage_usec": 8864028 + }, + "qbittorrent": { + "memory_current_bytes": 12652544, + "cpu_usage_usec": 526656 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637881 + } + } + }, + { + "elapsed_seconds": 56.50552541700017, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93163520, + "cpu_usage_usec": 4602117 + }, + "prowlarr": { + "memory_current_bytes": 137314304, + "cpu_usage_usec": 8864287 + }, + "qbittorrent": { + "memory_current_bytes": 12648448, + "cpu_usage_usec": 527462 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637956 + } + } + }, + { + "elapsed_seconds": 56.60668108600021, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93163520, + "cpu_usage_usec": 4602117 + }, + "prowlarr": { + "memory_current_bytes": 137310208, + "cpu_usage_usec": 8872655 + }, + "qbittorrent": { + "memory_current_bytes": 12648448, + "cpu_usage_usec": 527617 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637956 + } + } + }, + { + "elapsed_seconds": 56.70763353300026, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93163520, + "cpu_usage_usec": 4602117 + }, + "prowlarr": { + "memory_current_bytes": 137297920, + "cpu_usage_usec": 8872655 + }, + "qbittorrent": { + "memory_current_bytes": 12648448, + "cpu_usage_usec": 528299 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637956 + } + } + }, + { + "elapsed_seconds": 56.80849088100058, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93163520, + "cpu_usage_usec": 4602117 + }, + "prowlarr": { + "memory_current_bytes": 138055680, + "cpu_usage_usec": 8899249 + }, + "qbittorrent": { + "memory_current_bytes": 12886016, + "cpu_usage_usec": 528845 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637956 + } + } + }, + { + "elapsed_seconds": 56.90950108200013, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93163520, + "cpu_usage_usec": 4602857 + }, + "prowlarr": { + "memory_current_bytes": 138047488, + "cpu_usage_usec": 8899307 + }, + "qbittorrent": { + "memory_current_bytes": 12627968, + "cpu_usage_usec": 529012 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637956 + } + } + }, + { + "elapsed_seconds": 57.010562818000835, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93163520, + "cpu_usage_usec": 4602857 + }, + "prowlarr": { + "memory_current_bytes": 138047488, + "cpu_usage_usec": 8899307 + }, + "qbittorrent": { + "memory_current_bytes": 12787712, + "cpu_usage_usec": 529924 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637956 + } + } + }, + { + "elapsed_seconds": 57.11144167800012, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93163520, + "cpu_usage_usec": 4602857 + }, + "prowlarr": { + "memory_current_bytes": 138047488, + "cpu_usage_usec": 8899307 + }, + "qbittorrent": { + "memory_current_bytes": 12787712, + "cpu_usage_usec": 530070 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637956 + } + } + }, + { + "elapsed_seconds": 57.21190188300079, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92913664, + "cpu_usage_usec": 4602857 + }, + "prowlarr": { + "memory_current_bytes": 137523200, + "cpu_usage_usec": 8899307 + }, + "qbittorrent": { + "memory_current_bytes": 12349440, + "cpu_usage_usec": 530120 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637956 + } + } + }, + { + "elapsed_seconds": 57.312292309999975, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92913664, + "cpu_usage_usec": 4602857 + }, + "prowlarr": { + "memory_current_bytes": 137277440, + "cpu_usage_usec": 8899443 + }, + "qbittorrent": { + "memory_current_bytes": 12210176, + "cpu_usage_usec": 530120 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637956 + } + } + }, + { + "elapsed_seconds": 57.413257158000306, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92913664, + "cpu_usage_usec": 4602857 + }, + "prowlarr": { + "memory_current_bytes": 137277440, + "cpu_usage_usec": 8899460 + }, + "qbittorrent": { + "memory_current_bytes": 12472320, + "cpu_usage_usec": 530185 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1637956 + } + } + }, + { + "elapsed_seconds": 57.514163638000355, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92913664, + "cpu_usage_usec": 4602857 + }, + "prowlarr": { + "memory_current_bytes": 137277440, + "cpu_usage_usec": 8899460 + }, + "qbittorrent": { + "memory_current_bytes": 12472320, + "cpu_usage_usec": 530185 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638032 + } + } + }, + { + "elapsed_seconds": 57.615272505000576, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92913664, + "cpu_usage_usec": 4602857 + }, + "prowlarr": { + "memory_current_bytes": 137277440, + "cpu_usage_usec": 8900167 + }, + "qbittorrent": { + "memory_current_bytes": 12472320, + "cpu_usage_usec": 530227 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638032 + } + } + }, + { + "elapsed_seconds": 57.71640479400048, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92913664, + "cpu_usage_usec": 4602857 + }, + "prowlarr": { + "memory_current_bytes": 138063872, + "cpu_usage_usec": 8916853 + }, + "qbittorrent": { + "memory_current_bytes": 12472320, + "cpu_usage_usec": 530227 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638032 + } + } + }, + { + "elapsed_seconds": 57.817268926, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92913664, + "cpu_usage_usec": 4602936 + }, + "prowlarr": { + "memory_current_bytes": 138063872, + "cpu_usage_usec": 8916909 + }, + "qbittorrent": { + "memory_current_bytes": 12472320, + "cpu_usage_usec": 530227 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638032 + } + } + }, + { + "elapsed_seconds": 57.91818209900066, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92913664, + "cpu_usage_usec": 4602936 + }, + "prowlarr": { + "memory_current_bytes": 138047488, + "cpu_usage_usec": 8916909 + }, + "qbittorrent": { + "memory_current_bytes": 12472320, + "cpu_usage_usec": 530638 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638032 + } + } + }, + { + "elapsed_seconds": 58.01906386700011, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92913664, + "cpu_usage_usec": 4602936 + }, + "prowlarr": { + "memory_current_bytes": 138047488, + "cpu_usage_usec": 8916909 + }, + "qbittorrent": { + "memory_current_bytes": 12472320, + "cpu_usage_usec": 530638 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638032 + } + } + }, + { + "elapsed_seconds": 58.11987471200064, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92913664, + "cpu_usage_usec": 4602936 + }, + "prowlarr": { + "memory_current_bytes": 137805824, + "cpu_usage_usec": 8916909 + }, + "qbittorrent": { + "memory_current_bytes": 12472320, + "cpu_usage_usec": 530679 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638032 + } + } + }, + { + "elapsed_seconds": 58.2207660590002, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92913664, + "cpu_usage_usec": 4602936 + }, + "prowlarr": { + "memory_current_bytes": 137805824, + "cpu_usage_usec": 8916909 + }, + "qbittorrent": { + "memory_current_bytes": 12472320, + "cpu_usage_usec": 531104 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638032 + } + } + }, + { + "elapsed_seconds": 58.321157066000524, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92913664, + "cpu_usage_usec": 4602936 + }, + "prowlarr": { + "memory_current_bytes": 137805824, + "cpu_usage_usec": 8917096 + }, + "qbittorrent": { + "memory_current_bytes": 12718080, + "cpu_usage_usec": 531439 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638032 + } + } + }, + { + "elapsed_seconds": 58.42158912800005, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92913664, + "cpu_usage_usec": 4602936 + }, + "prowlarr": { + "memory_current_bytes": 137314304, + "cpu_usage_usec": 8917388 + }, + "qbittorrent": { + "memory_current_bytes": 12566528, + "cpu_usage_usec": 531614 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638032 + } + } + }, + { + "elapsed_seconds": 58.52224485900024, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92913664, + "cpu_usage_usec": 4602936 + }, + "prowlarr": { + "memory_current_bytes": 137310208, + "cpu_usage_usec": 8917388 + }, + "qbittorrent": { + "memory_current_bytes": 12320768, + "cpu_usage_usec": 531839 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638082 + } + } + }, + { + "elapsed_seconds": 58.62279254900022, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92913664, + "cpu_usage_usec": 4602936 + }, + "prowlarr": { + "memory_current_bytes": 137310208, + "cpu_usage_usec": 8917457 + }, + "qbittorrent": { + "memory_current_bytes": 12582912, + "cpu_usage_usec": 531873 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638082 + } + } + }, + { + "elapsed_seconds": 58.72359165300077, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92913664, + "cpu_usage_usec": 4602936 + }, + "prowlarr": { + "memory_current_bytes": 137310208, + "cpu_usage_usec": 8917457 + }, + "qbittorrent": { + "memory_current_bytes": 12582912, + "cpu_usage_usec": 531873 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638082 + } + } + }, + { + "elapsed_seconds": 58.824014364000504, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92913664, + "cpu_usage_usec": 4603115 + }, + "prowlarr": { + "memory_current_bytes": 137818112, + "cpu_usage_usec": 8986380 + }, + "qbittorrent": { + "memory_current_bytes": 12582912, + "cpu_usage_usec": 531873 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638082 + } + } + }, + { + "elapsed_seconds": 58.92441190700083, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92913664, + "cpu_usage_usec": 4603115 + }, + "prowlarr": { + "memory_current_bytes": 137818112, + "cpu_usage_usec": 8986380 + }, + "qbittorrent": { + "memory_current_bytes": 12574720, + "cpu_usage_usec": 531873 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638082 + } + } + }, + { + "elapsed_seconds": 59.02543914200032, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92913664, + "cpu_usage_usec": 4603115 + }, + "prowlarr": { + "memory_current_bytes": 137818112, + "cpu_usage_usec": 8986380 + }, + "qbittorrent": { + "memory_current_bytes": 12574720, + "cpu_usage_usec": 531873 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638082 + } + } + }, + { + "elapsed_seconds": 59.12641098900076, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92913664, + "cpu_usage_usec": 4603115 + }, + "prowlarr": { + "memory_current_bytes": 138080256, + "cpu_usage_usec": 8986461 + }, + "qbittorrent": { + "memory_current_bytes": 12574720, + "cpu_usage_usec": 531924 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638082 + } + } + }, + { + "elapsed_seconds": 59.227263276000485, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92913664, + "cpu_usage_usec": 4603115 + }, + "prowlarr": { + "memory_current_bytes": 138080256, + "cpu_usage_usec": 8986461 + }, + "qbittorrent": { + "memory_current_bytes": 12574720, + "cpu_usage_usec": 531954 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638082 + } + } + }, + { + "elapsed_seconds": 59.32832679400053, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92913664, + "cpu_usage_usec": 4603115 + }, + "prowlarr": { + "memory_current_bytes": 138084352, + "cpu_usage_usec": 8987218 + }, + "qbittorrent": { + "memory_current_bytes": 12697600, + "cpu_usage_usec": 532441 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638082 + } + } + }, + { + "elapsed_seconds": 59.42918627600011, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92913664, + "cpu_usage_usec": 4603115 + }, + "prowlarr": { + "memory_current_bytes": 138084352, + "cpu_usage_usec": 8987218 + }, + "qbittorrent": { + "memory_current_bytes": 12697600, + "cpu_usage_usec": 533694 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638082 + } + } + }, + { + "elapsed_seconds": 59.530031753, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92913664, + "cpu_usage_usec": 4603115 + }, + "prowlarr": { + "memory_current_bytes": 138084352, + "cpu_usage_usec": 8987323 + }, + "qbittorrent": { + "memory_current_bytes": 12697600, + "cpu_usage_usec": 534429 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638158 + } + } + }, + { + "elapsed_seconds": 59.63084807400082, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92913664, + "cpu_usage_usec": 4603115 + }, + "prowlarr": { + "memory_current_bytes": 138084352, + "cpu_usage_usec": 8987323 + }, + "qbittorrent": { + "memory_current_bytes": 12697600, + "cpu_usage_usec": 534816 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638158 + } + } + }, + { + "elapsed_seconds": 59.73122044499996, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92913664, + "cpu_usage_usec": 4603115 + }, + "prowlarr": { + "memory_current_bytes": 137650176, + "cpu_usage_usec": 8987340 + }, + "qbittorrent": { + "memory_current_bytes": 12587008, + "cpu_usage_usec": 534902 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638158 + } + } + }, + { + "elapsed_seconds": 59.83220308199998, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92913664, + "cpu_usage_usec": 4603199 + }, + "prowlarr": { + "memory_current_bytes": 137650176, + "cpu_usage_usec": 8987398 + }, + "qbittorrent": { + "memory_current_bytes": 12587008, + "cpu_usage_usec": 534902 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638158 + } + } + }, + { + "elapsed_seconds": 59.933164469000076, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92913664, + "cpu_usage_usec": 4603199 + }, + "prowlarr": { + "memory_current_bytes": 137650176, + "cpu_usage_usec": 8987398 + }, + "qbittorrent": { + "memory_current_bytes": 12587008, + "cpu_usage_usec": 534902 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638158 + } + } + }, + { + "elapsed_seconds": 60.034296799, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92913664, + "cpu_usage_usec": 4603199 + }, + "prowlarr": { + "memory_current_bytes": 137650176, + "cpu_usage_usec": 8987398 + }, + "qbittorrent": { + "memory_current_bytes": 12587008, + "cpu_usage_usec": 534902 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638158 + } + } + }, + { + "elapsed_seconds": 60.13550664500053, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93437952, + "cpu_usage_usec": 4607997 + }, + "prowlarr": { + "memory_current_bytes": 138436608, + "cpu_usage_usec": 9000633 + }, + "qbittorrent": { + "memory_current_bytes": 12587008, + "cpu_usage_usec": 534946 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638158 + } + } + }, + { + "elapsed_seconds": 60.23645484700046, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94482432, + "cpu_usage_usec": 4625558 + }, + "prowlarr": { + "memory_current_bytes": 138960896, + "cpu_usage_usec": 9022042 + }, + "qbittorrent": { + "memory_current_bytes": 12718080, + "cpu_usage_usec": 534946 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638158 + } + } + }, + { + "elapsed_seconds": 60.33731824200004, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94265344, + "cpu_usage_usec": 4625558 + }, + "prowlarr": { + "memory_current_bytes": 138960896, + "cpu_usage_usec": 9022333 + }, + "qbittorrent": { + "memory_current_bytes": 12718080, + "cpu_usage_usec": 534946 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638158 + } + } + }, + { + "elapsed_seconds": 60.43834798500029, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93814784, + "cpu_usage_usec": 4625558 + }, + "prowlarr": { + "memory_current_bytes": 138960896, + "cpu_usage_usec": 9022333 + }, + "qbittorrent": { + "memory_current_bytes": 12718080, + "cpu_usage_usec": 535045 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638158 + } + } + }, + { + "elapsed_seconds": 60.53924284599998, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93814784, + "cpu_usage_usec": 4625558 + }, + "prowlarr": { + "memory_current_bytes": 138960896, + "cpu_usage_usec": 9022423 + }, + "qbittorrent": { + "memory_current_bytes": 12718080, + "cpu_usage_usec": 535045 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638246 + } + } + }, + { + "elapsed_seconds": 60.63998842300043, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93814784, + "cpu_usage_usec": 4625592 + }, + "prowlarr": { + "memory_current_bytes": 138960896, + "cpu_usage_usec": 9023330 + }, + "qbittorrent": { + "memory_current_bytes": 12926976, + "cpu_usage_usec": 535518 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638246 + } + } + }, + { + "elapsed_seconds": 60.74095078100072, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93814784, + "cpu_usage_usec": 4625592 + }, + "prowlarr": { + "memory_current_bytes": 138702848, + "cpu_usage_usec": 9023653 + }, + "qbittorrent": { + "memory_current_bytes": 12926976, + "cpu_usage_usec": 536470 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638246 + } + } + }, + { + "elapsed_seconds": 60.84173846900012, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93814784, + "cpu_usage_usec": 4625682 + }, + "prowlarr": { + "memory_current_bytes": 138702848, + "cpu_usage_usec": 9023653 + }, + "qbittorrent": { + "memory_current_bytes": 12926976, + "cpu_usage_usec": 536470 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638246 + } + } + }, + { + "elapsed_seconds": 60.94259181800044, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93581312, + "cpu_usage_usec": 4625682 + }, + "prowlarr": { + "memory_current_bytes": 138276864, + "cpu_usage_usec": 9023653 + }, + "qbittorrent": { + "memory_current_bytes": 12926976, + "cpu_usage_usec": 536470 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638246 + } + } + }, + { + "elapsed_seconds": 61.04346209200048, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93581312, + "cpu_usage_usec": 4625682 + }, + "prowlarr": { + "memory_current_bytes": 137900032, + "cpu_usage_usec": 9023899 + }, + "qbittorrent": { + "memory_current_bytes": 12967936, + "cpu_usage_usec": 536470 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638246 + } + } + }, + { + "elapsed_seconds": 61.144399998000154, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93581312, + "cpu_usage_usec": 4625742 + }, + "prowlarr": { + "memory_current_bytes": 137900032, + "cpu_usage_usec": 9024261 + }, + "qbittorrent": { + "memory_current_bytes": 12967936, + "cpu_usage_usec": 536509 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638246 + } + } + }, + { + "elapsed_seconds": 61.245401083000615, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93327360, + "cpu_usage_usec": 4625767 + }, + "prowlarr": { + "memory_current_bytes": 137900032, + "cpu_usage_usec": 9024281 + }, + "qbittorrent": { + "memory_current_bytes": 12967936, + "cpu_usage_usec": 536647 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638246 + } + } + }, + { + "elapsed_seconds": 61.34627659100079, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93069312, + "cpu_usage_usec": 4625767 + }, + "prowlarr": { + "memory_current_bytes": 137854976, + "cpu_usage_usec": 9024332 + }, + "qbittorrent": { + "memory_current_bytes": 12967936, + "cpu_usage_usec": 536647 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638246 + } + } + }, + { + "elapsed_seconds": 61.44723926700044, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93069312, + "cpu_usage_usec": 4625767 + }, + "prowlarr": { + "memory_current_bytes": 137854976, + "cpu_usage_usec": 9024332 + }, + "qbittorrent": { + "memory_current_bytes": 12967936, + "cpu_usage_usec": 536781 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638246 + } + } + }, + { + "elapsed_seconds": 61.548060149000776, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93069312, + "cpu_usage_usec": 4625767 + }, + "prowlarr": { + "memory_current_bytes": 137854976, + "cpu_usage_usec": 9024431 + }, + "qbittorrent": { + "memory_current_bytes": 12931072, + "cpu_usage_usec": 537088 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638299 + } + } + }, + { + "elapsed_seconds": 61.64884848800011, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93069312, + "cpu_usage_usec": 4625767 + }, + "prowlarr": { + "memory_current_bytes": 137854976, + "cpu_usage_usec": 9024701 + }, + "qbittorrent": { + "memory_current_bytes": 12931072, + "cpu_usage_usec": 537136 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638299 + } + } + }, + { + "elapsed_seconds": 61.749696339000366, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93069312, + "cpu_usage_usec": 4625767 + }, + "prowlarr": { + "memory_current_bytes": 137854976, + "cpu_usage_usec": 9024701 + }, + "qbittorrent": { + "memory_current_bytes": 12931072, + "cpu_usage_usec": 537413 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638299 + } + } + }, + { + "elapsed_seconds": 61.850632769000185, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93069312, + "cpu_usage_usec": 4625822 + }, + "prowlarr": { + "memory_current_bytes": 137850880, + "cpu_usage_usec": 9024701 + }, + "qbittorrent": { + "memory_current_bytes": 13094912, + "cpu_usage_usec": 537725 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638299 + } + } + }, + { + "elapsed_seconds": 61.951063002999945, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93069312, + "cpu_usage_usec": 4625822 + }, + "prowlarr": { + "memory_current_bytes": 137850880, + "cpu_usage_usec": 9024701 + }, + "qbittorrent": { + "memory_current_bytes": 12980224, + "cpu_usage_usec": 538578 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638299 + } + } + }, + { + "elapsed_seconds": 62.05180518199995, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93069312, + "cpu_usage_usec": 4625822 + }, + "prowlarr": { + "memory_current_bytes": 137621504, + "cpu_usage_usec": 9024701 + }, + "qbittorrent": { + "memory_current_bytes": 12980224, + "cpu_usage_usec": 539403 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638299 + } + } + }, + { + "elapsed_seconds": 62.15260740800022, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93323264, + "cpu_usage_usec": 4632327 + }, + "prowlarr": { + "memory_current_bytes": 137879552, + "cpu_usage_usec": 9027791 + }, + "qbittorrent": { + "memory_current_bytes": 12873728, + "cpu_usage_usec": 540086 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638299 + } + } + }, + { + "elapsed_seconds": 62.25316467200082, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94285824, + "cpu_usage_usec": 4694084 + }, + "prowlarr": { + "memory_current_bytes": 138674176, + "cpu_usage_usec": 9090390 + }, + "qbittorrent": { + "memory_current_bytes": 12869632, + "cpu_usage_usec": 540321 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638299 + } + } + }, + { + "elapsed_seconds": 62.354026464000526, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94011392, + "cpu_usage_usec": 4694084 + }, + "prowlarr": { + "memory_current_bytes": 138674176, + "cpu_usage_usec": 9090591 + }, + "qbittorrent": { + "memory_current_bytes": 12828672, + "cpu_usage_usec": 541238 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638299 + } + } + }, + { + "elapsed_seconds": 62.45485052100048, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93757440, + "cpu_usage_usec": 4694084 + }, + "prowlarr": { + "memory_current_bytes": 138133504, + "cpu_usage_usec": 9090591 + }, + "qbittorrent": { + "memory_current_bytes": 12800000, + "cpu_usage_usec": 542214 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638299 + } + } + }, + { + "elapsed_seconds": 62.5556930570001, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93757440, + "cpu_usage_usec": 4694084 + }, + "prowlarr": { + "memory_current_bytes": 138133504, + "cpu_usage_usec": 9090673 + }, + "qbittorrent": { + "memory_current_bytes": 12800000, + "cpu_usage_usec": 542236 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638360 + } + } + }, + { + "elapsed_seconds": 62.65656607100027, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93757440, + "cpu_usage_usec": 4694084 + }, + "prowlarr": { + "memory_current_bytes": 138133504, + "cpu_usage_usec": 9090728 + }, + "qbittorrent": { + "memory_current_bytes": 12800000, + "cpu_usage_usec": 543279 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638360 + } + } + }, + { + "elapsed_seconds": 62.75756655500027, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93757440, + "cpu_usage_usec": 4694142 + }, + "prowlarr": { + "memory_current_bytes": 138166272, + "cpu_usage_usec": 9099608 + }, + "qbittorrent": { + "memory_current_bytes": 12652544, + "cpu_usage_usec": 543970 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638360 + } + } + }, + { + "elapsed_seconds": 62.85869083600028, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93757440, + "cpu_usage_usec": 4694218 + }, + "prowlarr": { + "memory_current_bytes": 137924608, + "cpu_usage_usec": 9099608 + }, + "qbittorrent": { + "memory_current_bytes": 12910592, + "cpu_usage_usec": 544661 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638360 + } + } + }, + { + "elapsed_seconds": 62.959366525000405, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93753344, + "cpu_usage_usec": 4694218 + }, + "prowlarr": { + "memory_current_bytes": 137650176, + "cpu_usage_usec": 9099608 + }, + "qbittorrent": { + "memory_current_bytes": 12910592, + "cpu_usage_usec": 545103 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638360 + } + } + }, + { + "elapsed_seconds": 63.060310688000754, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93753344, + "cpu_usage_usec": 4694218 + }, + "prowlarr": { + "memory_current_bytes": 137392128, + "cpu_usage_usec": 9099608 + }, + "qbittorrent": { + "memory_current_bytes": 12906496, + "cpu_usage_usec": 545891 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638360 + } + } + }, + { + "elapsed_seconds": 63.16132903900052, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93753344, + "cpu_usage_usec": 4694218 + }, + "prowlarr": { + "memory_current_bytes": 137392128, + "cpu_usage_usec": 9099654 + }, + "qbittorrent": { + "memory_current_bytes": 12906496, + "cpu_usage_usec": 546060 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638360 + } + } + }, + { + "elapsed_seconds": 63.26209679300064, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93655040, + "cpu_usage_usec": 4706394 + }, + "prowlarr": { + "memory_current_bytes": 137392128, + "cpu_usage_usec": 9100191 + }, + "qbittorrent": { + "memory_current_bytes": 12906496, + "cpu_usage_usec": 546926 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638360 + } + } + }, + { + "elapsed_seconds": 63.362586302000636, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93863936, + "cpu_usage_usec": 4766321 + }, + "prowlarr": { + "memory_current_bytes": 137392128, + "cpu_usage_usec": 9100397 + }, + "qbittorrent": { + "memory_current_bytes": 12906496, + "cpu_usage_usec": 547644 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638360 + } + } + }, + { + "elapsed_seconds": 63.46302331200059, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94277632, + "cpu_usage_usec": 4811176 + }, + "prowlarr": { + "memory_current_bytes": 137134080, + "cpu_usage_usec": 9100397 + }, + "qbittorrent": { + "memory_current_bytes": 12906496, + "cpu_usage_usec": 548193 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638360 + } + } + }, + { + "elapsed_seconds": 63.56390328500038, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94277632, + "cpu_usage_usec": 4811176 + }, + "prowlarr": { + "memory_current_bytes": 137134080, + "cpu_usage_usec": 9100488 + }, + "qbittorrent": { + "memory_current_bytes": 12906496, + "cpu_usage_usec": 548844 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638432 + } + } + }, + { + "elapsed_seconds": 63.66478128900053, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94277632, + "cpu_usage_usec": 4811176 + }, + "prowlarr": { + "memory_current_bytes": 137134080, + "cpu_usage_usec": 9101061 + }, + "qbittorrent": { + "memory_current_bytes": 12886016, + "cpu_usage_usec": 549536 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638432 + } + } + }, + { + "elapsed_seconds": 63.76548619000005, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94277632, + "cpu_usage_usec": 4811176 + }, + "prowlarr": { + "memory_current_bytes": 137129984, + "cpu_usage_usec": 9101497 + }, + "qbittorrent": { + "memory_current_bytes": 13316096, + "cpu_usage_usec": 550306 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638432 + } + } + }, + { + "elapsed_seconds": 63.865875437000796, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94277632, + "cpu_usage_usec": 4811271 + }, + "prowlarr": { + "memory_current_bytes": 137129984, + "cpu_usage_usec": 9101871 + }, + "qbittorrent": { + "memory_current_bytes": 13316096, + "cpu_usage_usec": 551053 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638432 + } + } + }, + { + "elapsed_seconds": 63.966836028000216, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94277632, + "cpu_usage_usec": 4811271 + }, + "prowlarr": { + "memory_current_bytes": 137129984, + "cpu_usage_usec": 9102164 + }, + "qbittorrent": { + "memory_current_bytes": 13316096, + "cpu_usage_usec": 551732 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638432 + } + } + }, + { + "elapsed_seconds": 64.06728995200046, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94277632, + "cpu_usage_usec": 4811271 + }, + "prowlarr": { + "memory_current_bytes": 136871936, + "cpu_usage_usec": 9102164 + }, + "qbittorrent": { + "memory_current_bytes": 13164544, + "cpu_usage_usec": 552386 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638432 + } + } + }, + { + "elapsed_seconds": 64.16772171299999, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94277632, + "cpu_usage_usec": 4811271 + }, + "prowlarr": { + "memory_current_bytes": 136871936, + "cpu_usage_usec": 9102195 + }, + "qbittorrent": { + "memory_current_bytes": 13426688, + "cpu_usage_usec": 552559 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638432 + } + } + }, + { + "elapsed_seconds": 64.26811287700002, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 95162368, + "cpu_usage_usec": 4817475 + }, + "prowlarr": { + "memory_current_bytes": 137920512, + "cpu_usage_usec": 9110417 + }, + "qbittorrent": { + "memory_current_bytes": 13418496, + "cpu_usage_usec": 553366 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638432 + } + } + }, + { + "elapsed_seconds": 64.36858621600004, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94638080, + "cpu_usage_usec": 4817475 + }, + "prowlarr": { + "memory_current_bytes": 137486336, + "cpu_usage_usec": 9110600 + }, + "qbittorrent": { + "memory_current_bytes": 13307904, + "cpu_usage_usec": 553817 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638432 + } + } + }, + { + "elapsed_seconds": 64.46907482999995, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94126080, + "cpu_usage_usec": 4817475 + }, + "prowlarr": { + "memory_current_bytes": 137224192, + "cpu_usage_usec": 9110600 + }, + "qbittorrent": { + "memory_current_bytes": 13094912, + "cpu_usage_usec": 554389 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638432 + } + } + }, + { + "elapsed_seconds": 64.5698684020008, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94126080, + "cpu_usage_usec": 4817475 + }, + "prowlarr": { + "memory_current_bytes": 137220096, + "cpu_usage_usec": 9110672 + }, + "qbittorrent": { + "memory_current_bytes": 13090816, + "cpu_usage_usec": 554907 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638469 + } + } + }, + { + "elapsed_seconds": 64.67073375600012, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94126080, + "cpu_usage_usec": 4817475 + }, + "prowlarr": { + "memory_current_bytes": 136990720, + "cpu_usage_usec": 9111167 + }, + "qbittorrent": { + "memory_current_bytes": 13090816, + "cpu_usage_usec": 554907 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638469 + } + } + }, + { + "elapsed_seconds": 64.77115026699994, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94126080, + "cpu_usage_usec": 4817528 + }, + "prowlarr": { + "memory_current_bytes": 136990720, + "cpu_usage_usec": 9111167 + }, + "qbittorrent": { + "memory_current_bytes": 13058048, + "cpu_usage_usec": 554907 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638469 + } + } + }, + { + "elapsed_seconds": 64.87203671299994, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94126080, + "cpu_usage_usec": 4817615 + }, + "prowlarr": { + "memory_current_bytes": 137752576, + "cpu_usage_usec": 9115859 + }, + "qbittorrent": { + "memory_current_bytes": 12865536, + "cpu_usage_usec": 554907 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638469 + } + } + }, + { + "elapsed_seconds": 64.97284707900053, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94126080, + "cpu_usage_usec": 4817615 + }, + "prowlarr": { + "memory_current_bytes": 137621504, + "cpu_usage_usec": 9131611 + }, + "qbittorrent": { + "memory_current_bytes": 13127680, + "cpu_usage_usec": 554907 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638469 + } + } + }, + { + "elapsed_seconds": 65.07381801100018, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94126080, + "cpu_usage_usec": 4817615 + }, + "prowlarr": { + "memory_current_bytes": 137621504, + "cpu_usage_usec": 9131611 + }, + "qbittorrent": { + "memory_current_bytes": 13127680, + "cpu_usage_usec": 554945 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638469 + } + } + }, + { + "elapsed_seconds": 65.1750722250008, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94126080, + "cpu_usage_usec": 4817615 + }, + "prowlarr": { + "memory_current_bytes": 137621504, + "cpu_usage_usec": 9131659 + }, + "qbittorrent": { + "memory_current_bytes": 13127680, + "cpu_usage_usec": 554945 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638469 + } + } + }, + { + "elapsed_seconds": 65.27597558100024, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94126080, + "cpu_usage_usec": 4817678 + }, + "prowlarr": { + "memory_current_bytes": 137621504, + "cpu_usage_usec": 9131680 + }, + "qbittorrent": { + "memory_current_bytes": 13520896, + "cpu_usage_usec": 555604 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638469 + } + } + }, + { + "elapsed_seconds": 65.37636269300037, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94126080, + "cpu_usage_usec": 4817678 + }, + "prowlarr": { + "memory_current_bytes": 137392128, + "cpu_usage_usec": 9133220 + }, + "qbittorrent": { + "memory_current_bytes": 13254656, + "cpu_usage_usec": 555604 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638469 + } + } + }, + { + "elapsed_seconds": 65.47677394200036, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94126080, + "cpu_usage_usec": 4817678 + }, + "prowlarr": { + "memory_current_bytes": 137392128, + "cpu_usage_usec": 9133220 + }, + "qbittorrent": { + "memory_current_bytes": 12886016, + "cpu_usage_usec": 555658 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638469 + } + } + }, + { + "elapsed_seconds": 65.57757531900006, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94126080, + "cpu_usage_usec": 4817678 + }, + "prowlarr": { + "memory_current_bytes": 137392128, + "cpu_usage_usec": 9133298 + }, + "qbittorrent": { + "memory_current_bytes": 12886016, + "cpu_usage_usec": 555681 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638512 + } + } + }, + { + "elapsed_seconds": 65.67853479400037, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94126080, + "cpu_usage_usec": 4817678 + }, + "prowlarr": { + "memory_current_bytes": 137392128, + "cpu_usage_usec": 9133528 + }, + "qbittorrent": { + "memory_current_bytes": 12886016, + "cpu_usage_usec": 555681 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638512 + } + } + }, + { + "elapsed_seconds": 65.77925795900046, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94126080, + "cpu_usage_usec": 4817678 + }, + "prowlarr": { + "memory_current_bytes": 137191424, + "cpu_usage_usec": 9133528 + }, + "qbittorrent": { + "memory_current_bytes": 13148160, + "cpu_usage_usec": 555869 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638512 + } + } + }, + { + "elapsed_seconds": 65.880169862, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94126080, + "cpu_usage_usec": 4817751 + }, + "prowlarr": { + "memory_current_bytes": 137191424, + "cpu_usage_usec": 9133890 + }, + "qbittorrent": { + "memory_current_bytes": 13410304, + "cpu_usage_usec": 556236 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638512 + } + } + }, + { + "elapsed_seconds": 65.98100145100034, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94126080, + "cpu_usage_usec": 4817751 + }, + "prowlarr": { + "memory_current_bytes": 137191424, + "cpu_usage_usec": 9134170 + }, + "qbittorrent": { + "memory_current_bytes": 13410304, + "cpu_usage_usec": 556236 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638512 + } + } + }, + { + "elapsed_seconds": 66.0817796400006, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94126080, + "cpu_usage_usec": 4817751 + }, + "prowlarr": { + "memory_current_bytes": 137191424, + "cpu_usage_usec": 9134170 + }, + "qbittorrent": { + "memory_current_bytes": 13410304, + "cpu_usage_usec": 556278 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638512 + } + } + }, + { + "elapsed_seconds": 66.18263126400052, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94126080, + "cpu_usage_usec": 4817751 + }, + "prowlarr": { + "memory_current_bytes": 137191424, + "cpu_usage_usec": 9134221 + }, + "qbittorrent": { + "memory_current_bytes": 13410304, + "cpu_usage_usec": 556278 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638512 + } + } + }, + { + "elapsed_seconds": 66.28310841100028, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 95391744, + "cpu_usage_usec": 4894305 + }, + "prowlarr": { + "memory_current_bytes": 138752000, + "cpu_usage_usec": 9185206 + }, + "qbittorrent": { + "memory_current_bytes": 14184448, + "cpu_usage_usec": 559157 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638512 + } + } + }, + { + "elapsed_seconds": 66.3837788410001, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 95293440, + "cpu_usage_usec": 4931501 + }, + "prowlarr": { + "memory_current_bytes": 138452992, + "cpu_usage_usec": 9235205 + }, + "qbittorrent": { + "memory_current_bytes": 14184448, + "cpu_usage_usec": 559625 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638512 + } + } + }, + { + "elapsed_seconds": 66.4844872120002, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 95281152, + "cpu_usage_usec": 4931943 + }, + "prowlarr": { + "memory_current_bytes": 138702848, + "cpu_usage_usec": 9285606 + }, + "qbittorrent": { + "memory_current_bytes": 13484032, + "cpu_usage_usec": 560592 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638512 + } + } + }, + { + "elapsed_seconds": 66.58503718800057, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 95027200, + "cpu_usage_usec": 4931943 + }, + "prowlarr": { + "memory_current_bytes": 138899456, + "cpu_usage_usec": 9335591 + }, + "qbittorrent": { + "memory_current_bytes": 19701760, + "cpu_usage_usec": 601368 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638574 + } + } + }, + { + "elapsed_seconds": 66.68557960900034, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 94769152, + "cpu_usage_usec": 4931943 + }, + "prowlarr": { + "memory_current_bytes": 138825728, + "cpu_usage_usec": 9385854 + }, + "qbittorrent": { + "memory_current_bytes": 27488256, + "cpu_usage_usec": 652302 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638574 + } + } + }, + { + "elapsed_seconds": 66.78643890900003, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 94760960, + "cpu_usage_usec": 4931975 + }, + "prowlarr": { + "memory_current_bytes": 140378112, + "cpu_usage_usec": 9412894 + }, + "qbittorrent": { + "memory_current_bytes": 31014912, + "cpu_usage_usec": 685364 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638574 + } + } + }, + { + "elapsed_seconds": 66.88728698600062, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 94760960, + "cpu_usage_usec": 4932070 + }, + "prowlarr": { + "memory_current_bytes": 140378112, + "cpu_usage_usec": 9412894 + }, + "qbittorrent": { + "memory_current_bytes": 31141888, + "cpu_usage_usec": 687472 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638574 + } + } + }, + { + "elapsed_seconds": 66.98820143600005, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 94760960, + "cpu_usage_usec": 4932070 + }, + "prowlarr": { + "memory_current_bytes": 140378112, + "cpu_usage_usec": 9412894 + }, + "qbittorrent": { + "memory_current_bytes": 31141888, + "cpu_usage_usec": 687728 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638574 + } + } + }, + { + "elapsed_seconds": 67.0890532680005, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 94760960, + "cpu_usage_usec": 4932070 + }, + "prowlarr": { + "memory_current_bytes": 140357632, + "cpu_usage_usec": 9412894 + }, + "qbittorrent": { + "memory_current_bytes": 31051776, + "cpu_usage_usec": 690167 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638574 + } + } + }, + { + "elapsed_seconds": 67.18995838499995, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 94744576, + "cpu_usage_usec": 4932070 + }, + "prowlarr": { + "memory_current_bytes": 140181504, + "cpu_usage_usec": 9412941 + }, + "qbittorrent": { + "memory_current_bytes": 31219712, + "cpu_usage_usec": 692126 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638574 + } + } + }, + { + "elapsed_seconds": 67.29060650500014, + "phase": "idle", + "services": { + "jackett": { + "memory_current_bytes": 94744576, + "cpu_usage_usec": 4932121 + }, + "prowlarr": { + "memory_current_bytes": 140181504, + "cpu_usage_usec": 9412941 + }, + "qbittorrent": { + "memory_current_bytes": 14475264, + "cpu_usage_usec": 695661 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638574 + } + } + }, + { + "elapsed_seconds": 67.39147582500027, + "phase": "idle", + "services": { + "jackett": { + "memory_current_bytes": 94744576, + "cpu_usage_usec": 4932121 + }, + "prowlarr": { + "memory_current_bytes": 140181504, + "cpu_usage_usec": 9413255 + }, + "qbittorrent": { + "memory_current_bytes": 14737408, + "cpu_usage_usec": 695661 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638574 + } + } + }, + { + "elapsed_seconds": 67.49233731999993, + "phase": "idle", + "services": { + "jackett": { + "memory_current_bytes": 94744576, + "cpu_usage_usec": 4932121 + }, + "prowlarr": { + "memory_current_bytes": 140181504, + "cpu_usage_usec": 9413255 + }, + "qbittorrent": { + "memory_current_bytes": 14716928, + "cpu_usage_usec": 695661 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638640 + } + } + }, + { + "elapsed_seconds": 67.59320272900004, + "phase": "idle", + "services": { + "jackett": { + "memory_current_bytes": 94605312, + "cpu_usage_usec": 4932121 + }, + "prowlarr": { + "memory_current_bytes": 140181504, + "cpu_usage_usec": 9413303 + }, + "qbittorrent": { + "memory_current_bytes": 14237696, + "cpu_usage_usec": 695688 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638640 + } + } + }, + { + "elapsed_seconds": 67.69432966800014, + "phase": "idle", + "services": { + "jackett": { + "memory_current_bytes": 94605312, + "cpu_usage_usec": 4932121 + }, + "prowlarr": { + "memory_current_bytes": 140181504, + "cpu_usage_usec": 9413303 + }, + "qbittorrent": { + "memory_current_bytes": 14139392, + "cpu_usage_usec": 695688 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638640 + } + } + }, + { + "elapsed_seconds": 67.79509253100059, + "phase": "idle", + "services": { + "jackett": { + "memory_current_bytes": 94605312, + "cpu_usage_usec": 4932121 + }, + "prowlarr": { + "memory_current_bytes": 140181504, + "cpu_usage_usec": 9413303 + }, + "qbittorrent": { + "memory_current_bytes": 14135296, + "cpu_usage_usec": 695688 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638640 + } + } + }, + { + "elapsed_seconds": 67.89598536800077, + "phase": "idle", + "services": { + "jackett": { + "memory_current_bytes": 94605312, + "cpu_usage_usec": 4932200 + }, + "prowlarr": { + "memory_current_bytes": 140181504, + "cpu_usage_usec": 9413357 + }, + "qbittorrent": { + "memory_current_bytes": 13897728, + "cpu_usage_usec": 695688 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638640 + } + } + }, + { + "elapsed_seconds": 67.99694970400014, + "phase": "idle", + "services": { + "jackett": { + "memory_current_bytes": 94605312, + "cpu_usage_usec": 4932200 + }, + "prowlarr": { + "memory_current_bytes": 140181504, + "cpu_usage_usec": 9413357 + }, + "qbittorrent": { + "memory_current_bytes": 13996032, + "cpu_usage_usec": 696484 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638640 + } + } + }, + { + "elapsed_seconds": 68.09800605600049, + "phase": "idle", + "services": { + "jackett": { + "memory_current_bytes": 94605312, + "cpu_usage_usec": 4932200 + }, + "prowlarr": { + "memory_current_bytes": 140181504, + "cpu_usage_usec": 9413357 + }, + "qbittorrent": { + "memory_current_bytes": 13996032, + "cpu_usage_usec": 696543 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638640 + } + } + }, + { + "elapsed_seconds": 68.19883569500053, + "phase": "idle", + "services": { + "jackett": { + "memory_current_bytes": 94605312, + "cpu_usage_usec": 4932200 + }, + "prowlarr": { + "memory_current_bytes": 140181504, + "cpu_usage_usec": 9413357 + }, + "qbittorrent": { + "memory_current_bytes": 13996032, + "cpu_usage_usec": 696593 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638640 + } + } + }, + { + "elapsed_seconds": 68.2992946910008, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94605312, + "cpu_usage_usec": 4932200 + }, + "prowlarr": { + "memory_current_bytes": 140705792, + "cpu_usage_usec": 9440653 + }, + "qbittorrent": { + "memory_current_bytes": 13828096, + "cpu_usage_usec": 696806 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638640 + } + } + }, + { + "elapsed_seconds": 68.40029693400083, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94605312, + "cpu_usage_usec": 4932200 + }, + "prowlarr": { + "memory_current_bytes": 140664832, + "cpu_usage_usec": 9449380 + }, + "qbittorrent": { + "memory_current_bytes": 13828096, + "cpu_usage_usec": 696806 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638640 + } + } + }, + { + "elapsed_seconds": 68.50137656000061, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94605312, + "cpu_usage_usec": 4932200 + }, + "prowlarr": { + "memory_current_bytes": 140664832, + "cpu_usage_usec": 9449380 + }, + "qbittorrent": { + "memory_current_bytes": 13828096, + "cpu_usage_usec": 696806 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638718 + } + } + }, + { + "elapsed_seconds": 68.6023504220002, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94605312, + "cpu_usage_usec": 4932200 + }, + "prowlarr": { + "memory_current_bytes": 140664832, + "cpu_usage_usec": 9449456 + }, + "qbittorrent": { + "memory_current_bytes": 13828096, + "cpu_usage_usec": 696861 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638718 + } + } + }, + { + "elapsed_seconds": 68.70332239100026, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94605312, + "cpu_usage_usec": 4932200 + }, + "prowlarr": { + "memory_current_bytes": 140435456, + "cpu_usage_usec": 9449456 + }, + "qbittorrent": { + "memory_current_bytes": 13582336, + "cpu_usage_usec": 697010 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638718 + } + } + }, + { + "elapsed_seconds": 68.80455597000037, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94605312, + "cpu_usage_usec": 4932200 + }, + "prowlarr": { + "memory_current_bytes": 140435456, + "cpu_usage_usec": 9449456 + }, + "qbittorrent": { + "memory_current_bytes": 13582336, + "cpu_usage_usec": 697010 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638718 + } + } + }, + { + "elapsed_seconds": 68.90544810700067, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94863360, + "cpu_usage_usec": 4945154 + }, + "prowlarr": { + "memory_current_bytes": 140435456, + "cpu_usage_usec": 9449504 + }, + "qbittorrent": { + "memory_current_bytes": 13582336, + "cpu_usage_usec": 697010 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638718 + } + } + }, + { + "elapsed_seconds": 69.00645212200016, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94863360, + "cpu_usage_usec": 4945154 + }, + "prowlarr": { + "memory_current_bytes": 140435456, + "cpu_usage_usec": 9449504 + }, + "qbittorrent": { + "memory_current_bytes": 13443072, + "cpu_usage_usec": 697010 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638718 + } + } + }, + { + "elapsed_seconds": 69.10726246600007, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94863360, + "cpu_usage_usec": 4945154 + }, + "prowlarr": { + "memory_current_bytes": 140435456, + "cpu_usage_usec": 9449504 + }, + "qbittorrent": { + "memory_current_bytes": 13443072, + "cpu_usage_usec": 697061 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638718 + } + } + }, + { + "elapsed_seconds": 69.20819280600062, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94863360, + "cpu_usage_usec": 4945154 + }, + "prowlarr": { + "memory_current_bytes": 140435456, + "cpu_usage_usec": 9449504 + }, + "qbittorrent": { + "memory_current_bytes": 13443072, + "cpu_usage_usec": 697106 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638718 + } + } + }, + { + "elapsed_seconds": 69.30860085800032, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94613504, + "cpu_usage_usec": 4945154 + }, + "prowlarr": { + "memory_current_bytes": 140435456, + "cpu_usage_usec": 9449504 + }, + "qbittorrent": { + "memory_current_bytes": 13258752, + "cpu_usage_usec": 697296 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638718 + } + } + }, + { + "elapsed_seconds": 69.40942420300053, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94613504, + "cpu_usage_usec": 4945154 + }, + "prowlarr": { + "memory_current_bytes": 140296192, + "cpu_usage_usec": 9449730 + }, + "qbittorrent": { + "memory_current_bytes": 13520896, + "cpu_usage_usec": 697296 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638718 + } + } + }, + { + "elapsed_seconds": 69.51029124200068, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94613504, + "cpu_usage_usec": 4945154 + }, + "prowlarr": { + "memory_current_bytes": 140296192, + "cpu_usage_usec": 9449730 + }, + "qbittorrent": { + "memory_current_bytes": 13520896, + "cpu_usage_usec": 697296 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638785 + } + } + }, + { + "elapsed_seconds": 69.61118210700079, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94613504, + "cpu_usage_usec": 4945154 + }, + "prowlarr": { + "memory_current_bytes": 140296192, + "cpu_usage_usec": 9449805 + }, + "qbittorrent": { + "memory_current_bytes": 13520896, + "cpu_usage_usec": 697340 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638785 + } + } + }, + { + "elapsed_seconds": 69.71208274000037, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94613504, + "cpu_usage_usec": 4945154 + }, + "prowlarr": { + "memory_current_bytes": 140296192, + "cpu_usage_usec": 9449805 + }, + "qbittorrent": { + "memory_current_bytes": 13676544, + "cpu_usage_usec": 698147 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638785 + } + } + }, + { + "elapsed_seconds": 69.8130277780001, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94613504, + "cpu_usage_usec": 4945154 + }, + "prowlarr": { + "memory_current_bytes": 140296192, + "cpu_usage_usec": 9449857 + }, + "qbittorrent": { + "memory_current_bytes": 13631488, + "cpu_usage_usec": 698200 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638785 + } + } + }, + { + "elapsed_seconds": 69.9138750330003, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94875648, + "cpu_usage_usec": 4945735 + }, + "prowlarr": { + "memory_current_bytes": 140296192, + "cpu_usage_usec": 9449857 + }, + "qbittorrent": { + "memory_current_bytes": 13631488, + "cpu_usage_usec": 698200 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638785 + } + } + }, + { + "elapsed_seconds": 70.01472617900072, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94875648, + "cpu_usage_usec": 4945735 + }, + "prowlarr": { + "memory_current_bytes": 140296192, + "cpu_usage_usec": 9449857 + }, + "qbittorrent": { + "memory_current_bytes": 13631488, + "cpu_usage_usec": 698512 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638785 + } + } + }, + { + "elapsed_seconds": 70.11564755800009, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94875648, + "cpu_usage_usec": 4945735 + }, + "prowlarr": { + "memory_current_bytes": 140296192, + "cpu_usage_usec": 9450306 + }, + "qbittorrent": { + "memory_current_bytes": 13631488, + "cpu_usage_usec": 698537 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638785 + } + } + }, + { + "elapsed_seconds": 70.21648324500075, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94875648, + "cpu_usage_usec": 4945782 + }, + "prowlarr": { + "memory_current_bytes": 140296192, + "cpu_usage_usec": 9450306 + }, + "qbittorrent": { + "memory_current_bytes": 13631488, + "cpu_usage_usec": 698658 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638785 + } + } + }, + { + "elapsed_seconds": 70.31733950100079, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94875648, + "cpu_usage_usec": 4945782 + }, + "prowlarr": { + "memory_current_bytes": 140296192, + "cpu_usage_usec": 9450653 + }, + "qbittorrent": { + "memory_current_bytes": 13619200, + "cpu_usage_usec": 698817 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638785 + } + } + }, + { + "elapsed_seconds": 70.41841143200054, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94875648, + "cpu_usage_usec": 4945782 + }, + "prowlarr": { + "memory_current_bytes": 140296192, + "cpu_usage_usec": 9450906 + }, + "qbittorrent": { + "memory_current_bytes": 13619200, + "cpu_usage_usec": 698817 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638785 + } + } + }, + { + "elapsed_seconds": 70.5193214890005, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 96182272, + "cpu_usage_usec": 4958481 + }, + "prowlarr": { + "memory_current_bytes": 142102528, + "cpu_usage_usec": 9476160 + }, + "qbittorrent": { + "memory_current_bytes": 13578240, + "cpu_usage_usec": 698970 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638874 + } + } + }, + { + "elapsed_seconds": 70.61986058300045, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 95928320, + "cpu_usage_usec": 4958481 + }, + "prowlarr": { + "memory_current_bytes": 142102528, + "cpu_usage_usec": 9476249 + }, + "qbittorrent": { + "memory_current_bytes": 13578240, + "cpu_usage_usec": 699019 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638874 + } + } + }, + { + "elapsed_seconds": 70.72076445700077, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 95928320, + "cpu_usage_usec": 4958481 + }, + "prowlarr": { + "memory_current_bytes": 141901824, + "cpu_usage_usec": 9476249 + }, + "qbittorrent": { + "memory_current_bytes": 13578240, + "cpu_usage_usec": 699157 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638874 + } + } + }, + { + "elapsed_seconds": 70.82125508400077, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 95686656, + "cpu_usage_usec": 4958520 + }, + "prowlarr": { + "memory_current_bytes": 141639680, + "cpu_usage_usec": 9476281 + }, + "qbittorrent": { + "memory_current_bytes": 13578240, + "cpu_usage_usec": 699157 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638874 + } + } + }, + { + "elapsed_seconds": 70.92224365100083, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 95686656, + "cpu_usage_usec": 4958520 + }, + "prowlarr": { + "memory_current_bytes": 141639680, + "cpu_usage_usec": 9476281 + }, + "qbittorrent": { + "memory_current_bytes": 13996032, + "cpu_usage_usec": 700678 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638874 + } + } + }, + { + "elapsed_seconds": 71.02311377200022, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 95428608, + "cpu_usage_usec": 4958563 + }, + "prowlarr": { + "memory_current_bytes": 141676544, + "cpu_usage_usec": 9476790 + }, + "qbittorrent": { + "memory_current_bytes": 13959168, + "cpu_usage_usec": 701654 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638874 + } + } + }, + { + "elapsed_seconds": 71.1235177260005, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94916608, + "cpu_usage_usec": 4958563 + }, + "prowlarr": { + "memory_current_bytes": 142434304, + "cpu_usage_usec": 9480341 + }, + "qbittorrent": { + "memory_current_bytes": 13492224, + "cpu_usage_usec": 702243 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638874 + } + } + }, + { + "elapsed_seconds": 71.22394758700011, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94916608, + "cpu_usage_usec": 4958563 + }, + "prowlarr": { + "memory_current_bytes": 142176256, + "cpu_usage_usec": 9480341 + }, + "qbittorrent": { + "memory_current_bytes": 13488128, + "cpu_usage_usec": 702813 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638874 + } + } + }, + { + "elapsed_seconds": 71.32492768500015, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94916608, + "cpu_usage_usec": 4958563 + }, + "prowlarr": { + "memory_current_bytes": 142176256, + "cpu_usage_usec": 9480881 + }, + "qbittorrent": { + "memory_current_bytes": 13488128, + "cpu_usage_usec": 703797 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638874 + } + } + }, + { + "elapsed_seconds": 71.42591492400061, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94916608, + "cpu_usage_usec": 4958563 + }, + "prowlarr": { + "memory_current_bytes": 141914112, + "cpu_usage_usec": 9480881 + }, + "qbittorrent": { + "memory_current_bytes": 13488128, + "cpu_usage_usec": 704548 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638874 + } + } + }, + { + "elapsed_seconds": 71.5267702330002, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 95133696, + "cpu_usage_usec": 4989702 + }, + "prowlarr": { + "memory_current_bytes": 141914112, + "cpu_usage_usec": 9482066 + }, + "qbittorrent": { + "memory_current_bytes": 13488128, + "cpu_usage_usec": 704834 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638891 + } + } + }, + { + "elapsed_seconds": 71.62755751000077, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 95129600, + "cpu_usage_usec": 4989702 + }, + "prowlarr": { + "memory_current_bytes": 141914112, + "cpu_usage_usec": 9482066 + }, + "qbittorrent": { + "memory_current_bytes": 13684736, + "cpu_usage_usec": 705848 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638891 + } + } + }, + { + "elapsed_seconds": 71.72840588899999, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 95129600, + "cpu_usage_usec": 4989702 + }, + "prowlarr": { + "memory_current_bytes": 141914112, + "cpu_usage_usec": 9482333 + }, + "qbittorrent": { + "memory_current_bytes": 13684736, + "cpu_usage_usec": 706943 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638891 + } + } + }, + { + "elapsed_seconds": 71.8287934050004, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 95129600, + "cpu_usage_usec": 4989758 + }, + "prowlarr": { + "memory_current_bytes": 141914112, + "cpu_usage_usec": 9482377 + }, + "qbittorrent": { + "memory_current_bytes": 13684736, + "cpu_usage_usec": 707142 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638891 + } + } + }, + { + "elapsed_seconds": 71.92966030600019, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 95129600, + "cpu_usage_usec": 4989758 + }, + "prowlarr": { + "memory_current_bytes": 141914112, + "cpu_usage_usec": 9482377 + }, + "qbittorrent": { + "memory_current_bytes": 13684736, + "cpu_usage_usec": 707980 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638891 + } + } + }, + { + "elapsed_seconds": 72.03050541700031, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94867456, + "cpu_usage_usec": 4989758 + }, + "prowlarr": { + "memory_current_bytes": 141914112, + "cpu_usage_usec": 9482816 + }, + "qbittorrent": { + "memory_current_bytes": 13684736, + "cpu_usage_usec": 708586 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638891 + } + } + }, + { + "elapsed_seconds": 72.13145789800001, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94867456, + "cpu_usage_usec": 4989758 + }, + "prowlarr": { + "memory_current_bytes": 141844480, + "cpu_usage_usec": 9482816 + }, + "qbittorrent": { + "memory_current_bytes": 13840384, + "cpu_usage_usec": 709120 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638891 + } + } + }, + { + "elapsed_seconds": 72.2323098400002, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94867456, + "cpu_usage_usec": 4989758 + }, + "prowlarr": { + "memory_current_bytes": 141844480, + "cpu_usage_usec": 9482816 + }, + "qbittorrent": { + "memory_current_bytes": 13840384, + "cpu_usage_usec": 709972 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638891 + } + } + }, + { + "elapsed_seconds": 72.3331942090008, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94867456, + "cpu_usage_usec": 4989758 + }, + "prowlarr": { + "memory_current_bytes": 141844480, + "cpu_usage_usec": 9483364 + }, + "qbittorrent": { + "memory_current_bytes": 13819904, + "cpu_usage_usec": 710972 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638891 + } + } + }, + { + "elapsed_seconds": 72.43419646100028, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94699520, + "cpu_usage_usec": 4989758 + }, + "prowlarr": { + "memory_current_bytes": 141844480, + "cpu_usage_usec": 9483364 + }, + "qbittorrent": { + "memory_current_bytes": 13819904, + "cpu_usage_usec": 711063 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638891 + } + } + }, + { + "elapsed_seconds": 72.53461828400032, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 95465472, + "cpu_usage_usec": 5041178 + }, + "prowlarr": { + "memory_current_bytes": 138604544, + "cpu_usage_usec": 9566809 + }, + "qbittorrent": { + "memory_current_bytes": 13905920, + "cpu_usage_usec": 711370 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638962 + } + } + }, + { + "elapsed_seconds": 72.63541989000078, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 95436800, + "cpu_usage_usec": 5059723 + }, + "prowlarr": { + "memory_current_bytes": 138579968, + "cpu_usage_usec": 9576930 + }, + "qbittorrent": { + "memory_current_bytes": 13905920, + "cpu_usage_usec": 712274 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638962 + } + } + }, + { + "elapsed_seconds": 72.73628472500059, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 95436800, + "cpu_usage_usec": 5059723 + }, + "prowlarr": { + "memory_current_bytes": 138579968, + "cpu_usage_usec": 9577216 + }, + "qbittorrent": { + "memory_current_bytes": 13774848, + "cpu_usage_usec": 712721 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638962 + } + } + }, + { + "elapsed_seconds": 72.83715091000067, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 95436800, + "cpu_usage_usec": 5059781 + }, + "prowlarr": { + "memory_current_bytes": 138240000, + "cpu_usage_usec": 9577273 + }, + "qbittorrent": { + "memory_current_bytes": 13774848, + "cpu_usage_usec": 713199 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638962 + } + } + }, + { + "elapsed_seconds": 72.93803842200032, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 95436800, + "cpu_usage_usec": 5059781 + }, + "prowlarr": { + "memory_current_bytes": 138240000, + "cpu_usage_usec": 9577273 + }, + "qbittorrent": { + "memory_current_bytes": 13770752, + "cpu_usage_usec": 713497 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638962 + } + } + }, + { + "elapsed_seconds": 73.03892286900009, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 95420416, + "cpu_usage_usec": 5059832 + }, + "prowlarr": { + "memory_current_bytes": 138240000, + "cpu_usage_usec": 9577273 + }, + "qbittorrent": { + "memory_current_bytes": 13770752, + "cpu_usage_usec": 714304 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638962 + } + } + }, + { + "elapsed_seconds": 73.13972534799996, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 95420416, + "cpu_usage_usec": 5059832 + }, + "prowlarr": { + "memory_current_bytes": 138240000, + "cpu_usage_usec": 9577273 + }, + "qbittorrent": { + "memory_current_bytes": 13770752, + "cpu_usage_usec": 714531 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638962 + } + } + }, + { + "elapsed_seconds": 73.24056005900002, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 95420416, + "cpu_usage_usec": 5059832 + }, + "prowlarr": { + "memory_current_bytes": 138743808, + "cpu_usage_usec": 9600814 + }, + "qbittorrent": { + "memory_current_bytes": 13770752, + "cpu_usage_usec": 714653 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638962 + } + } + }, + { + "elapsed_seconds": 73.34143613700053, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 95170560, + "cpu_usage_usec": 5059832 + }, + "prowlarr": { + "memory_current_bytes": 138743808, + "cpu_usage_usec": 9601271 + }, + "qbittorrent": { + "memory_current_bytes": 13770752, + "cpu_usage_usec": 714779 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638962 + } + } + }, + { + "elapsed_seconds": 73.44227408700044, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 95170560, + "cpu_usage_usec": 5059832 + }, + "prowlarr": { + "memory_current_bytes": 138739712, + "cpu_usage_usec": 9601271 + }, + "qbittorrent": { + "memory_current_bytes": 13770752, + "cpu_usage_usec": 714779 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1638962 + } + } + }, + { + "elapsed_seconds": 73.54287477600064, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94908416, + "cpu_usage_usec": 5059885 + }, + "prowlarr": { + "memory_current_bytes": 138211328, + "cpu_usage_usec": 9601335 + }, + "qbittorrent": { + "memory_current_bytes": 13684736, + "cpu_usage_usec": 714779 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1639037 + } + } + }, + { + "elapsed_seconds": 73.64368468200064, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94908416, + "cpu_usage_usec": 5059885 + }, + "prowlarr": { + "memory_current_bytes": 138133504, + "cpu_usage_usec": 9601335 + }, + "qbittorrent": { + "memory_current_bytes": 13910016, + "cpu_usage_usec": 714794 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1639037 + } + } + }, + { + "elapsed_seconds": 73.74447593100012, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94908416, + "cpu_usage_usec": 5059885 + }, + "prowlarr": { + "memory_current_bytes": 138395648, + "cpu_usage_usec": 9603287 + }, + "qbittorrent": { + "memory_current_bytes": 13910016, + "cpu_usage_usec": 714794 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1639037 + } + } + }, + { + "elapsed_seconds": 73.84526946400001, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94908416, + "cpu_usage_usec": 5059955 + }, + "prowlarr": { + "memory_current_bytes": 138153984, + "cpu_usage_usec": 9603345 + }, + "qbittorrent": { + "memory_current_bytes": 14139392, + "cpu_usage_usec": 715465 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1639037 + } + } + }, + { + "elapsed_seconds": 73.9456816890006, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94908416, + "cpu_usage_usec": 5059955 + }, + "prowlarr": { + "memory_current_bytes": 138153984, + "cpu_usage_usec": 9603345 + }, + "qbittorrent": { + "memory_current_bytes": 14237696, + "cpu_usage_usec": 715933 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1639037 + } + } + }, + { + "elapsed_seconds": 74.04653180300011, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94908416, + "cpu_usage_usec": 5059955 + }, + "prowlarr": { + "memory_current_bytes": 138153984, + "cpu_usage_usec": 9603345 + }, + "qbittorrent": { + "memory_current_bytes": 14237696, + "cpu_usage_usec": 716236 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1639037 + } + } + }, + { + "elapsed_seconds": 74.14736716200059, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94908416, + "cpu_usage_usec": 5059955 + }, + "prowlarr": { + "memory_current_bytes": 138153984, + "cpu_usage_usec": 9603345 + }, + "qbittorrent": { + "memory_current_bytes": 14225408, + "cpu_usage_usec": 717059 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1639037 + } + } + }, + { + "elapsed_seconds": 74.24819223500072, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94908416, + "cpu_usage_usec": 5059955 + }, + "prowlarr": { + "memory_current_bytes": 138153984, + "cpu_usage_usec": 9604114 + }, + "qbittorrent": { + "memory_current_bytes": 14487552, + "cpu_usage_usec": 717984 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1639037 + } + } + }, + { + "elapsed_seconds": 74.34861405500033, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94908416, + "cpu_usage_usec": 5059955 + }, + "prowlarr": { + "memory_current_bytes": 137912320, + "cpu_usage_usec": 9604388 + }, + "qbittorrent": { + "memory_current_bytes": 14385152, + "cpu_usage_usec": 718487 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1639037 + } + } + }, + { + "elapsed_seconds": 74.44945658300003, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94908416, + "cpu_usage_usec": 5059955 + }, + "prowlarr": { + "memory_current_bytes": 137912320, + "cpu_usage_usec": 9604388 + }, + "qbittorrent": { + "memory_current_bytes": 14647296, + "cpu_usage_usec": 719153 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1639037 + } + } + }, + { + "elapsed_seconds": 74.54990652700053, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 95690752, + "cpu_usage_usec": 5070590 + }, + "prowlarr": { + "memory_current_bytes": 142512128, + "cpu_usage_usec": 9679436 + }, + "qbittorrent": { + "memory_current_bytes": 14274560, + "cpu_usage_usec": 719495 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1639063 + } + } + }, + { + "elapsed_seconds": 74.65039898500072, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 95690752, + "cpu_usage_usec": 5070590 + }, + "prowlarr": { + "memory_current_bytes": 142249984, + "cpu_usage_usec": 9679436 + }, + "qbittorrent": { + "memory_current_bytes": 14012416, + "cpu_usage_usec": 719692 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1639063 + } + } + }, + { + "elapsed_seconds": 74.75087209499998, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 95440896, + "cpu_usage_usec": 5070590 + }, + "prowlarr": { + "memory_current_bytes": 142249984, + "cpu_usage_usec": 9679436 + }, + "qbittorrent": { + "memory_current_bytes": 14012416, + "cpu_usage_usec": 719900 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1639063 + } + } + }, + { + "elapsed_seconds": 74.85139856300066, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 95182848, + "cpu_usage_usec": 5070633 + }, + "prowlarr": { + "memory_current_bytes": 141758464, + "cpu_usage_usec": 9679473 + }, + "qbittorrent": { + "memory_current_bytes": 14012416, + "cpu_usage_usec": 719947 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1639063 + } + } + }, + { + "elapsed_seconds": 74.95210784000028, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 95182848, + "cpu_usage_usec": 5070633 + }, + "prowlarr": { + "memory_current_bytes": 141553664, + "cpu_usage_usec": 9679473 + }, + "qbittorrent": { + "memory_current_bytes": 13975552, + "cpu_usage_usec": 719947 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1639063 + } + } + }, + { + "elapsed_seconds": 75.05297825700018, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 95170560, + "cpu_usage_usec": 5070677 + }, + "prowlarr": { + "memory_current_bytes": 141553664, + "cpu_usage_usec": 9679473 + }, + "qbittorrent": { + "memory_current_bytes": 13975552, + "cpu_usage_usec": 719947 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1639063 + } + } + }, + { + "elapsed_seconds": 75.1537755670006, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 95170560, + "cpu_usage_usec": 5070677 + }, + "prowlarr": { + "memory_current_bytes": 141553664, + "cpu_usage_usec": 9679473 + }, + "qbittorrent": { + "memory_current_bytes": 13975552, + "cpu_usage_usec": 719970 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1639063 + } + } + }, + { + "elapsed_seconds": 75.25444097800028, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 95170560, + "cpu_usage_usec": 5070677 + }, + "prowlarr": { + "memory_current_bytes": 142573568, + "cpu_usage_usec": 9696705 + }, + "qbittorrent": { + "memory_current_bytes": 13975552, + "cpu_usage_usec": 719992 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1639063 + } + } + }, + { + "elapsed_seconds": 75.35531508900021, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 95170560, + "cpu_usage_usec": 5070677 + }, + "prowlarr": { + "memory_current_bytes": 142573568, + "cpu_usage_usec": 9711845 + }, + "qbittorrent": { + "memory_current_bytes": 13975552, + "cpu_usage_usec": 720157 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1639063 + } + } + }, + { + "elapsed_seconds": 75.45618912400005, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94912512, + "cpu_usage_usec": 5070725 + }, + "prowlarr": { + "memory_current_bytes": 142573568, + "cpu_usage_usec": 9711845 + }, + "qbittorrent": { + "memory_current_bytes": 13975552, + "cpu_usage_usec": 720157 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1639063 + } + } + }, + { + "elapsed_seconds": 75.5566750500002, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94912512, + "cpu_usage_usec": 5070751 + }, + "prowlarr": { + "memory_current_bytes": 142725120, + "cpu_usage_usec": 9712273 + }, + "qbittorrent": { + "memory_current_bytes": 14237696, + "cpu_usage_usec": 720340 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1639115 + } + } + }, + { + "elapsed_seconds": 75.65746318200036, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94912512, + "cpu_usage_usec": 5070751 + }, + "prowlarr": { + "memory_current_bytes": 142462976, + "cpu_usage_usec": 9712392 + }, + "qbittorrent": { + "memory_current_bytes": 14233600, + "cpu_usage_usec": 720994 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1639115 + } + } + }, + { + "elapsed_seconds": 75.75841589200081, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94912512, + "cpu_usage_usec": 5070751 + }, + "prowlarr": { + "memory_current_bytes": 142458880, + "cpu_usage_usec": 9713559 + }, + "qbittorrent": { + "memory_current_bytes": 14233600, + "cpu_usage_usec": 721419 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1639115 + } + } + }, + { + "elapsed_seconds": 75.85937560399998, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94912512, + "cpu_usage_usec": 5070814 + }, + "prowlarr": { + "memory_current_bytes": 142458880, + "cpu_usage_usec": 9713622 + }, + "qbittorrent": { + "memory_current_bytes": 14213120, + "cpu_usage_usec": 721833 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1639115 + } + } + }, + { + "elapsed_seconds": 75.96029757600081, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94912512, + "cpu_usage_usec": 5070814 + }, + "prowlarr": { + "memory_current_bytes": 142200832, + "cpu_usage_usec": 9714104 + }, + "qbittorrent": { + "memory_current_bytes": 14311424, + "cpu_usage_usec": 722838 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1639115 + } + } + }, + { + "elapsed_seconds": 76.06110289700064, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94912512, + "cpu_usage_usec": 5070814 + }, + "prowlarr": { + "memory_current_bytes": 142200832, + "cpu_usage_usec": 9714104 + }, + "qbittorrent": { + "memory_current_bytes": 14311424, + "cpu_usage_usec": 723888 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1639115 + } + } + }, + { + "elapsed_seconds": 76.16193497700078, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94912512, + "cpu_usage_usec": 5070814 + }, + "prowlarr": { + "memory_current_bytes": 142200832, + "cpu_usage_usec": 9714104 + }, + "qbittorrent": { + "memory_current_bytes": 14311424, + "cpu_usage_usec": 725064 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1639115 + } + } + }, + { + "elapsed_seconds": 76.26272963500014, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94912512, + "cpu_usage_usec": 5070814 + }, + "prowlarr": { + "memory_current_bytes": 142200832, + "cpu_usage_usec": 9714997 + }, + "qbittorrent": { + "memory_current_bytes": 14311424, + "cpu_usage_usec": 725700 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1639115 + } + } + }, + { + "elapsed_seconds": 76.36356116000024, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 94912512, + "cpu_usage_usec": 5070814 + }, + "prowlarr": { + "memory_current_bytes": 142200832, + "cpu_usage_usec": 9715658 + }, + "qbittorrent": { + "memory_current_bytes": 14311424, + "cpu_usage_usec": 726577 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1639115 + } + } + }, + { + "elapsed_seconds": 76.46459976000006, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 95371264, + "cpu_usage_usec": 5079375 + }, + "prowlarr": { + "memory_current_bytes": 141979648, + "cpu_usage_usec": 9720052 + }, + "qbittorrent": { + "memory_current_bytes": 14311424, + "cpu_usage_usec": 727699 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1639115 + } + } + }, + { + "elapsed_seconds": 76.56510197900025, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 95690752, + "cpu_usage_usec": 5140076 + }, + "prowlarr": { + "memory_current_bytes": 141979648, + "cpu_usage_usec": 9720098 + }, + "qbittorrent": { + "memory_current_bytes": 14262272, + "cpu_usage_usec": 727795 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1639159 + } + } + }, + { + "elapsed_seconds": 76.66587677200005, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 95674368, + "cpu_usage_usec": 5140076 + }, + "prowlarr": { + "memory_current_bytes": 141787136, + "cpu_usage_usec": 9720569 + }, + "qbittorrent": { + "memory_current_bytes": 14262272, + "cpu_usage_usec": 728581 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1639159 + } + } + }, + { + "elapsed_seconds": 76.76681650699993, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 95674368, + "cpu_usage_usec": 5140076 + }, + "prowlarr": { + "memory_current_bytes": 141787136, + "cpu_usage_usec": 9720569 + }, + "qbittorrent": { + "memory_current_bytes": 14524416, + "cpu_usage_usec": 728912 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1639159 + } + } + }, + { + "elapsed_seconds": 76.86766206900029, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 95674368, + "cpu_usage_usec": 5140139 + }, + "prowlarr": { + "memory_current_bytes": 141787136, + "cpu_usage_usec": 9720613 + }, + "qbittorrent": { + "memory_current_bytes": 14524416, + "cpu_usage_usec": 729662 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1639159 + } + } + }, + { + "elapsed_seconds": 76.96854845600046, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 95674368, + "cpu_usage_usec": 5142260 + }, + "prowlarr": { + "memory_current_bytes": 141787136, + "cpu_usage_usec": 9720613 + }, + "qbittorrent": { + "memory_current_bytes": 14524416, + "cpu_usage_usec": 730098 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1639159 + } + } + }, + { + "elapsed_seconds": 77.06891945000007, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 95674368, + "cpu_usage_usec": 5142260 + }, + "prowlarr": { + "memory_current_bytes": 141787136, + "cpu_usage_usec": 9720613 + }, + "qbittorrent": { + "memory_current_bytes": 14524416, + "cpu_usage_usec": 730615 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1639159 + } + } + }, + { + "elapsed_seconds": 77.16978649200064, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 95670272, + "cpu_usage_usec": 5142260 + }, + "prowlarr": { + "memory_current_bytes": 141787136, + "cpu_usage_usec": 9720613 + }, + "qbittorrent": { + "memory_current_bytes": 14524416, + "cpu_usage_usec": 731217 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1639159 + } + } + }, + { + "elapsed_seconds": 77.27060738900036, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 95670272, + "cpu_usage_usec": 5142260 + }, + "prowlarr": { + "memory_current_bytes": 141787136, + "cpu_usage_usec": 9720613 + }, + "qbittorrent": { + "memory_current_bytes": 14680064, + "cpu_usage_usec": 732081 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1639159 + } + } + }, + { + "elapsed_seconds": 77.37114143500003, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 95670272, + "cpu_usage_usec": 5142260 + }, + "prowlarr": { + "memory_current_bytes": 141787136, + "cpu_usage_usec": 9721169 + }, + "qbittorrent": { + "memory_current_bytes": 14680064, + "cpu_usage_usec": 733149 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1639159 + } + } + }, + { + "elapsed_seconds": 77.47158657399996, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 95911936, + "cpu_usage_usec": 5150215 + }, + "prowlarr": { + "memory_current_bytes": 143339520, + "cpu_usage_usec": 9736251 + }, + "qbittorrent": { + "memory_current_bytes": 14512128, + "cpu_usage_usec": 733757 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1639159 + } + } + }, + { + "elapsed_seconds": 77.57241574300042, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 95911936, + "cpu_usage_usec": 5150215 + }, + "prowlarr": { + "memory_current_bytes": 143339520, + "cpu_usage_usec": 9736293 + }, + "qbittorrent": { + "memory_current_bytes": 14331904, + "cpu_usage_usec": 734395 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1639214 + } + } + }, + { + "elapsed_seconds": 77.67327929900057, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 95662080, + "cpu_usage_usec": 5150215 + }, + "prowlarr": { + "memory_current_bytes": 143339520, + "cpu_usage_usec": 9736293 + }, + "qbittorrent": { + "memory_current_bytes": 14254080, + "cpu_usage_usec": 734594 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1639214 + } + } + }, + { + "elapsed_seconds": 77.77378457500072, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 95494144, + "cpu_usage_usec": 5150215 + }, + "prowlarr": { + "memory_current_bytes": 143007744, + "cpu_usage_usec": 9736631 + }, + "qbittorrent": { + "memory_current_bytes": 14516224, + "cpu_usage_usec": 736066 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1639214 + } + } + }, + { + "elapsed_seconds": 77.87473200600016, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 95494144, + "cpu_usage_usec": 5150260 + }, + "prowlarr": { + "memory_current_bytes": 142856192, + "cpu_usage_usec": 9739819 + }, + "qbittorrent": { + "memory_current_bytes": 14516224, + "cpu_usage_usec": 736269 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1639214 + } + } + }, + { + "elapsed_seconds": 77.97558183399997, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 95494144, + "cpu_usage_usec": 5150308 + }, + "prowlarr": { + "memory_current_bytes": 142098432, + "cpu_usage_usec": 9739819 + }, + "qbittorrent": { + "memory_current_bytes": 14778368, + "cpu_usage_usec": 737609 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1639214 + } + } + }, + { + "elapsed_seconds": 78.07655941100074, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 95252480, + "cpu_usage_usec": 5150308 + }, + "prowlarr": { + "memory_current_bytes": 142098432, + "cpu_usage_usec": 9739819 + }, + "qbittorrent": { + "memory_current_bytes": 14835712, + "cpu_usage_usec": 738356 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1639214 + } + } + }, + { + "elapsed_seconds": 78.17739432000053, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 95252480, + "cpu_usage_usec": 5150308 + }, + "prowlarr": { + "memory_current_bytes": 142098432, + "cpu_usage_usec": 9739819 + }, + "qbittorrent": { + "memory_current_bytes": 14835712, + "cpu_usage_usec": 739864 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1639214 + } + } + }, + { + "elapsed_seconds": 78.27819407900006, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 95252480, + "cpu_usage_usec": 5150308 + }, + "prowlarr": { + "memory_current_bytes": 142069760, + "cpu_usage_usec": 9739819 + }, + "qbittorrent": { + "memory_current_bytes": 14835712, + "cpu_usage_usec": 741319 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1639214 + } + } + }, + { + "elapsed_seconds": 78.37901372200031, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 95252480, + "cpu_usage_usec": 5150308 + }, + "prowlarr": { + "memory_current_bytes": 142069760, + "cpu_usage_usec": 9741286 + }, + "qbittorrent": { + "memory_current_bytes": 14835712, + "cpu_usage_usec": 742381 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1639214 + } + } + }, + { + "elapsed_seconds": 78.47951898700012, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 95772672, + "cpu_usage_usec": 5173656 + }, + "prowlarr": { + "memory_current_bytes": 142073856, + "cpu_usage_usec": 9742070 + }, + "qbittorrent": { + "memory_current_bytes": 14835712, + "cpu_usage_usec": 742833 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1639214 + } + } + }, + { + "elapsed_seconds": 78.58040739600074, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 95756288, + "cpu_usage_usec": 5185194 + }, + "prowlarr": { + "memory_current_bytes": 142073856, + "cpu_usage_usec": 9742141 + }, + "qbittorrent": { + "memory_current_bytes": 14835712, + "cpu_usage_usec": 743601 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1639245 + } + } + }, + { + "elapsed_seconds": 78.6813092830007, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 95752192, + "cpu_usage_usec": 5185194 + }, + "prowlarr": { + "memory_current_bytes": 142073856, + "cpu_usage_usec": 9742360 + }, + "qbittorrent": { + "memory_current_bytes": 15097856, + "cpu_usage_usec": 744405 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1639245 + } + } + }, + { + "elapsed_seconds": 78.78224210500048, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 95752192, + "cpu_usage_usec": 5185194 + }, + "prowlarr": { + "memory_current_bytes": 142073856, + "cpu_usage_usec": 9742641 + }, + "qbittorrent": { + "memory_current_bytes": 14929920, + "cpu_usage_usec": 744947 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1639245 + } + } + }, + { + "elapsed_seconds": 78.8834896340004, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 95752192, + "cpu_usage_usec": 5185238 + }, + "prowlarr": { + "memory_current_bytes": 142073856, + "cpu_usage_usec": 9743019 + }, + "qbittorrent": { + "memory_current_bytes": 14901248, + "cpu_usage_usec": 745682 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1639245 + } + } + }, + { + "elapsed_seconds": 78.98438059399996, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 95494144, + "cpu_usage_usec": 5185287 + }, + "prowlarr": { + "memory_current_bytes": 141811712, + "cpu_usage_usec": 9743352 + }, + "qbittorrent": { + "memory_current_bytes": 15224832, + "cpu_usage_usec": 746402 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1639245 + } + } + }, + { + "elapsed_seconds": 79.08522291600002, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 95494144, + "cpu_usage_usec": 5185287 + }, + "prowlarr": { + "memory_current_bytes": 141750272, + "cpu_usage_usec": 9743352 + }, + "qbittorrent": { + "memory_current_bytes": 15224832, + "cpu_usage_usec": 747364 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1639245 + } + } + }, + { + "elapsed_seconds": 79.18628347000049, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 95494144, + "cpu_usage_usec": 5185287 + }, + "prowlarr": { + "memory_current_bytes": 141750272, + "cpu_usage_usec": 9743352 + }, + "qbittorrent": { + "memory_current_bytes": 15224832, + "cpu_usage_usec": 748305 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1639245 + } + } + }, + { + "elapsed_seconds": 79.28723805500067, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 95494144, + "cpu_usage_usec": 5185287 + }, + "prowlarr": { + "memory_current_bytes": 141750272, + "cpu_usage_usec": 9743352 + }, + "qbittorrent": { + "memory_current_bytes": 15224832, + "cpu_usage_usec": 749319 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1639245 + } + } + }, + { + "elapsed_seconds": 79.3877389170002, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 95490048, + "cpu_usage_usec": 5185287 + }, + "prowlarr": { + "memory_current_bytes": 141750272, + "cpu_usage_usec": 9743677 + }, + "qbittorrent": { + "memory_current_bytes": 14573568, + "cpu_usage_usec": 750181 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1639245 + } + } + }, + { + "elapsed_seconds": 79.48810474000038, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 95948800, + "cpu_usage_usec": 5205675 + }, + "prowlarr": { + "memory_current_bytes": 143179776, + "cpu_usage_usec": 9779204 + }, + "qbittorrent": { + "memory_current_bytes": 15626240, + "cpu_usage_usec": 752056 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1639245 + } + } + }, + { + "elapsed_seconds": 79.58859286700044, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 95948800, + "cpu_usage_usec": 5205675 + }, + "prowlarr": { + "memory_current_bytes": 143433728, + "cpu_usage_usec": 9842905 + }, + "qbittorrent": { + "memory_current_bytes": 18362368, + "cpu_usage_usec": 773980 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1639289 + } + } + }, + { + "elapsed_seconds": 79.68897946700054, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 95428608, + "cpu_usage_usec": 5205675 + }, + "prowlarr": { + "memory_current_bytes": 143384576, + "cpu_usage_usec": 9885123 + }, + "qbittorrent": { + "memory_current_bytes": 27885568, + "cpu_usage_usec": 829213 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1639289 + } + } + }, + { + "elapsed_seconds": 79.78959505400053, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 95428608, + "cpu_usage_usec": 5205675 + }, + "prowlarr": { + "memory_current_bytes": 143384576, + "cpu_usage_usec": 9885123 + }, + "qbittorrent": { + "memory_current_bytes": 34103296, + "cpu_usage_usec": 872723 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1639289 + } + } + }, + { + "elapsed_seconds": 79.89002400000027, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 95428608, + "cpu_usage_usec": 5205737 + }, + "prowlarr": { + "memory_current_bytes": 142458880, + "cpu_usage_usec": 9885169 + }, + "qbittorrent": { + "memory_current_bytes": 34099200, + "cpu_usage_usec": 884862 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1639289 + } + } + }, + { + "elapsed_seconds": 79.991269741, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 95428608, + "cpu_usage_usec": 5205788 + }, + "prowlarr": { + "memory_current_bytes": 142458880, + "cpu_usage_usec": 9885169 + }, + "qbittorrent": { + "memory_current_bytes": 33734656, + "cpu_usage_usec": 885672 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1639289 + } + } + }, + { + "elapsed_seconds": 80.09226032600054, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 95428608, + "cpu_usage_usec": 5205788 + }, + "prowlarr": { + "memory_current_bytes": 142200832, + "cpu_usage_usec": 9885169 + }, + "qbittorrent": { + "memory_current_bytes": 31911936, + "cpu_usage_usec": 886655 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1639289 + } + } + }, + { + "elapsed_seconds": 80.19312158299999, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 95420416, + "cpu_usage_usec": 5206018 + }, + "prowlarr": { + "memory_current_bytes": 142200832, + "cpu_usage_usec": 9885169 + }, + "qbittorrent": { + "memory_current_bytes": 31981568, + "cpu_usage_usec": 889011 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1639289 + } + } + }, + { + "elapsed_seconds": 80.29402445400046, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 95420416, + "cpu_usage_usec": 5206018 + }, + "prowlarr": { + "memory_current_bytes": 142200832, + "cpu_usage_usec": 9885169 + }, + "qbittorrent": { + "memory_current_bytes": 31981568, + "cpu_usage_usec": 889414 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1639289 + } + } + }, + { + "elapsed_seconds": 80.39500422600031, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 95420416, + "cpu_usage_usec": 5206018 + }, + "prowlarr": { + "memory_current_bytes": 142462976, + "cpu_usage_usec": 9888400 + }, + "qbittorrent": { + "memory_current_bytes": 32137216, + "cpu_usage_usec": 891653 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1639289 + } + } + }, + { + "elapsed_seconds": 80.4959417910004, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 95420416, + "cpu_usage_usec": 5206089 + }, + "prowlarr": { + "memory_current_bytes": 142462976, + "cpu_usage_usec": 9888400 + }, + "qbittorrent": { + "memory_current_bytes": 32137216, + "cpu_usage_usec": 891862 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1639289 + } + } + }, + { + "elapsed_seconds": 80.59635159000027, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 95420416, + "cpu_usage_usec": 5206089 + }, + "prowlarr": { + "memory_current_bytes": 142462976, + "cpu_usage_usec": 9888472 + }, + "qbittorrent": { + "memory_current_bytes": 32456704, + "cpu_usage_usec": 894475 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1639361 + } + } + }, + { + "elapsed_seconds": 80.69721946700065, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 95420416, + "cpu_usage_usec": 5206089 + }, + "prowlarr": { + "memory_current_bytes": 142462976, + "cpu_usage_usec": 9888472 + }, + "qbittorrent": { + "memory_current_bytes": 32649216, + "cpu_usage_usec": 897287 + }, + "flaresolverr": { + "memory_current_bytes": 76054528, + "cpu_usage_usec": 1639361 + } + } + }, + { + "elapsed_seconds": 80.79760395500034, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 6791168, + "cpu_usage_usec": 5260355 + }, + "prowlarr": { + "memory_current_bytes": 143106048, + "cpu_usage_usec": 9915917 + }, + "qbittorrent": { + "memory_current_bytes": 3514368, + "cpu_usage_usec": 939112 + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 80.89801279200037, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 6316032, + "cpu_usage_usec": 5274408 + }, + "prowlarr": { + "memory_current_bytes": 142512128, + "cpu_usage_usec": 9915945 + }, + "qbittorrent": { + "memory_current_bytes": 2555904, + "cpu_usage_usec": 939112 + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 80.99896406800053, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 6082560, + "cpu_usage_usec": 5274408 + }, + "prowlarr": { + "memory_current_bytes": 142512128, + "cpu_usage_usec": 9915945 + }, + "qbittorrent": { + "memory_current_bytes": 2555904, + "cpu_usage_usec": 939112 + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 81.09969954400003, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 5689344, + "cpu_usage_usec": 5274408 + }, + "prowlarr": { + "memory_current_bytes": 142512128, + "cpu_usage_usec": 9915945 + }, + "qbittorrent": { + "memory_current_bytes": 2555904, + "cpu_usage_usec": 939112 + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 81.20044125300046, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 5353472, + "cpu_usage_usec": 5274408 + }, + "prowlarr": { + "memory_current_bytes": 142512128, + "cpu_usage_usec": 9915945 + }, + "qbittorrent": { + "memory_current_bytes": 2555904, + "cpu_usage_usec": 939112 + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 81.30124717500075, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 5353472, + "cpu_usage_usec": 5274408 + }, + "prowlarr": { + "memory_current_bytes": 142512128, + "cpu_usage_usec": 9915979 + }, + "qbittorrent": { + "memory_current_bytes": 2555904, + "cpu_usage_usec": 939112 + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 81.40250588600065, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 5353472, + "cpu_usage_usec": 5274408 + }, + "prowlarr": { + "memory_current_bytes": 122990592, + "cpu_usage_usec": 9966826 + }, + "qbittorrent": { + "memory_current_bytes": 2555904, + "cpu_usage_usec": 939112 + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 81.5029139420003, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 5091328, + "cpu_usage_usec": 5274408 + }, + "prowlarr": { + "memory_current_bytes": 15499264, + "cpu_usage_usec": 10018911 + }, + "qbittorrent": { + "memory_current_bytes": 2555904, + "cpu_usage_usec": 939112 + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 81.60327495100046, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 5091328, + "cpu_usage_usec": 5274408 + }, + "prowlarr": { + "memory_current_bytes": 14065664, + "cpu_usage_usec": 10020911 + }, + "qbittorrent": { + "memory_current_bytes": 2555904, + "cpu_usage_usec": 939112 + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 81.70420145500066, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 5091328, + "cpu_usage_usec": 5274408 + }, + "prowlarr": { + "memory_current_bytes": 14065664, + "cpu_usage_usec": 10020911 + }, + "qbittorrent": { + "memory_current_bytes": 2555904, + "cpu_usage_usec": 939112 + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 81.80506463700021, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 5091328, + "cpu_usage_usec": 5274408 + }, + "prowlarr": { + "memory_current_bytes": 14065664, + "cpu_usage_usec": 10020911 + }, + "qbittorrent": { + "memory_current_bytes": 2555904, + "cpu_usage_usec": 939112 + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 81.90616261600007, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 5083136, + "cpu_usage_usec": 5274408 + }, + "prowlarr": { + "memory_current_bytes": 14065664, + "cpu_usage_usec": 10020911 + }, + "qbittorrent": { + "memory_current_bytes": 2555904, + "cpu_usage_usec": 939112 + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 82.00703975700071, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 5083136, + "cpu_usage_usec": 5274408 + }, + "prowlarr": { + "memory_current_bytes": 14065664, + "cpu_usage_usec": 10020911 + }, + "qbittorrent": { + "memory_current_bytes": 2555904, + "cpu_usage_usec": 939112 + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 82.1078152630007, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 5083136, + "cpu_usage_usec": 5274408 + }, + "prowlarr": { + "memory_current_bytes": 13860864, + "cpu_usage_usec": 10020911 + }, + "qbittorrent": { + "memory_current_bytes": 2555904, + "cpu_usage_usec": 939112 + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 82.20863916000053, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 5083136, + "cpu_usage_usec": 5274408 + }, + "prowlarr": { + "memory_current_bytes": 13852672, + "cpu_usage_usec": 10020911 + }, + "qbittorrent": { + "memory_current_bytes": 2555904, + "cpu_usage_usec": 939112 + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 82.30943368099997, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 5083136, + "cpu_usage_usec": 5274408 + }, + "prowlarr": { + "memory_current_bytes": 13430784, + "cpu_usage_usec": 10020911 + }, + "qbittorrent": { + "memory_current_bytes": 2555904, + "cpu_usage_usec": 939112 + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 82.410213354, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 5083136, + "cpu_usage_usec": 5274408 + }, + "prowlarr": { + "memory_current_bytes": 13430784, + "cpu_usage_usec": 10020911 + }, + "qbittorrent": { + "memory_current_bytes": 2555904, + "cpu_usage_usec": 939112 + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 82.51107279600001, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 5083136, + "cpu_usage_usec": 5274408 + }, + "prowlarr": { + "memory_current_bytes": 13238272, + "cpu_usage_usec": 10020911 + }, + "qbittorrent": { + "memory_current_bytes": 2555904, + "cpu_usage_usec": 939112 + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 82.61183265599993, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 5083136, + "cpu_usage_usec": 5274408 + }, + "prowlarr": { + "memory_current_bytes": 13172736, + "cpu_usage_usec": 10020911 + }, + "qbittorrent": { + "memory_current_bytes": 2555904, + "cpu_usage_usec": 939112 + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 82.71265802900052, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 5083136, + "cpu_usage_usec": 5274408 + }, + "prowlarr": { + "memory_current_bytes": 13172736, + "cpu_usage_usec": 10020911 + }, + "qbittorrent": { + "memory_current_bytes": 2547712, + "cpu_usage_usec": 939112 + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 82.81354867500067, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 5083136, + "cpu_usage_usec": 5274408 + }, + "prowlarr": { + "memory_current_bytes": 13172736, + "cpu_usage_usec": 10020911 + }, + "qbittorrent": { + "memory_current_bytes": 2547712, + "cpu_usage_usec": 939112 + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 82.91429054200034, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 5083136, + "cpu_usage_usec": 5274408 + }, + "prowlarr": { + "memory_current_bytes": 13172736, + "cpu_usage_usec": 10020911 + }, + "qbittorrent": { + "memory_current_bytes": 2547712, + "cpu_usage_usec": 939112 + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 83.01503099199999, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 5083136, + "cpu_usage_usec": 5274408 + }, + "prowlarr": { + "memory_current_bytes": 13172736, + "cpu_usage_usec": 10020911 + }, + "qbittorrent": { + "memory_current_bytes": 2547712, + "cpu_usage_usec": 939112 + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 83.1159091160007, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 5083136, + "cpu_usage_usec": 5274408 + }, + "prowlarr": { + "memory_current_bytes": 12914688, + "cpu_usage_usec": 10020911 + }, + "qbittorrent": { + "memory_current_bytes": 2547712, + "cpu_usage_usec": 939112 + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 83.21668579300058, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 5083136, + "cpu_usage_usec": 5274408 + }, + "prowlarr": { + "memory_current_bytes": 12914688, + "cpu_usage_usec": 10020911 + }, + "qbittorrent": { + "memory_current_bytes": 2547712, + "cpu_usage_usec": 939112 + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 83.3172391930002, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 5083136, + "cpu_usage_usec": 5274408 + }, + "prowlarr": { + "memory_current_bytes": 12914688, + "cpu_usage_usec": 10020911 + }, + "qbittorrent": { + "memory_current_bytes": 2547712, + "cpu_usage_usec": 939112 + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 83.41839940600039, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 5083136, + "cpu_usage_usec": 5274408 + }, + "prowlarr": { + "memory_current_bytes": 12914688, + "cpu_usage_usec": 10020911 + }, + "qbittorrent": { + "memory_current_bytes": 2547712, + "cpu_usage_usec": 939112 + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 83.51918641500015, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 5083136, + "cpu_usage_usec": 5274408 + }, + "prowlarr": { + "memory_current_bytes": 12914688, + "cpu_usage_usec": 10020911 + }, + "qbittorrent": { + "memory_current_bytes": 2547712, + "cpu_usage_usec": 939112 + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 83.61996246800027, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 5083136, + "cpu_usage_usec": 5274408 + }, + "prowlarr": { + "memory_current_bytes": 12914688, + "cpu_usage_usec": 10020911 + }, + "qbittorrent": { + "memory_current_bytes": 2547712, + "cpu_usage_usec": 939112 + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 83.72068343499996, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 5083136, + "cpu_usage_usec": 5274408 + }, + "prowlarr": { + "memory_current_bytes": 12795904, + "cpu_usage_usec": 10020911 + }, + "qbittorrent": { + "memory_current_bytes": 2547712, + "cpu_usage_usec": 939112 + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 83.82111997900029, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 5083136, + "cpu_usage_usec": 5274408 + }, + "prowlarr": { + "memory_current_bytes": 12570624, + "cpu_usage_usec": 10020911 + }, + "qbittorrent": { + "unavailable": true + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 83.92145201400035, + "phase": "teardown", + "services": { + "jackett": { + "unavailable": true + }, + "prowlarr": { + "memory_current_bytes": 12570624, + "cpu_usage_usec": 10020911 + }, + "qbittorrent": { + "unavailable": true + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 84.02218094399996, + "phase": "teardown", + "services": { + "jackett": { + "unavailable": true + }, + "prowlarr": { + "memory_current_bytes": 12570624, + "cpu_usage_usec": 10020911 + }, + "qbittorrent": { + "unavailable": true + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 84.12251656700028, + "phase": "teardown", + "services": { + "jackett": { + "unavailable": true + }, + "prowlarr": { + "memory_current_bytes": 12570624, + "cpu_usage_usec": 10020911 + }, + "qbittorrent": { + "unavailable": true + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 84.22331891200065, + "phase": "teardown", + "services": { + "jackett": { + "unavailable": true + }, + "prowlarr": { + "memory_current_bytes": 12570624, + "cpu_usage_usec": 10020911 + }, + "qbittorrent": { + "unavailable": true + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 84.32374573900051, + "phase": "teardown", + "services": { + "jackett": { + "unavailable": true + }, + "prowlarr": { + "memory_current_bytes": 12570624, + "cpu_usage_usec": 10020911 + }, + "qbittorrent": { + "unavailable": true + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 84.42407295900011, + "phase": "teardown", + "services": { + "jackett": { + "unavailable": true + }, + "prowlarr": { + "memory_current_bytes": 12570624, + "cpu_usage_usec": 10020911 + }, + "qbittorrent": { + "unavailable": true + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 84.52434976800032, + "phase": "teardown", + "services": { + "jackett": { + "unavailable": true + }, + "prowlarr": { + "unavailable": true + }, + "qbittorrent": { + "unavailable": true + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 84.62455585600037, + "phase": "teardown", + "services": { + "jackett": { + "unavailable": true + }, + "prowlarr": { + "unavailable": true + }, + "qbittorrent": { + "unavailable": true + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 84.72497296500023, + "phase": "teardown", + "services": { + "jackett": { + "unavailable": true + }, + "prowlarr": { + "unavailable": true + }, + "qbittorrent": { + "unavailable": true + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 84.82541707500059, + "phase": "teardown", + "services": { + "jackett": { + "unavailable": true + }, + "prowlarr": { + "unavailable": true + }, + "qbittorrent": { + "unavailable": true + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 84.92592266000065, + "phase": "teardown", + "services": { + "jackett": { + "unavailable": true + }, + "prowlarr": { + "unavailable": true + }, + "qbittorrent": { + "unavailable": true + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 85.02618736100067, + "phase": "teardown", + "services": { + "jackett": { + "unavailable": true + }, + "prowlarr": { + "unavailable": true + }, + "qbittorrent": { + "unavailable": true + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 85.12648105100016, + "phase": "teardown", + "services": { + "jackett": { + "unavailable": true + }, + "prowlarr": { + "unavailable": true + }, + "qbittorrent": { + "unavailable": true + }, + "flaresolverr": { + "unavailable": true + } + } + } + ], + "trials": [ + { + "search_requests": 5, + "search_seconds": 24.39684659700015, + "download_seconds": 2.0683495019993643, + "payload_bytes": 16777216, + "sha256": "341aacac661ccb210720bedaa9ead5d668fe5ea41a73532fc147c71e34040df1" + }, + { + "search_requests": 5, + "search_seconds": 15.827975221999623, + "download_seconds": 1.0480724819999523, + "payload_bytes": 16777216, + "sha256": "341aacac661ccb210720bedaa9ead5d668fe5ea41a73532fc147c71e34040df1" + }, + { + "search_requests": 5, + "search_seconds": 11.20846798599996, + "download_seconds": 1.2422488199999862, + "payload_bytes": 16777216, + "sha256": "341aacac661ccb210720bedaa9ead5d668fe5ea41a73532fc147c71e34040df1" + } + ], + "metric": "memory.current bytes and cpu.stat usage_usec per cgroup; do not add to host PSS", + "errors": [], + "project": "helm-bench-0e14c39d86", + "limits": { + "jackett": { + "memory_max": "268435456", + "cpu_max": "50000 100000", + "verified": true + }, + "prowlarr": { + "memory_max": "268435456", + "cpu_max": "50000 100000", + "verified": true + }, + "qbittorrent": { + "memory_max": "268435456", + "cpu_max": "50000 100000", + "verified": true + }, + "flaresolverr": { + "memory_max": "536870912", + "cpu_max": "50000 100000", + "verified": true + } + }, + "metadata": { + "engine": "docker", + "version": "29.8.2", + "project": "helm-bench-0e14c39d86", + "containers": [ + { + "id": "087fef62e1b6555fef2b1c1d1663d7341ddf13f5b870d64414512f8192662745", + "pid": 209311, + "image_id": "sha256:894893ed4d4557764df3e74d27c5bc1b3944e5a33ed410e62ab7c744b348f415", + "image": "sha256:894893ed4d4557764df3e74d27c5bc1b3944e5a33ed410e62ab7c744b348f415", + "memory_limit_bytes": 536870912, + "nano_cpus": 500000000, + "name": "/helm-bench-0e14c39d86-flaresolverr" + }, + { + "id": "c2a838e4363042167df602c8e9aee9eb3fdaa81c904f2f292c21547398823c90", + "pid": 209063, + "image_id": "sha256:66af76dac14d022d43e060ee2970bf149309b463346c45a37fa844a6265bcdc0", + "image": "sha256:66af76dac14d022d43e060ee2970bf149309b463346c45a37fa844a6265bcdc0", + "memory_limit_bytes": 268435456, + "nano_cpus": 500000000, + "name": "/helm-bench-0e14c39d86-qbittorrent" + }, + { + "id": "fab54ac3a6371013d1745af70d0450fee7bd48a3fed29e2af73ec1d074ebc550", + "pid": 208787, + "image_id": "sha256:48cd1d7e2a8b73178829c03e0606b8c820d067d6f7d7d92328573eb311e3e521", + "image": "sha256:48cd1d7e2a8b73178829c03e0606b8c820d067d6f7d7d92328573eb311e3e521", + "memory_limit_bytes": 268435456, + "nano_cpus": 500000000, + "name": "/helm-bench-0e14c39d86-prowlarr" + }, + { + "id": "4c89ff04625b898d4e3fbed477b5108067db0cf7b3d2b2ac23bd70c801744ee5", + "pid": 208601, + "image_id": "sha256:d39ca96018ff40dc20730d80f96195a784ec71b1fb647b86a6db1d01431c85c5", + "image": "sha256:d39ca96018ff40dc20730d80f96195a784ec71b1fb647b86a6db1d01431c85c5", + "memory_limit_bytes": 268435456, + "nano_cpus": 500000000, + "name": "/helm-bench-0e14c39d86-jackett" + } + ], + "attachment": "read_only; local workload does not exercise these services" + }, + "all_containers_stopped": true, + "success": true, + "cleanup_errors": [] +} diff --git a/docs/benchmarks/stack-podman.json b/docs/benchmarks/stack-podman.json new file mode 100644 index 0000000..e0b7adc --- /dev/null +++ b/docs/benchmarks/stack-podman.json @@ -0,0 +1,8237 @@ +{ + "engine": "podman", + "samples": [ + { + "elapsed_seconds": 14.075876862000769, + "phase": "idle", + "services": { + "jackett": { + "memory_current_bytes": 83906560, + "cpu_usage_usec": 3683860 + }, + "prowlarr": { + "memory_current_bytes": 114061312, + "cpu_usage_usec": 5172608 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 362152 + }, + "flaresolverr": { + "memory_current_bytes": 90542080, + "cpu_usage_usec": 2222362 + } + } + }, + { + "elapsed_seconds": 14.176883280000766, + "phase": "idle", + "services": { + "jackett": { + "memory_current_bytes": 83484672, + "cpu_usage_usec": 3683908 + }, + "prowlarr": { + "memory_current_bytes": 114061312, + "cpu_usage_usec": 5174385 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 362152 + }, + "flaresolverr": { + "memory_current_bytes": 90542080, + "cpu_usage_usec": 2222421 + } + } + }, + { + "elapsed_seconds": 14.277899170000637, + "phase": "idle", + "services": { + "jackett": { + "memory_current_bytes": 83484672, + "cpu_usage_usec": 3684036 + }, + "prowlarr": { + "memory_current_bytes": 114061312, + "cpu_usage_usec": 5174385 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 362189 + }, + "flaresolverr": { + "memory_current_bytes": 90542080, + "cpu_usage_usec": 2222421 + } + } + }, + { + "elapsed_seconds": 14.378817878000518, + "phase": "idle", + "services": { + "jackett": { + "memory_current_bytes": 83263488, + "cpu_usage_usec": 3684036 + }, + "prowlarr": { + "memory_current_bytes": 113848320, + "cpu_usage_usec": 5174385 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 362189 + }, + "flaresolverr": { + "memory_current_bytes": 90542080, + "cpu_usage_usec": 2222421 + } + } + }, + { + "elapsed_seconds": 14.479847841000264, + "phase": "idle", + "services": { + "jackett": { + "memory_current_bytes": 83263488, + "cpu_usage_usec": 3684036 + }, + "prowlarr": { + "memory_current_bytes": 113840128, + "cpu_usage_usec": 5174779 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 362399 + }, + "flaresolverr": { + "memory_current_bytes": 90542080, + "cpu_usage_usec": 2222421 + } + } + }, + { + "elapsed_seconds": 14.580783492000592, + "phase": "idle", + "services": { + "jackett": { + "memory_current_bytes": 83263488, + "cpu_usage_usec": 3684114 + }, + "prowlarr": { + "memory_current_bytes": 113840128, + "cpu_usage_usec": 5174804 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 362399 + }, + "flaresolverr": { + "memory_current_bytes": 90542080, + "cpu_usage_usec": 2222421 + } + } + }, + { + "elapsed_seconds": 14.681628975000422, + "phase": "idle", + "services": { + "jackett": { + "memory_current_bytes": 83263488, + "cpu_usage_usec": 3684114 + }, + "prowlarr": { + "memory_current_bytes": 113840128, + "cpu_usage_usec": 5174804 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 362399 + }, + "flaresolverr": { + "memory_current_bytes": 90542080, + "cpu_usage_usec": 2222421 + } + } + }, + { + "elapsed_seconds": 14.78252305100068, + "phase": "idle", + "services": { + "jackett": { + "memory_current_bytes": 83263488, + "cpu_usage_usec": 3684114 + }, + "prowlarr": { + "memory_current_bytes": 113840128, + "cpu_usage_usec": 5174891 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 362432 + }, + "flaresolverr": { + "memory_current_bytes": 90542080, + "cpu_usage_usec": 2222421 + } + } + }, + { + "elapsed_seconds": 14.883510032000231, + "phase": "idle", + "services": { + "jackett": { + "memory_current_bytes": 83263488, + "cpu_usage_usec": 3684114 + }, + "prowlarr": { + "memory_current_bytes": 113840128, + "cpu_usage_usec": 5174891 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 362477 + }, + "flaresolverr": { + "memory_current_bytes": 90542080, + "cpu_usage_usec": 2222421 + } + } + }, + { + "elapsed_seconds": 14.984422098000323, + "phase": "idle", + "services": { + "jackett": { + "memory_current_bytes": 83263488, + "cpu_usage_usec": 3684114 + }, + "prowlarr": { + "memory_current_bytes": 113545216, + "cpu_usage_usec": 5174941 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 362477 + }, + "flaresolverr": { + "memory_current_bytes": 90542080, + "cpu_usage_usec": 2222421 + } + } + }, + { + "elapsed_seconds": 15.08563790900007, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 83259392, + "cpu_usage_usec": 3684179 + }, + "prowlarr": { + "memory_current_bytes": 114057216, + "cpu_usage_usec": 5181626 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 362477 + }, + "flaresolverr": { + "memory_current_bytes": 90542080, + "cpu_usage_usec": 2222421 + } + } + }, + { + "elapsed_seconds": 15.18607016200076, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 83779584, + "cpu_usage_usec": 3687205 + }, + "prowlarr": { + "memory_current_bytes": 114671616, + "cpu_usage_usec": 5244496 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 362477 + }, + "flaresolverr": { + "memory_current_bytes": 90542080, + "cpu_usage_usec": 2222442 + } + } + }, + { + "elapsed_seconds": 15.286478482000348, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 83779584, + "cpu_usage_usec": 3687283 + }, + "prowlarr": { + "memory_current_bytes": 114499584, + "cpu_usage_usec": 5244496 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 362497 + }, + "flaresolverr": { + "memory_current_bytes": 90542080, + "cpu_usage_usec": 2222442 + } + } + }, + { + "elapsed_seconds": 15.387328948000686, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 83775488, + "cpu_usage_usec": 3687283 + }, + "prowlarr": { + "memory_current_bytes": 114233344, + "cpu_usage_usec": 5244496 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 362497 + }, + "flaresolverr": { + "memory_current_bytes": 90542080, + "cpu_usage_usec": 2222442 + } + } + }, + { + "elapsed_seconds": 15.488263070000357, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 83775488, + "cpu_usage_usec": 3687283 + }, + "prowlarr": { + "memory_current_bytes": 113979392, + "cpu_usage_usec": 5245079 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 362497 + }, + "flaresolverr": { + "memory_current_bytes": 90542080, + "cpu_usage_usec": 2222442 + } + } + }, + { + "elapsed_seconds": 15.588787163000234, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 84369408, + "cpu_usage_usec": 3735201 + }, + "prowlarr": { + "memory_current_bytes": 113942528, + "cpu_usage_usec": 5245146 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 362497 + }, + "flaresolverr": { + "memory_current_bytes": 90542080, + "cpu_usage_usec": 2222442 + } + } + }, + { + "elapsed_seconds": 15.689228252000248, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 85213184, + "cpu_usage_usec": 3747455 + }, + "prowlarr": { + "memory_current_bytes": 114847744, + "cpu_usage_usec": 5289195 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 362530 + }, + "flaresolverr": { + "memory_current_bytes": 90542080, + "cpu_usage_usec": 2222442 + } + } + }, + { + "elapsed_seconds": 15.789992740000343, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 85200896, + "cpu_usage_usec": 3747455 + }, + "prowlarr": { + "memory_current_bytes": 115605504, + "cpu_usage_usec": 5296689 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 362548 + }, + "flaresolverr": { + "memory_current_bytes": 90542080, + "cpu_usage_usec": 2222442 + } + } + }, + { + "elapsed_seconds": 15.890993089000403, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 85200896, + "cpu_usage_usec": 3747455 + }, + "prowlarr": { + "memory_current_bytes": 115605504, + "cpu_usage_usec": 5296921 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 362615 + }, + "flaresolverr": { + "memory_current_bytes": 90542080, + "cpu_usage_usec": 2222442 + } + } + }, + { + "elapsed_seconds": 15.99192387200037, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 84684800, + "cpu_usage_usec": 3747455 + }, + "prowlarr": { + "memory_current_bytes": 115453952, + "cpu_usage_usec": 5296921 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 362615 + }, + "flaresolverr": { + "memory_current_bytes": 90542080, + "cpu_usage_usec": 2222442 + } + } + }, + { + "elapsed_seconds": 16.09284444000059, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 84529152, + "cpu_usage_usec": 3747489 + }, + "prowlarr": { + "memory_current_bytes": 114937856, + "cpu_usage_usec": 5296971 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 362615 + }, + "flaresolverr": { + "memory_current_bytes": 90542080, + "cpu_usage_usec": 2222442 + } + } + }, + { + "elapsed_seconds": 16.193755066999984, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 84529152, + "cpu_usage_usec": 3747553 + }, + "prowlarr": { + "memory_current_bytes": 114462720, + "cpu_usage_usec": 5298884 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 362615 + }, + "flaresolverr": { + "memory_current_bytes": 90542080, + "cpu_usage_usec": 2222514 + } + } + }, + { + "elapsed_seconds": 16.294214432000445, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 84529152, + "cpu_usage_usec": 3747673 + }, + "prowlarr": { + "memory_current_bytes": 114462720, + "cpu_usage_usec": 5298884 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 362658 + }, + "flaresolverr": { + "memory_current_bytes": 90542080, + "cpu_usage_usec": 2222514 + } + } + }, + { + "elapsed_seconds": 16.39470213000004, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 84529152, + "cpu_usage_usec": 3747673 + }, + "prowlarr": { + "memory_current_bytes": 114462720, + "cpu_usage_usec": 5298884 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 362658 + }, + "flaresolverr": { + "memory_current_bytes": 90542080, + "cpu_usage_usec": 2222514 + } + } + }, + { + "elapsed_seconds": 16.495267728000726, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 84529152, + "cpu_usage_usec": 3747673 + }, + "prowlarr": { + "memory_current_bytes": 114462720, + "cpu_usage_usec": 5299202 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 362658 + }, + "flaresolverr": { + "memory_current_bytes": 90542080, + "cpu_usage_usec": 2222514 + } + } + }, + { + "elapsed_seconds": 16.595857676999913, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 84291584, + "cpu_usage_usec": 3747692 + }, + "prowlarr": { + "memory_current_bytes": 114462720, + "cpu_usage_usec": 5299272 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 362658 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222514 + } + } + }, + { + "elapsed_seconds": 16.696415193000576, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 84291584, + "cpu_usage_usec": 3747692 + }, + "prowlarr": { + "memory_current_bytes": 114462720, + "cpu_usage_usec": 5299564 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 362679 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222514 + } + } + }, + { + "elapsed_seconds": 16.796863629000654, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 84291584, + "cpu_usage_usec": 3747692 + }, + "prowlarr": { + "memory_current_bytes": 114462720, + "cpu_usage_usec": 5299630 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 362679 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222514 + } + } + }, + { + "elapsed_seconds": 16.897279187000095, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 84291584, + "cpu_usage_usec": 3747692 + }, + "prowlarr": { + "memory_current_bytes": 114462720, + "cpu_usage_usec": 5299774 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 362700 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222514 + } + } + }, + { + "elapsed_seconds": 16.997703245000594, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 84291584, + "cpu_usage_usec": 3747692 + }, + "prowlarr": { + "memory_current_bytes": 114462720, + "cpu_usage_usec": 5299774 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 362700 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222514 + } + } + }, + { + "elapsed_seconds": 17.098184655000296, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 84291584, + "cpu_usage_usec": 3747692 + }, + "prowlarr": { + "memory_current_bytes": 114462720, + "cpu_usage_usec": 5299809 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 362700 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222514 + } + } + }, + { + "elapsed_seconds": 17.1986218130005, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 84291584, + "cpu_usage_usec": 3747692 + }, + "prowlarr": { + "memory_current_bytes": 114462720, + "cpu_usage_usec": 5299809 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 362986 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222564 + } + } + }, + { + "elapsed_seconds": 17.29917556000055, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 84291584, + "cpu_usage_usec": 3747769 + }, + "prowlarr": { + "memory_current_bytes": 114462720, + "cpu_usage_usec": 5299809 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 362986 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222564 + } + } + }, + { + "elapsed_seconds": 17.39959283100052, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 84291584, + "cpu_usage_usec": 3747769 + }, + "prowlarr": { + "memory_current_bytes": 114462720, + "cpu_usage_usec": 5299809 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 363058 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222564 + } + } + }, + { + "elapsed_seconds": 17.499997635, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 84291584, + "cpu_usage_usec": 3747769 + }, + "prowlarr": { + "memory_current_bytes": 114462720, + "cpu_usage_usec": 5300008 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 363058 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222564 + } + } + }, + { + "elapsed_seconds": 17.600490350000655, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 82698240, + "cpu_usage_usec": 3761842 + }, + "prowlarr": { + "memory_current_bytes": 118206464, + "cpu_usage_usec": 5319438 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 363058 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222564 + } + } + }, + { + "elapsed_seconds": 17.70198074400014, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 83165184, + "cpu_usage_usec": 3831931 + }, + "prowlarr": { + "memory_current_bytes": 118509568, + "cpu_usage_usec": 5348148 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 363086 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222564 + } + } + }, + { + "elapsed_seconds": 17.802604814000006, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 83759104, + "cpu_usage_usec": 3884961 + }, + "prowlarr": { + "memory_current_bytes": 118509568, + "cpu_usage_usec": 5348434 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 363086 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222564 + } + } + }, + { + "elapsed_seconds": 17.903034523000315, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 85114880, + "cpu_usage_usec": 3935836 + }, + "prowlarr": { + "memory_current_bytes": 118509568, + "cpu_usage_usec": 5348434 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 363086 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222564 + } + } + }, + { + "elapsed_seconds": 18.003444065000622, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 85630976, + "cpu_usage_usec": 3986676 + }, + "prowlarr": { + "memory_current_bytes": 118480896, + "cpu_usage_usec": 5348434 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 363086 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222564 + } + } + }, + { + "elapsed_seconds": 18.103877450000255, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 85536768, + "cpu_usage_usec": 4036896 + }, + "prowlarr": { + "memory_current_bytes": 117854208, + "cpu_usage_usec": 5348484 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 363086 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222564 + } + } + }, + { + "elapsed_seconds": 18.204306682000606, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 85602304, + "cpu_usage_usec": 4085890 + }, + "prowlarr": { + "memory_current_bytes": 117850112, + "cpu_usage_usec": 5349781 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 363112 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222616 + } + } + }, + { + "elapsed_seconds": 18.304974055999992, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 85852160, + "cpu_usage_usec": 4137306 + }, + "prowlarr": { + "memory_current_bytes": 117850112, + "cpu_usage_usec": 5349781 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 363112 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222616 + } + } + }, + { + "elapsed_seconds": 18.40565629000048, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 88850432, + "cpu_usage_usec": 4187465 + }, + "prowlarr": { + "memory_current_bytes": 117813248, + "cpu_usage_usec": 5349781 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 363112 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222616 + } + } + }, + { + "elapsed_seconds": 18.506185955000547, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 89169920, + "cpu_usage_usec": 4205257 + }, + "prowlarr": { + "memory_current_bytes": 117813248, + "cpu_usage_usec": 5350161 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 363112 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222616 + } + } + }, + { + "elapsed_seconds": 18.606608153000707, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 88985600, + "cpu_usage_usec": 4205293 + }, + "prowlarr": { + "memory_current_bytes": 117813248, + "cpu_usage_usec": 5350206 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 363112 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222616 + } + } + }, + { + "elapsed_seconds": 18.707029320999936, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 88981504, + "cpu_usage_usec": 4205293 + }, + "prowlarr": { + "memory_current_bytes": 117813248, + "cpu_usage_usec": 5350428 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 363130 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222616 + } + } + }, + { + "elapsed_seconds": 18.807565758000237, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 88981504, + "cpu_usage_usec": 4205293 + }, + "prowlarr": { + "memory_current_bytes": 117813248, + "cpu_usage_usec": 5350597 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 363130 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222616 + } + } + }, + { + "elapsed_seconds": 18.908115533000455, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 88981504, + "cpu_usage_usec": 4205293 + }, + "prowlarr": { + "memory_current_bytes": 117813248, + "cpu_usage_usec": 5350597 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 363213 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222616 + } + } + }, + { + "elapsed_seconds": 19.00855292000051, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 88981504, + "cpu_usage_usec": 4205293 + }, + "prowlarr": { + "memory_current_bytes": 117813248, + "cpu_usage_usec": 5350597 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 363254 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222616 + } + } + }, + { + "elapsed_seconds": 19.108961346000797, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 88981504, + "cpu_usage_usec": 4205293 + }, + "prowlarr": { + "memory_current_bytes": 118005760, + "cpu_usage_usec": 5356568 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 363254 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222616 + } + } + }, + { + "elapsed_seconds": 19.20941553600005, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 88981504, + "cpu_usage_usec": 4205293 + }, + "prowlarr": { + "memory_current_bytes": 118267904, + "cpu_usage_usec": 5358711 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 363271 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222658 + } + } + }, + { + "elapsed_seconds": 19.30988053600049, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 88981504, + "cpu_usage_usec": 4205888 + }, + "prowlarr": { + "memory_current_bytes": 118247424, + "cpu_usage_usec": 5358711 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 363271 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222658 + } + } + }, + { + "elapsed_seconds": 19.410318567000104, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 88981504, + "cpu_usage_usec": 4205888 + }, + "prowlarr": { + "memory_current_bytes": 118247424, + "cpu_usage_usec": 5358711 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 363271 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222658 + } + } + }, + { + "elapsed_seconds": 19.51075345300069, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 88981504, + "cpu_usage_usec": 4205888 + }, + "prowlarr": { + "memory_current_bytes": 118247424, + "cpu_usage_usec": 5359016 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 363271 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222658 + } + } + }, + { + "elapsed_seconds": 19.611210949999986, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 89497600, + "cpu_usage_usec": 4212882 + }, + "prowlarr": { + "memory_current_bytes": 117940224, + "cpu_usage_usec": 5371487 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 363271 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222658 + } + } + }, + { + "elapsed_seconds": 19.711640086000443, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 89497600, + "cpu_usage_usec": 4212882 + }, + "prowlarr": { + "memory_current_bytes": 117940224, + "cpu_usage_usec": 5371559 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 363289 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222658 + } + } + }, + { + "elapsed_seconds": 19.81204165300005, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 89493504, + "cpu_usage_usec": 4212882 + }, + "prowlarr": { + "memory_current_bytes": 117747712, + "cpu_usage_usec": 5371797 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 363289 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222658 + } + } + }, + { + "elapsed_seconds": 19.912441753000166, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 89489408, + "cpu_usage_usec": 4212882 + }, + "prowlarr": { + "memory_current_bytes": 117710848, + "cpu_usage_usec": 5371797 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 363289 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222658 + } + } + }, + { + "elapsed_seconds": 20.012858791000326, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 89489408, + "cpu_usage_usec": 4212882 + }, + "prowlarr": { + "memory_current_bytes": 117710848, + "cpu_usage_usec": 5371797 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 363289 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222658 + } + } + }, + { + "elapsed_seconds": 20.113274183000613, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 88989696, + "cpu_usage_usec": 4212915 + }, + "prowlarr": { + "memory_current_bytes": 117972992, + "cpu_usage_usec": 5372581 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 363289 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222658 + } + } + }, + { + "elapsed_seconds": 20.213836495000578, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 88989696, + "cpu_usage_usec": 4212915 + }, + "prowlarr": { + "memory_current_bytes": 117972992, + "cpu_usage_usec": 5372689 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 363317 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222692 + } + } + }, + { + "elapsed_seconds": 20.31424877400059, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 88989696, + "cpu_usage_usec": 4212995 + }, + "prowlarr": { + "memory_current_bytes": 117972992, + "cpu_usage_usec": 5372689 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 363317 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222692 + } + } + }, + { + "elapsed_seconds": 20.414817636999942, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 88989696, + "cpu_usage_usec": 4212995 + }, + "prowlarr": { + "memory_current_bytes": 117972992, + "cpu_usage_usec": 5372689 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 363393 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222692 + } + } + }, + { + "elapsed_seconds": 20.51525206400038, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 88756224, + "cpu_usage_usec": 4212995 + }, + "prowlarr": { + "memory_current_bytes": 117755904, + "cpu_usage_usec": 5372998 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 363393 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222692 + } + } + }, + { + "elapsed_seconds": 20.615727254000376, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 88756224, + "cpu_usage_usec": 4213035 + }, + "prowlarr": { + "memory_current_bytes": 118325248, + "cpu_usage_usec": 5387887 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 363393 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222692 + } + } + }, + { + "elapsed_seconds": 20.71615270300026, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 88756224, + "cpu_usage_usec": 4213035 + }, + "prowlarr": { + "memory_current_bytes": 118419456, + "cpu_usage_usec": 5455785 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 363464 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222692 + } + } + }, + { + "elapsed_seconds": 20.81660797099994, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 88756224, + "cpu_usage_usec": 4213035 + }, + "prowlarr": { + "memory_current_bytes": 118730752, + "cpu_usage_usec": 5505460 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 363464 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222692 + } + } + }, + { + "elapsed_seconds": 20.91715949600075, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 88756224, + "cpu_usage_usec": 4213035 + }, + "prowlarr": { + "memory_current_bytes": 120606720, + "cpu_usage_usec": 5556086 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 363490 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222692 + } + } + }, + { + "elapsed_seconds": 21.017644389000452, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 88756224, + "cpu_usage_usec": 4213035 + }, + "prowlarr": { + "memory_current_bytes": 121593856, + "cpu_usage_usec": 5606707 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 363535 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222692 + } + } + }, + { + "elapsed_seconds": 21.118060581000464, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 88756224, + "cpu_usage_usec": 4213035 + }, + "prowlarr": { + "memory_current_bytes": 122089472, + "cpu_usage_usec": 5655595 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 363535 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222692 + } + } + }, + { + "elapsed_seconds": 21.218983118000324, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 88756224, + "cpu_usage_usec": 4213035 + }, + "prowlarr": { + "memory_current_bytes": 122548224, + "cpu_usage_usec": 5705796 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 363548 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222722 + } + } + }, + { + "elapsed_seconds": 21.31991160800044, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 88756224, + "cpu_usage_usec": 4213132 + }, + "prowlarr": { + "memory_current_bytes": 122515456, + "cpu_usage_usec": 5744590 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 363548 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222722 + } + } + }, + { + "elapsed_seconds": 21.420351382000263, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 88756224, + "cpu_usage_usec": 4213132 + }, + "prowlarr": { + "memory_current_bytes": 122515456, + "cpu_usage_usec": 5744590 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 363548 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222722 + } + } + }, + { + "elapsed_seconds": 21.521262616000058, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 88756224, + "cpu_usage_usec": 4213132 + }, + "prowlarr": { + "memory_current_bytes": 122777600, + "cpu_usage_usec": 5745276 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 363548 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222722 + } + } + }, + { + "elapsed_seconds": 21.62221700000009, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 89018368, + "cpu_usage_usec": 4213511 + }, + "prowlarr": { + "memory_current_bytes": 122777600, + "cpu_usage_usec": 5746891 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 363548 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222722 + } + } + }, + { + "elapsed_seconds": 21.723150580000038, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 89018368, + "cpu_usage_usec": 4213511 + }, + "prowlarr": { + "memory_current_bytes": 122777600, + "cpu_usage_usec": 5747045 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 363592 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222722 + } + } + }, + { + "elapsed_seconds": 21.823600308000096, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 89018368, + "cpu_usage_usec": 4213511 + }, + "prowlarr": { + "memory_current_bytes": 122748928, + "cpu_usage_usec": 5747212 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 363592 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222722 + } + } + }, + { + "elapsed_seconds": 21.923998539999957, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 89018368, + "cpu_usage_usec": 4213511 + }, + "prowlarr": { + "memory_current_bytes": 122380288, + "cpu_usage_usec": 5747212 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 363670 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222722 + } + } + }, + { + "elapsed_seconds": 22.024417433000053, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 88760320, + "cpu_usage_usec": 4213511 + }, + "prowlarr": { + "memory_current_bytes": 122380288, + "cpu_usage_usec": 5747212 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 363670 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222722 + } + } + }, + { + "elapsed_seconds": 22.124876974000472, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 88760320, + "cpu_usage_usec": 4213544 + }, + "prowlarr": { + "memory_current_bytes": 122327040, + "cpu_usage_usec": 5747251 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 363670 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222722 + } + } + }, + { + "elapsed_seconds": 22.225413118000688, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 88756224, + "cpu_usage_usec": 4213544 + }, + "prowlarr": { + "memory_current_bytes": 122327040, + "cpu_usage_usec": 5747251 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 363697 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222783 + } + } + }, + { + "elapsed_seconds": 22.326406131000113, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 88756224, + "cpu_usage_usec": 4213665 + }, + "prowlarr": { + "memory_current_bytes": 122327040, + "cpu_usage_usec": 5747251 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 363697 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222783 + } + } + }, + { + "elapsed_seconds": 22.427028638000593, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 88756224, + "cpu_usage_usec": 4213665 + }, + "prowlarr": { + "memory_current_bytes": 122327040, + "cpu_usage_usec": 5747251 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 363697 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222783 + } + } + }, + { + "elapsed_seconds": 22.527965850000328, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 88756224, + "cpu_usage_usec": 4213665 + }, + "prowlarr": { + "memory_current_bytes": 122327040, + "cpu_usage_usec": 5747686 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 363697 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222783 + } + } + }, + { + "elapsed_seconds": 22.628842032000648, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 89726976, + "cpu_usage_usec": 4259428 + }, + "prowlarr": { + "memory_current_bytes": 123604992, + "cpu_usage_usec": 5767420 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 363697 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222783 + } + } + }, + { + "elapsed_seconds": 22.729293248999966, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 89673728, + "cpu_usage_usec": 4314677 + }, + "prowlarr": { + "memory_current_bytes": 123088896, + "cpu_usage_usec": 5767497 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 363706 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222783 + } + } + }, + { + "elapsed_seconds": 22.829809681999905, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 89624576, + "cpu_usage_usec": 4364831 + }, + "prowlarr": { + "memory_current_bytes": 123088896, + "cpu_usage_usec": 5767497 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 363706 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222783 + } + } + }, + { + "elapsed_seconds": 22.930259340000703, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 89473024, + "cpu_usage_usec": 4414931 + }, + "prowlarr": { + "memory_current_bytes": 122871808, + "cpu_usage_usec": 5767497 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 363759 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222783 + } + } + }, + { + "elapsed_seconds": 23.03070643400042, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 89645056, + "cpu_usage_usec": 4464805 + }, + "prowlarr": { + "memory_current_bytes": 122867712, + "cpu_usage_usec": 5767497 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 363759 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222783 + } + } + }, + { + "elapsed_seconds": 23.13116368900046, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 89841664, + "cpu_usage_usec": 4515273 + }, + "prowlarr": { + "memory_current_bytes": 122630144, + "cpu_usage_usec": 5768249 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 363759 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222783 + } + } + }, + { + "elapsed_seconds": 23.231627160000244, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 89841664, + "cpu_usage_usec": 4529889 + }, + "prowlarr": { + "memory_current_bytes": 122630144, + "cpu_usage_usec": 5768249 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 363824 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222826 + } + } + }, + { + "elapsed_seconds": 23.33244910600024, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 89800704, + "cpu_usage_usec": 4529969 + }, + "prowlarr": { + "memory_current_bytes": 122384384, + "cpu_usage_usec": 5768249 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 363824 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222826 + } + } + }, + { + "elapsed_seconds": 23.433444898000744, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 89800704, + "cpu_usage_usec": 4529969 + }, + "prowlarr": { + "memory_current_bytes": 122384384, + "cpu_usage_usec": 5768249 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 363983 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222826 + } + } + }, + { + "elapsed_seconds": 23.53482480399998, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 89800704, + "cpu_usage_usec": 4529969 + }, + "prowlarr": { + "memory_current_bytes": 122384384, + "cpu_usage_usec": 5768760 + }, + "qbittorrent": { + "memory_current_bytes": 25878528, + "cpu_usage_usec": 363983 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222826 + } + } + }, + { + "elapsed_seconds": 23.636201054000594, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 90312704, + "cpu_usage_usec": 4535406 + }, + "prowlarr": { + "memory_current_bytes": 123691008, + "cpu_usage_usec": 5774989 + }, + "qbittorrent": { + "memory_current_bytes": 27504640, + "cpu_usage_usec": 365956 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222826 + } + } + }, + { + "elapsed_seconds": 23.73663533800027, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 90099712, + "cpu_usage_usec": 4535406 + }, + "prowlarr": { + "memory_current_bytes": 123691008, + "cpu_usage_usec": 5775078 + }, + "qbittorrent": { + "memory_current_bytes": 27504640, + "cpu_usage_usec": 365984 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222826 + } + } + }, + { + "elapsed_seconds": 23.838710306000394, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 90079232, + "cpu_usage_usec": 4535406 + }, + "prowlarr": { + "memory_current_bytes": 123691008, + "cpu_usage_usec": 5775409 + }, + "qbittorrent": { + "memory_current_bytes": 27365376, + "cpu_usage_usec": 367309 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222826 + } + } + }, + { + "elapsed_seconds": 23.93911267600015, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 90079232, + "cpu_usage_usec": 4535406 + }, + "prowlarr": { + "memory_current_bytes": 123691008, + "cpu_usage_usec": 5775409 + }, + "qbittorrent": { + "memory_current_bytes": 27271168, + "cpu_usage_usec": 367309 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222826 + } + } + }, + { + "elapsed_seconds": 24.03952905300048, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 90075136, + "cpu_usage_usec": 4535406 + }, + "prowlarr": { + "memory_current_bytes": 123416576, + "cpu_usage_usec": 5775409 + }, + "qbittorrent": { + "memory_current_bytes": 27303936, + "cpu_usage_usec": 367880 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222826 + } + } + }, + { + "elapsed_seconds": 24.140149968000514, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 89862144, + "cpu_usage_usec": 4535440 + }, + "prowlarr": { + "memory_current_bytes": 122400768, + "cpu_usage_usec": 5775443 + }, + "qbittorrent": { + "memory_current_bytes": 26054656, + "cpu_usage_usec": 367880 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222826 + } + } + }, + { + "elapsed_seconds": 24.241105521999998, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 89862144, + "cpu_usage_usec": 4535515 + }, + "prowlarr": { + "memory_current_bytes": 122400768, + "cpu_usage_usec": 5775443 + }, + "qbittorrent": { + "memory_current_bytes": 26849280, + "cpu_usage_usec": 371158 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222860 + } + } + }, + { + "elapsed_seconds": 24.34157189600046, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 89858048, + "cpu_usage_usec": 4535515 + }, + "prowlarr": { + "memory_current_bytes": 122400768, + "cpu_usage_usec": 5775443 + }, + "qbittorrent": { + "memory_current_bytes": 35528704, + "cpu_usage_usec": 422473 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222860 + } + } + }, + { + "elapsed_seconds": 24.44239390400071, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 89858048, + "cpu_usage_usec": 4535515 + }, + "prowlarr": { + "memory_current_bytes": 122400768, + "cpu_usage_usec": 5775443 + }, + "qbittorrent": { + "memory_current_bytes": 46596096, + "cpu_usage_usec": 475852 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222860 + } + } + }, + { + "elapsed_seconds": 24.543018068000492, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 89858048, + "cpu_usage_usec": 4535515 + }, + "prowlarr": { + "memory_current_bytes": 122851328, + "cpu_usage_usec": 5826786 + }, + "qbittorrent": { + "memory_current_bytes": 46428160, + "cpu_usage_usec": 504006 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222860 + } + } + }, + { + "elapsed_seconds": 24.644093640999927, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 89858048, + "cpu_usage_usec": 4535599 + }, + "prowlarr": { + "memory_current_bytes": 122818560, + "cpu_usage_usec": 5876746 + }, + "qbittorrent": { + "memory_current_bytes": 46186496, + "cpu_usage_usec": 504006 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222860 + } + } + }, + { + "elapsed_seconds": 24.744544116000725, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 89858048, + "cpu_usage_usec": 4535599 + }, + "prowlarr": { + "memory_current_bytes": 123019264, + "cpu_usage_usec": 5926669 + }, + "qbittorrent": { + "memory_current_bytes": 44527616, + "cpu_usage_usec": 505593 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222860 + } + } + }, + { + "elapsed_seconds": 24.8450764600002, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 89858048, + "cpu_usage_usec": 4535599 + }, + "prowlarr": { + "memory_current_bytes": 123240448, + "cpu_usage_usec": 5977170 + }, + "qbittorrent": { + "memory_current_bytes": 44527616, + "cpu_usage_usec": 505593 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222860 + } + } + }, + { + "elapsed_seconds": 24.94582999100021, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 89858048, + "cpu_usage_usec": 4535599 + }, + "prowlarr": { + "memory_current_bytes": 123203584, + "cpu_usage_usec": 6027105 + }, + "qbittorrent": { + "memory_current_bytes": 44376064, + "cpu_usage_usec": 507025 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222860 + } + } + }, + { + "elapsed_seconds": 25.046762747000685, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 89829376, + "cpu_usage_usec": 4535696 + }, + "prowlarr": { + "memory_current_bytes": 123555840, + "cpu_usage_usec": 6077102 + }, + "qbittorrent": { + "memory_current_bytes": 44011520, + "cpu_usage_usec": 507025 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222860 + } + } + }, + { + "elapsed_seconds": 25.14722976900066, + "phase": "idle", + "services": { + "jackett": { + "memory_current_bytes": 89829376, + "cpu_usage_usec": 4535696 + }, + "prowlarr": { + "memory_current_bytes": 123715584, + "cpu_usage_usec": 6127073 + }, + "qbittorrent": { + "memory_current_bytes": 27848704, + "cpu_usage_usec": 510067 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222893 + } + } + }, + { + "elapsed_seconds": 25.24825706000047, + "phase": "idle", + "services": { + "jackett": { + "memory_current_bytes": 89829376, + "cpu_usage_usec": 4535759 + }, + "prowlarr": { + "memory_current_bytes": 123936768, + "cpu_usage_usec": 6177249 + }, + "qbittorrent": { + "memory_current_bytes": 27840512, + "cpu_usage_usec": 510088 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222893 + } + } + }, + { + "elapsed_seconds": 25.34872555400034, + "phase": "idle", + "services": { + "jackett": { + "memory_current_bytes": 89829376, + "cpu_usage_usec": 4535759 + }, + "prowlarr": { + "memory_current_bytes": 124141568, + "cpu_usage_usec": 6227183 + }, + "qbittorrent": { + "memory_current_bytes": 27353088, + "cpu_usage_usec": 510088 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222893 + } + } + }, + { + "elapsed_seconds": 25.449626438999985, + "phase": "idle", + "services": { + "jackett": { + "memory_current_bytes": 89829376, + "cpu_usage_usec": 4535759 + }, + "prowlarr": { + "memory_current_bytes": 124133376, + "cpu_usage_usec": 6236483 + }, + "qbittorrent": { + "memory_current_bytes": 27103232, + "cpu_usage_usec": 510088 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222893 + } + } + }, + { + "elapsed_seconds": 25.550979096000447, + "phase": "idle", + "services": { + "jackett": { + "memory_current_bytes": 89829376, + "cpu_usage_usec": 4535759 + }, + "prowlarr": { + "memory_current_bytes": 124395520, + "cpu_usage_usec": 6237233 + }, + "qbittorrent": { + "memory_current_bytes": 27066368, + "cpu_usage_usec": 510128 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222893 + } + } + }, + { + "elapsed_seconds": 25.65143824900042, + "phase": "idle", + "services": { + "jackett": { + "memory_current_bytes": 90255360, + "cpu_usage_usec": 4587256 + }, + "prowlarr": { + "memory_current_bytes": 124395520, + "cpu_usage_usec": 6237272 + }, + "qbittorrent": { + "memory_current_bytes": 26591232, + "cpu_usage_usec": 510128 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222893 + } + } + }, + { + "elapsed_seconds": 25.75239019500077, + "phase": "idle", + "services": { + "jackett": { + "memory_current_bytes": 90566656, + "cpu_usage_usec": 4637588 + }, + "prowlarr": { + "memory_current_bytes": 124395520, + "cpu_usage_usec": 6237939 + }, + "qbittorrent": { + "memory_current_bytes": 26591232, + "cpu_usage_usec": 510156 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222893 + } + } + }, + { + "elapsed_seconds": 25.853333273000317, + "phase": "idle", + "services": { + "jackett": { + "memory_current_bytes": 90509312, + "cpu_usage_usec": 4655378 + }, + "prowlarr": { + "memory_current_bytes": 124395520, + "cpu_usage_usec": 6237939 + }, + "qbittorrent": { + "memory_current_bytes": 26591232, + "cpu_usage_usec": 510156 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222893 + } + } + }, + { + "elapsed_seconds": 25.95378056700065, + "phase": "idle", + "services": { + "jackett": { + "memory_current_bytes": 90509312, + "cpu_usage_usec": 4655378 + }, + "prowlarr": { + "memory_current_bytes": 124063744, + "cpu_usage_usec": 6237939 + }, + "qbittorrent": { + "memory_current_bytes": 26591232, + "cpu_usage_usec": 510156 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222893 + } + } + }, + { + "elapsed_seconds": 26.054203294000217, + "phase": "idle", + "services": { + "jackett": { + "memory_current_bytes": 90476544, + "cpu_usage_usec": 4655378 + }, + "prowlarr": { + "memory_current_bytes": 124063744, + "cpu_usage_usec": 6237962 + }, + "qbittorrent": { + "memory_current_bytes": 26591232, + "cpu_usage_usec": 510156 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222893 + } + } + }, + { + "elapsed_seconds": 26.1546289350008, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91275264, + "cpu_usage_usec": 4661684 + }, + "prowlarr": { + "memory_current_bytes": 125345792, + "cpu_usage_usec": 6252560 + }, + "qbittorrent": { + "memory_current_bytes": 26836992, + "cpu_usage_usec": 510373 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222943 + } + } + }, + { + "elapsed_seconds": 26.255114252000567, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91275264, + "cpu_usage_usec": 4661765 + }, + "prowlarr": { + "memory_current_bytes": 125325312, + "cpu_usage_usec": 6252560 + }, + "qbittorrent": { + "memory_current_bytes": 26836992, + "cpu_usage_usec": 510406 + }, + "flaresolverr": { + "memory_current_bytes": 90537984, + "cpu_usage_usec": 2222943 + } + } + }, + { + "elapsed_seconds": 26.3556054590008, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91017216, + "cpu_usage_usec": 4661765 + }, + "prowlarr": { + "memory_current_bytes": 125108224, + "cpu_usage_usec": 6252560 + }, + "qbittorrent": { + "memory_current_bytes": 26836992, + "cpu_usage_usec": 510406 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2222943 + } + } + }, + { + "elapsed_seconds": 26.455987787000595, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 90255360, + "cpu_usage_usec": 4661765 + }, + "prowlarr": { + "memory_current_bytes": 124858368, + "cpu_usage_usec": 6252560 + }, + "qbittorrent": { + "memory_current_bytes": 26574848, + "cpu_usage_usec": 510519 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2222943 + } + } + }, + { + "elapsed_seconds": 26.556442521000463, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 90255360, + "cpu_usage_usec": 4661765 + }, + "prowlarr": { + "memory_current_bytes": 124620800, + "cpu_usage_usec": 6252741 + }, + "qbittorrent": { + "memory_current_bytes": 26562560, + "cpu_usage_usec": 510519 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2222943 + } + } + }, + { + "elapsed_seconds": 26.656960836000508, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 90255360, + "cpu_usage_usec": 4661813 + }, + "prowlarr": { + "memory_current_bytes": 124624896, + "cpu_usage_usec": 6253459 + }, + "qbittorrent": { + "memory_current_bytes": 26562560, + "cpu_usage_usec": 510519 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2222943 + } + } + }, + { + "elapsed_seconds": 26.757460415000423, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 90255360, + "cpu_usage_usec": 4661813 + }, + "prowlarr": { + "memory_current_bytes": 124624896, + "cpu_usage_usec": 6253534 + }, + "qbittorrent": { + "memory_current_bytes": 26562560, + "cpu_usage_usec": 510542 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2222943 + } + } + }, + { + "elapsed_seconds": 26.858316135000678, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 90255360, + "cpu_usage_usec": 4661813 + }, + "prowlarr": { + "memory_current_bytes": 124366848, + "cpu_usage_usec": 6253688 + }, + "qbittorrent": { + "memory_current_bytes": 26562560, + "cpu_usage_usec": 510542 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2222943 + } + } + }, + { + "elapsed_seconds": 26.95877482600008, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 90255360, + "cpu_usage_usec": 4661813 + }, + "prowlarr": { + "memory_current_bytes": 124366848, + "cpu_usage_usec": 6253688 + }, + "qbittorrent": { + "memory_current_bytes": 26562560, + "cpu_usage_usec": 510571 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2222943 + } + } + }, + { + "elapsed_seconds": 27.059700456000428, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 90255360, + "cpu_usage_usec": 4661813 + }, + "prowlarr": { + "memory_current_bytes": 124366848, + "cpu_usage_usec": 6253736 + }, + "qbittorrent": { + "memory_current_bytes": 26562560, + "cpu_usage_usec": 510571 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2222943 + } + } + }, + { + "elapsed_seconds": 27.160154550000698, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 90255360, + "cpu_usage_usec": 4661876 + }, + "prowlarr": { + "memory_current_bytes": 124366848, + "cpu_usage_usec": 6254098 + }, + "qbittorrent": { + "memory_current_bytes": 26562560, + "cpu_usage_usec": 510658 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2222989 + } + } + }, + { + "elapsed_seconds": 27.26104599000064, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 90255360, + "cpu_usage_usec": 4661993 + }, + "prowlarr": { + "memory_current_bytes": 124366848, + "cpu_usage_usec": 6254098 + }, + "qbittorrent": { + "memory_current_bytes": 26562560, + "cpu_usage_usec": 510691 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2222989 + } + } + }, + { + "elapsed_seconds": 27.36192593800024, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 90255360, + "cpu_usage_usec": 4661993 + }, + "prowlarr": { + "memory_current_bytes": 124366848, + "cpu_usage_usec": 6254098 + }, + "qbittorrent": { + "memory_current_bytes": 26562560, + "cpu_usage_usec": 510691 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2222989 + } + } + }, + { + "elapsed_seconds": 27.462812024000414, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 90255360, + "cpu_usage_usec": 4661993 + }, + "prowlarr": { + "memory_current_bytes": 124366848, + "cpu_usage_usec": 6254098 + }, + "qbittorrent": { + "memory_current_bytes": 26562560, + "cpu_usage_usec": 510691 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2222989 + } + } + }, + { + "elapsed_seconds": 27.563693654999952, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 90255360, + "cpu_usage_usec": 4661993 + }, + "prowlarr": { + "memory_current_bytes": 124366848, + "cpu_usage_usec": 6254491 + }, + "qbittorrent": { + "memory_current_bytes": 26562560, + "cpu_usage_usec": 510691 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2222989 + } + } + }, + { + "elapsed_seconds": 27.66421949600044, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 90255360, + "cpu_usage_usec": 4661993 + }, + "prowlarr": { + "memory_current_bytes": 124129280, + "cpu_usage_usec": 6254491 + }, + "qbittorrent": { + "memory_current_bytes": 26562560, + "cpu_usage_usec": 510691 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2222989 + } + } + }, + { + "elapsed_seconds": 27.764727984000274, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 90255360, + "cpu_usage_usec": 4661993 + }, + "prowlarr": { + "memory_current_bytes": 124129280, + "cpu_usage_usec": 6254595 + }, + "qbittorrent": { + "memory_current_bytes": 26562560, + "cpu_usage_usec": 510730 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2222989 + } + } + }, + { + "elapsed_seconds": 27.86565251400043, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 90255360, + "cpu_usage_usec": 4661993 + }, + "prowlarr": { + "memory_current_bytes": 124129280, + "cpu_usage_usec": 6254595 + }, + "qbittorrent": { + "memory_current_bytes": 26562560, + "cpu_usage_usec": 510730 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2222989 + } + } + }, + { + "elapsed_seconds": 27.96654429299997, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 90255360, + "cpu_usage_usec": 4661993 + }, + "prowlarr": { + "memory_current_bytes": 124129280, + "cpu_usage_usec": 6254641 + }, + "qbittorrent": { + "memory_current_bytes": 26562560, + "cpu_usage_usec": 510835 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2222989 + } + } + }, + { + "elapsed_seconds": 28.06738336900071, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 90255360, + "cpu_usage_usec": 4661993 + }, + "prowlarr": { + "memory_current_bytes": 124129280, + "cpu_usage_usec": 6254641 + }, + "qbittorrent": { + "memory_current_bytes": 26562560, + "cpu_usage_usec": 510835 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2222989 + } + } + }, + { + "elapsed_seconds": 28.167929950000143, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91250688, + "cpu_usage_usec": 4712694 + }, + "prowlarr": { + "memory_current_bytes": 123928576, + "cpu_usage_usec": 6277350 + }, + "qbittorrent": { + "memory_current_bytes": 26562560, + "cpu_usage_usec": 511009 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223037 + } + } + }, + { + "elapsed_seconds": 28.268970230999912, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91230208, + "cpu_usage_usec": 4763540 + }, + "prowlarr": { + "memory_current_bytes": 123928576, + "cpu_usage_usec": 6277350 + }, + "qbittorrent": { + "memory_current_bytes": 26562560, + "cpu_usage_usec": 511049 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223037 + } + } + }, + { + "elapsed_seconds": 28.369408715000645, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91381760, + "cpu_usage_usec": 4814519 + }, + "prowlarr": { + "memory_current_bytes": 123453440, + "cpu_usage_usec": 6277350 + }, + "qbittorrent": { + "memory_current_bytes": 26562560, + "cpu_usage_usec": 511049 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223037 + } + } + }, + { + "elapsed_seconds": 28.470296824000798, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91344896, + "cpu_usage_usec": 4832775 + }, + "prowlarr": { + "memory_current_bytes": 123453440, + "cpu_usage_usec": 6277861 + }, + "qbittorrent": { + "memory_current_bytes": 26816512, + "cpu_usage_usec": 511650 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223037 + } + } + }, + { + "elapsed_seconds": 28.57075089600039, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91344896, + "cpu_usage_usec": 4832775 + }, + "prowlarr": { + "memory_current_bytes": 123314176, + "cpu_usage_usec": 6277861 + }, + "qbittorrent": { + "memory_current_bytes": 26816512, + "cpu_usage_usec": 511650 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223037 + } + } + }, + { + "elapsed_seconds": 28.671678149999934, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91607040, + "cpu_usage_usec": 4836779 + }, + "prowlarr": { + "memory_current_bytes": 123318272, + "cpu_usage_usec": 6279274 + }, + "qbittorrent": { + "memory_current_bytes": 26816512, + "cpu_usage_usec": 511650 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223037 + } + } + }, + { + "elapsed_seconds": 28.772614770000473, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91607040, + "cpu_usage_usec": 4836779 + }, + "prowlarr": { + "memory_current_bytes": 123318272, + "cpu_usage_usec": 6279472 + }, + "qbittorrent": { + "memory_current_bytes": 26816512, + "cpu_usage_usec": 511662 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223037 + } + } + }, + { + "elapsed_seconds": 28.87357801899998, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91607040, + "cpu_usage_usec": 4836779 + }, + "prowlarr": { + "memory_current_bytes": 123318272, + "cpu_usage_usec": 6279979 + }, + "qbittorrent": { + "memory_current_bytes": 26816512, + "cpu_usage_usec": 511662 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223037 + } + } + }, + { + "elapsed_seconds": 28.974464660000194, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91607040, + "cpu_usage_usec": 4836779 + }, + "prowlarr": { + "memory_current_bytes": 123318272, + "cpu_usage_usec": 6279979 + }, + "qbittorrent": { + "memory_current_bytes": 26816512, + "cpu_usage_usec": 511688 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223037 + } + } + }, + { + "elapsed_seconds": 29.075327447000745, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91496448, + "cpu_usage_usec": 4836779 + }, + "prowlarr": { + "memory_current_bytes": 123318272, + "cpu_usage_usec": 6279979 + }, + "qbittorrent": { + "memory_current_bytes": 26816512, + "cpu_usage_usec": 511688 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223037 + } + } + }, + { + "elapsed_seconds": 29.17651246100013, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91496448, + "cpu_usage_usec": 4836832 + }, + "prowlarr": { + "memory_current_bytes": 123281408, + "cpu_usage_usec": 6280996 + }, + "qbittorrent": { + "memory_current_bytes": 26816512, + "cpu_usage_usec": 511880 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223096 + } + } + }, + { + "elapsed_seconds": 29.277358882000044, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91496448, + "cpu_usage_usec": 4836948 + }, + "prowlarr": { + "memory_current_bytes": 123281408, + "cpu_usage_usec": 6280996 + }, + "qbittorrent": { + "memory_current_bytes": 26816512, + "cpu_usage_usec": 511925 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223096 + } + } + }, + { + "elapsed_seconds": 29.378094940000665, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91246592, + "cpu_usage_usec": 4836948 + }, + "prowlarr": { + "memory_current_bytes": 123281408, + "cpu_usage_usec": 6280996 + }, + "qbittorrent": { + "memory_current_bytes": 26816512, + "cpu_usage_usec": 511925 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223096 + } + } + }, + { + "elapsed_seconds": 29.478919017999942, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91246592, + "cpu_usage_usec": 4836948 + }, + "prowlarr": { + "memory_current_bytes": 123023360, + "cpu_usage_usec": 6281440 + }, + "qbittorrent": { + "memory_current_bytes": 26816512, + "cpu_usage_usec": 512057 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223096 + } + } + }, + { + "elapsed_seconds": 29.57982861000073, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91242496, + "cpu_usage_usec": 4836948 + }, + "prowlarr": { + "memory_current_bytes": 122773504, + "cpu_usage_usec": 6281440 + }, + "qbittorrent": { + "memory_current_bytes": 26816512, + "cpu_usage_usec": 512057 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223096 + } + } + }, + { + "elapsed_seconds": 29.68032229200071, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 90984448, + "cpu_usage_usec": 4837055 + }, + "prowlarr": { + "memory_current_bytes": 122773504, + "cpu_usage_usec": 6281493 + }, + "qbittorrent": { + "memory_current_bytes": 26562560, + "cpu_usage_usec": 512057 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223096 + } + } + }, + { + "elapsed_seconds": 29.781197397000142, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 90984448, + "cpu_usage_usec": 4837055 + }, + "prowlarr": { + "memory_current_bytes": 122773504, + "cpu_usage_usec": 6281597 + }, + "qbittorrent": { + "memory_current_bytes": 26562560, + "cpu_usage_usec": 512103 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223096 + } + } + }, + { + "elapsed_seconds": 29.881990755000515, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 90984448, + "cpu_usage_usec": 4837055 + }, + "prowlarr": { + "memory_current_bytes": 122773504, + "cpu_usage_usec": 6281597 + }, + "qbittorrent": { + "memory_current_bytes": 26562560, + "cpu_usage_usec": 512103 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223096 + } + } + }, + { + "elapsed_seconds": 29.983110269000463, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 90984448, + "cpu_usage_usec": 4837055 + }, + "prowlarr": { + "memory_current_bytes": 122732544, + "cpu_usage_usec": 6281597 + }, + "qbittorrent": { + "memory_current_bytes": 26562560, + "cpu_usage_usec": 512103 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223096 + } + } + }, + { + "elapsed_seconds": 30.083737375000055, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 90984448, + "cpu_usage_usec": 4837055 + }, + "prowlarr": { + "memory_current_bytes": 122732544, + "cpu_usage_usec": 6281597 + }, + "qbittorrent": { + "memory_current_bytes": 26562560, + "cpu_usage_usec": 512103 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223096 + } + } + }, + { + "elapsed_seconds": 30.184703722999984, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91762688, + "cpu_usage_usec": 4844378 + }, + "prowlarr": { + "memory_current_bytes": 124358656, + "cpu_usage_usec": 6299593 + }, + "qbittorrent": { + "memory_current_bytes": 26562560, + "cpu_usage_usec": 512255 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223145 + } + } + }, + { + "elapsed_seconds": 30.285644567000418, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91762688, + "cpu_usage_usec": 4844494 + }, + "prowlarr": { + "memory_current_bytes": 124338176, + "cpu_usage_usec": 6299593 + }, + "qbittorrent": { + "memory_current_bytes": 26562560, + "cpu_usage_usec": 512295 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223145 + } + } + }, + { + "elapsed_seconds": 30.38653825900019, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91508736, + "cpu_usage_usec": 4844494 + }, + "prowlarr": { + "memory_current_bytes": 124338176, + "cpu_usage_usec": 6299593 + }, + "qbittorrent": { + "memory_current_bytes": 26824704, + "cpu_usage_usec": 513325 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223145 + } + } + }, + { + "elapsed_seconds": 30.487394525000127, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91508736, + "cpu_usage_usec": 4844494 + }, + "prowlarr": { + "memory_current_bytes": 124329984, + "cpu_usage_usec": 6300028 + }, + "qbittorrent": { + "memory_current_bytes": 26787840, + "cpu_usage_usec": 513325 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223145 + } + } + }, + { + "elapsed_seconds": 30.588370195000607, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91508736, + "cpu_usage_usec": 4844494 + }, + "prowlarr": { + "memory_current_bytes": 123817984, + "cpu_usage_usec": 6300028 + }, + "qbittorrent": { + "memory_current_bytes": 26787840, + "cpu_usage_usec": 513325 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223145 + } + } + }, + { + "elapsed_seconds": 30.689378173000478, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91254784, + "cpu_usage_usec": 4844579 + }, + "prowlarr": { + "memory_current_bytes": 123817984, + "cpu_usage_usec": 6301376 + }, + "qbittorrent": { + "memory_current_bytes": 26771456, + "cpu_usage_usec": 513752 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223145 + } + } + }, + { + "elapsed_seconds": 30.790441506000207, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 90996736, + "cpu_usage_usec": 4844579 + }, + "prowlarr": { + "memory_current_bytes": 123817984, + "cpu_usage_usec": 6301519 + }, + "qbittorrent": { + "memory_current_bytes": 26771456, + "cpu_usage_usec": 513779 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223145 + } + } + }, + { + "elapsed_seconds": 30.891671520000273, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 90996736, + "cpu_usage_usec": 4844579 + }, + "prowlarr": { + "memory_current_bytes": 123576320, + "cpu_usage_usec": 6302074 + }, + "qbittorrent": { + "memory_current_bytes": 26763264, + "cpu_usage_usec": 514146 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223145 + } + } + }, + { + "elapsed_seconds": 30.992604427000515, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 90996736, + "cpu_usage_usec": 4844579 + }, + "prowlarr": { + "memory_current_bytes": 123576320, + "cpu_usage_usec": 6302074 + }, + "qbittorrent": { + "memory_current_bytes": 26763264, + "cpu_usage_usec": 514146 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223145 + } + } + }, + { + "elapsed_seconds": 31.093015482000737, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 90996736, + "cpu_usage_usec": 4844579 + }, + "prowlarr": { + "memory_current_bytes": 123576320, + "cpu_usage_usec": 6302074 + }, + "qbittorrent": { + "memory_current_bytes": 26537984, + "cpu_usage_usec": 514227 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223145 + } + } + }, + { + "elapsed_seconds": 31.1934475500002, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 90992640, + "cpu_usage_usec": 4844619 + }, + "prowlarr": { + "memory_current_bytes": 123817984, + "cpu_usage_usec": 6382200 + }, + "qbittorrent": { + "memory_current_bytes": 26537984, + "cpu_usage_usec": 514227 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223174 + } + } + }, + { + "elapsed_seconds": 31.29404616300053, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 90992640, + "cpu_usage_usec": 4844716 + }, + "prowlarr": { + "memory_current_bytes": 123617280, + "cpu_usage_usec": 6431440 + }, + "qbittorrent": { + "memory_current_bytes": 26537984, + "cpu_usage_usec": 514240 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223174 + } + } + }, + { + "elapsed_seconds": 31.394554106000214, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 90992640, + "cpu_usage_usec": 4844716 + }, + "prowlarr": { + "memory_current_bytes": 123842560, + "cpu_usage_usec": 6481482 + }, + "qbittorrent": { + "memory_current_bytes": 26537984, + "cpu_usage_usec": 514240 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223174 + } + } + }, + { + "elapsed_seconds": 31.49502479200055, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 90992640, + "cpu_usage_usec": 4844716 + }, + "prowlarr": { + "memory_current_bytes": 124002304, + "cpu_usage_usec": 6532337 + }, + "qbittorrent": { + "memory_current_bytes": 26537984, + "cpu_usage_usec": 514240 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223174 + } + } + }, + { + "elapsed_seconds": 31.595451436000076, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 90992640, + "cpu_usage_usec": 4844716 + }, + "prowlarr": { + "memory_current_bytes": 126283776, + "cpu_usage_usec": 6581839 + }, + "qbittorrent": { + "memory_current_bytes": 26509312, + "cpu_usage_usec": 514240 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223174 + } + } + }, + { + "elapsed_seconds": 31.695916450999903, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91193344, + "cpu_usage_usec": 4884852 + }, + "prowlarr": { + "memory_current_bytes": 126525440, + "cpu_usage_usec": 6631785 + }, + "qbittorrent": { + "memory_current_bytes": 26509312, + "cpu_usage_usec": 514240 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223174 + } + } + }, + { + "elapsed_seconds": 31.796318168000653, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91607040, + "cpu_usage_usec": 4922184 + }, + "prowlarr": { + "memory_current_bytes": 132984832, + "cpu_usage_usec": 6682497 + }, + "qbittorrent": { + "memory_current_bytes": 26509312, + "cpu_usage_usec": 514266 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223174 + } + } + }, + { + "elapsed_seconds": 31.896806678000758, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91607040, + "cpu_usage_usec": 4922184 + }, + "prowlarr": { + "memory_current_bytes": 132677632, + "cpu_usage_usec": 6693321 + }, + "qbittorrent": { + "memory_current_bytes": 26480640, + "cpu_usage_usec": 514266 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223174 + } + } + }, + { + "elapsed_seconds": 31.99769454000034, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91607040, + "cpu_usage_usec": 4922184 + }, + "prowlarr": { + "memory_current_bytes": 132677632, + "cpu_usage_usec": 6693321 + }, + "qbittorrent": { + "memory_current_bytes": 26480640, + "cpu_usage_usec": 514266 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223174 + } + } + }, + { + "elapsed_seconds": 32.09866354800033, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91770880, + "cpu_usage_usec": 4922618 + }, + "prowlarr": { + "memory_current_bytes": 132939776, + "cpu_usage_usec": 6695058 + }, + "qbittorrent": { + "memory_current_bytes": 26480640, + "cpu_usage_usec": 514432 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223174 + } + } + }, + { + "elapsed_seconds": 32.19906697100032, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92807168, + "cpu_usage_usec": 4942694 + }, + "prowlarr": { + "memory_current_bytes": 134230016, + "cpu_usage_usec": 6712294 + }, + "qbittorrent": { + "memory_current_bytes": 26480640, + "cpu_usage_usec": 514432 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223230 + } + } + }, + { + "elapsed_seconds": 32.30006750800021, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92557312, + "cpu_usage_usec": 4942802 + }, + "prowlarr": { + "memory_current_bytes": 134225920, + "cpu_usage_usec": 6712294 + }, + "qbittorrent": { + "memory_current_bytes": 26480640, + "cpu_usage_usec": 514446 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223230 + } + } + }, + { + "elapsed_seconds": 32.40094998800032, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92557312, + "cpu_usage_usec": 4942802 + }, + "prowlarr": { + "memory_current_bytes": 134225920, + "cpu_usage_usec": 6712294 + }, + "qbittorrent": { + "memory_current_bytes": 26480640, + "cpu_usage_usec": 514612 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223230 + } + } + }, + { + "elapsed_seconds": 32.50191672700021, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92557312, + "cpu_usage_usec": 4942802 + }, + "prowlarr": { + "memory_current_bytes": 133992448, + "cpu_usage_usec": 6712622 + }, + "qbittorrent": { + "memory_current_bytes": 26480640, + "cpu_usage_usec": 514612 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223230 + } + } + }, + { + "elapsed_seconds": 32.60285428499992, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92041216, + "cpu_usage_usec": 4942852 + }, + "prowlarr": { + "memory_current_bytes": 133468160, + "cpu_usage_usec": 6712681 + }, + "qbittorrent": { + "memory_current_bytes": 26480640, + "cpu_usage_usec": 514612 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223230 + } + } + }, + { + "elapsed_seconds": 32.70329581100032, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91594752, + "cpu_usage_usec": 4942852 + }, + "prowlarr": { + "memory_current_bytes": 133210112, + "cpu_usage_usec": 6713911 + }, + "qbittorrent": { + "memory_current_bytes": 26480640, + "cpu_usage_usec": 514612 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223230 + } + } + }, + { + "elapsed_seconds": 32.80432271400059, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91594752, + "cpu_usage_usec": 4942852 + }, + "prowlarr": { + "memory_current_bytes": 132960256, + "cpu_usage_usec": 6714297 + }, + "qbittorrent": { + "memory_current_bytes": 26480640, + "cpu_usage_usec": 514666 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223230 + } + } + }, + { + "elapsed_seconds": 32.905179594999936, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91594752, + "cpu_usage_usec": 4942852 + }, + "prowlarr": { + "memory_current_bytes": 132960256, + "cpu_usage_usec": 6714297 + }, + "qbittorrent": { + "memory_current_bytes": 26480640, + "cpu_usage_usec": 514701 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223230 + } + } + }, + { + "elapsed_seconds": 33.006055691000256, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91594752, + "cpu_usage_usec": 4942852 + }, + "prowlarr": { + "memory_current_bytes": 132960256, + "cpu_usage_usec": 6714297 + }, + "qbittorrent": { + "memory_current_bytes": 26480640, + "cpu_usage_usec": 514701 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223230 + } + } + }, + { + "elapsed_seconds": 33.10694577600043, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91594752, + "cpu_usage_usec": 4942925 + }, + "prowlarr": { + "memory_current_bytes": 132726784, + "cpu_usage_usec": 6714377 + }, + "qbittorrent": { + "memory_current_bytes": 26480640, + "cpu_usage_usec": 514893 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223230 + } + } + }, + { + "elapsed_seconds": 33.20784315900073, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91594752, + "cpu_usage_usec": 4942925 + }, + "prowlarr": { + "memory_current_bytes": 132726784, + "cpu_usage_usec": 6714714 + }, + "qbittorrent": { + "memory_current_bytes": 26480640, + "cpu_usage_usec": 514893 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223269 + } + } + }, + { + "elapsed_seconds": 33.308754861000125, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91594752, + "cpu_usage_usec": 4943030 + }, + "prowlarr": { + "memory_current_bytes": 132726784, + "cpu_usage_usec": 6714714 + }, + "qbittorrent": { + "memory_current_bytes": 26480640, + "cpu_usage_usec": 514916 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223269 + } + } + }, + { + "elapsed_seconds": 33.40962274699996, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91594752, + "cpu_usage_usec": 4943030 + }, + "prowlarr": { + "memory_current_bytes": 132726784, + "cpu_usage_usec": 6714714 + }, + "qbittorrent": { + "memory_current_bytes": 26480640, + "cpu_usage_usec": 514916 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223269 + } + } + }, + { + "elapsed_seconds": 33.51052345300013, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91594752, + "cpu_usage_usec": 4943030 + }, + "prowlarr": { + "memory_current_bytes": 132726784, + "cpu_usage_usec": 6715125 + }, + "qbittorrent": { + "memory_current_bytes": 26480640, + "cpu_usage_usec": 514916 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223269 + } + } + }, + { + "elapsed_seconds": 33.6115333860007, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91594752, + "cpu_usage_usec": 4943030 + }, + "prowlarr": { + "memory_current_bytes": 132726784, + "cpu_usage_usec": 6715173 + }, + "qbittorrent": { + "memory_current_bytes": 26480640, + "cpu_usage_usec": 514916 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223269 + } + } + }, + { + "elapsed_seconds": 33.712541960000635, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91594752, + "cpu_usage_usec": 4943030 + }, + "prowlarr": { + "memory_current_bytes": 132726784, + "cpu_usage_usec": 6715286 + }, + "qbittorrent": { + "memory_current_bytes": 26480640, + "cpu_usage_usec": 514916 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223269 + } + } + }, + { + "elapsed_seconds": 33.81342286600011, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91594752, + "cpu_usage_usec": 4943030 + }, + "prowlarr": { + "memory_current_bytes": 132726784, + "cpu_usage_usec": 6715286 + }, + "qbittorrent": { + "memory_current_bytes": 26480640, + "cpu_usage_usec": 514960 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223269 + } + } + }, + { + "elapsed_seconds": 33.914359166000395, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91594752, + "cpu_usage_usec": 4943030 + }, + "prowlarr": { + "memory_current_bytes": 132726784, + "cpu_usage_usec": 6715286 + }, + "qbittorrent": { + "memory_current_bytes": 26480640, + "cpu_usage_usec": 515099 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223269 + } + } + }, + { + "elapsed_seconds": 34.01530447799996, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 91594752, + "cpu_usage_usec": 4943030 + }, + "prowlarr": { + "memory_current_bytes": 132726784, + "cpu_usage_usec": 6715286 + }, + "qbittorrent": { + "memory_current_bytes": 26480640, + "cpu_usage_usec": 515099 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223269 + } + } + }, + { + "elapsed_seconds": 34.11665453400019, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 92864512, + "cpu_usage_usec": 4966328 + }, + "prowlarr": { + "memory_current_bytes": 133672960, + "cpu_usage_usec": 6729719 + }, + "qbittorrent": { + "memory_current_bytes": 26480640, + "cpu_usage_usec": 515330 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223269 + } + } + }, + { + "elapsed_seconds": 34.21709354399991, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 92700672, + "cpu_usage_usec": 5041147 + }, + "prowlarr": { + "memory_current_bytes": 133152768, + "cpu_usage_usec": 6730172 + }, + "qbittorrent": { + "memory_current_bytes": 27766784, + "cpu_usage_usec": 517900 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223327 + } + } + }, + { + "elapsed_seconds": 34.31758675800029, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 92114944, + "cpu_usage_usec": 5083350 + }, + "prowlarr": { + "memory_current_bytes": 132636672, + "cpu_usage_usec": 6730172 + }, + "qbittorrent": { + "memory_current_bytes": 35819520, + "cpu_usage_usec": 572771 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223327 + } + } + }, + { + "elapsed_seconds": 34.41844396500073, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 92110848, + "cpu_usage_usec": 5083350 + }, + "prowlarr": { + "memory_current_bytes": 132636672, + "cpu_usage_usec": 6730275 + }, + "qbittorrent": { + "memory_current_bytes": 46129152, + "cpu_usage_usec": 621479 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223327 + } + } + }, + { + "elapsed_seconds": 34.51936679700066, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 92082176, + "cpu_usage_usec": 5083350 + }, + "prowlarr": { + "memory_current_bytes": 132636672, + "cpu_usage_usec": 6730563 + }, + "qbittorrent": { + "memory_current_bytes": 46555136, + "cpu_usage_usec": 649893 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223327 + } + } + }, + { + "elapsed_seconds": 34.62027228000079, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 92082176, + "cpu_usage_usec": 5083416 + }, + "prowlarr": { + "memory_current_bytes": 132636672, + "cpu_usage_usec": 6730627 + }, + "qbittorrent": { + "memory_current_bytes": 46039040, + "cpu_usage_usec": 651385 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223327 + } + } + }, + { + "elapsed_seconds": 34.72112422999999, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 92082176, + "cpu_usage_usec": 5083416 + }, + "prowlarr": { + "memory_current_bytes": 132636672, + "cpu_usage_usec": 6730718 + }, + "qbittorrent": { + "memory_current_bytes": 44326912, + "cpu_usage_usec": 651765 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223327 + } + } + }, + { + "elapsed_seconds": 34.82202151900037, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 92082176, + "cpu_usage_usec": 5083416 + }, + "prowlarr": { + "memory_current_bytes": 132636672, + "cpu_usage_usec": 6731007 + }, + "qbittorrent": { + "memory_current_bytes": 44748800, + "cpu_usage_usec": 653037 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223327 + } + } + }, + { + "elapsed_seconds": 34.922992281000006, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 92082176, + "cpu_usage_usec": 5083416 + }, + "prowlarr": { + "memory_current_bytes": 132636672, + "cpu_usage_usec": 6731007 + }, + "qbittorrent": { + "memory_current_bytes": 44748800, + "cpu_usage_usec": 653094 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223327 + } + } + }, + { + "elapsed_seconds": 35.02387487000033, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 92082176, + "cpu_usage_usec": 5083416 + }, + "prowlarr": { + "memory_current_bytes": 132636672, + "cpu_usage_usec": 6731007 + }, + "qbittorrent": { + "memory_current_bytes": 44351488, + "cpu_usage_usec": 654457 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223327 + } + } + }, + { + "elapsed_seconds": 35.124280015000295, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 92082176, + "cpu_usage_usec": 5083485 + }, + "prowlarr": { + "memory_current_bytes": 132861952, + "cpu_usage_usec": 6756245 + }, + "qbittorrent": { + "memory_current_bytes": 44351488, + "cpu_usage_usec": 654457 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223327 + } + } + }, + { + "elapsed_seconds": 35.225131358, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 92082176, + "cpu_usage_usec": 5083485 + }, + "prowlarr": { + "memory_current_bytes": 133619712, + "cpu_usage_usec": 6815694 + }, + "qbittorrent": { + "memory_current_bytes": 44191744, + "cpu_usage_usec": 655069 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223370 + } + } + }, + { + "elapsed_seconds": 35.325974448000125, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 92082176, + "cpu_usage_usec": 5083596 + }, + "prowlarr": { + "memory_current_bytes": 133808128, + "cpu_usage_usec": 6865926 + }, + "qbittorrent": { + "memory_current_bytes": 44138496, + "cpu_usage_usec": 655069 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223370 + } + } + }, + { + "elapsed_seconds": 35.42695338700014, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 92082176, + "cpu_usage_usec": 5083596 + }, + "prowlarr": { + "memory_current_bytes": 133955584, + "cpu_usage_usec": 6915347 + }, + "qbittorrent": { + "memory_current_bytes": 44486656, + "cpu_usage_usec": 656358 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223370 + } + } + }, + { + "elapsed_seconds": 35.528026083999976, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 92082176, + "cpu_usage_usec": 5083596 + }, + "prowlarr": { + "memory_current_bytes": 133947392, + "cpu_usage_usec": 6944342 + }, + "qbittorrent": { + "memory_current_bytes": 44486656, + "cpu_usage_usec": 656451 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223370 + } + } + }, + { + "elapsed_seconds": 35.629111577, + "phase": "idle", + "services": { + "jackett": { + "memory_current_bytes": 92082176, + "cpu_usage_usec": 5083596 + }, + "prowlarr": { + "memory_current_bytes": 133947392, + "cpu_usage_usec": 6944368 + }, + "qbittorrent": { + "memory_current_bytes": 28319744, + "cpu_usage_usec": 659726 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223370 + } + } + }, + { + "elapsed_seconds": 35.73030084400034, + "phase": "idle", + "services": { + "jackett": { + "memory_current_bytes": 92082176, + "cpu_usage_usec": 5083596 + }, + "prowlarr": { + "memory_current_bytes": 133947392, + "cpu_usage_usec": 6944429 + }, + "qbittorrent": { + "memory_current_bytes": 28319744, + "cpu_usage_usec": 659757 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223370 + } + } + }, + { + "elapsed_seconds": 35.83120772700022, + "phase": "idle", + "services": { + "jackett": { + "memory_current_bytes": 92082176, + "cpu_usage_usec": 5083596 + }, + "prowlarr": { + "memory_current_bytes": 133947392, + "cpu_usage_usec": 6944429 + }, + "qbittorrent": { + "memory_current_bytes": 28106752, + "cpu_usage_usec": 659757 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223370 + } + } + }, + { + "elapsed_seconds": 35.932095185000435, + "phase": "idle", + "services": { + "jackett": { + "memory_current_bytes": 92082176, + "cpu_usage_usec": 5083596 + }, + "prowlarr": { + "memory_current_bytes": 133947392, + "cpu_usage_usec": 6944429 + }, + "qbittorrent": { + "memory_current_bytes": 27852800, + "cpu_usage_usec": 659757 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223370 + } + } + }, + { + "elapsed_seconds": 36.03305937999994, + "phase": "idle", + "services": { + "jackett": { + "memory_current_bytes": 92082176, + "cpu_usage_usec": 5083596 + }, + "prowlarr": { + "memory_current_bytes": 133890048, + "cpu_usage_usec": 6944429 + }, + "qbittorrent": { + "memory_current_bytes": 27852800, + "cpu_usage_usec": 659792 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223370 + } + } + }, + { + "elapsed_seconds": 36.13395538500026, + "phase": "idle", + "services": { + "jackett": { + "memory_current_bytes": 92082176, + "cpu_usage_usec": 5083596 + }, + "prowlarr": { + "memory_current_bytes": 133890048, + "cpu_usage_usec": 6944503 + }, + "qbittorrent": { + "memory_current_bytes": 27852800, + "cpu_usage_usec": 659792 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223370 + } + } + }, + { + "elapsed_seconds": 36.23437533300057, + "phase": "idle", + "services": { + "jackett": { + "memory_current_bytes": 92082176, + "cpu_usage_usec": 5083596 + }, + "prowlarr": { + "memory_current_bytes": 133890048, + "cpu_usage_usec": 6944503 + }, + "qbittorrent": { + "memory_current_bytes": 27852800, + "cpu_usage_usec": 659845 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223437 + } + } + }, + { + "elapsed_seconds": 36.33527630200024, + "phase": "idle", + "services": { + "jackett": { + "memory_current_bytes": 92082176, + "cpu_usage_usec": 5083658 + }, + "prowlarr": { + "memory_current_bytes": 133890048, + "cpu_usage_usec": 6944503 + }, + "qbittorrent": { + "memory_current_bytes": 27852800, + "cpu_usage_usec": 659845 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223437 + } + } + }, + { + "elapsed_seconds": 36.435734152000805, + "phase": "idle", + "services": { + "jackett": { + "memory_current_bytes": 92082176, + "cpu_usage_usec": 5083658 + }, + "prowlarr": { + "memory_current_bytes": 133890048, + "cpu_usage_usec": 6944503 + }, + "qbittorrent": { + "memory_current_bytes": 27185152, + "cpu_usage_usec": 659845 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223437 + } + } + }, + { + "elapsed_seconds": 36.5362449510003, + "phase": "idle", + "services": { + "jackett": { + "memory_current_bytes": 92082176, + "cpu_usage_usec": 5083658 + }, + "prowlarr": { + "memory_current_bytes": 133890048, + "cpu_usage_usec": 6944784 + }, + "qbittorrent": { + "memory_current_bytes": 27111424, + "cpu_usage_usec": 659845 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223437 + } + } + }, + { + "elapsed_seconds": 36.63675206100015, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93130752, + "cpu_usage_usec": 5089986 + }, + "prowlarr": { + "memory_current_bytes": 130830336, + "cpu_usage_usec": 6965514 + }, + "qbittorrent": { + "memory_current_bytes": 26824704, + "cpu_usage_usec": 660050 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223437 + } + } + }, + { + "elapsed_seconds": 36.73723348600015, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93130752, + "cpu_usage_usec": 5089986 + }, + "prowlarr": { + "memory_current_bytes": 130793472, + "cpu_usage_usec": 6965614 + }, + "qbittorrent": { + "memory_current_bytes": 26824704, + "cpu_usage_usec": 660069 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223437 + } + } + }, + { + "elapsed_seconds": 36.83769625400055, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92606464, + "cpu_usage_usec": 5089986 + }, + "prowlarr": { + "memory_current_bytes": 130289664, + "cpu_usage_usec": 6965614 + }, + "qbittorrent": { + "memory_current_bytes": 26824704, + "cpu_usage_usec": 660069 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223437 + } + } + }, + { + "elapsed_seconds": 36.938576341000044, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92352512, + "cpu_usage_usec": 5089986 + }, + "prowlarr": { + "memory_current_bytes": 130056192, + "cpu_usage_usec": 6965614 + }, + "qbittorrent": { + "memory_current_bytes": 27082752, + "cpu_usage_usec": 660337 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223437 + } + } + }, + { + "elapsed_seconds": 37.039472957000726, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92352512, + "cpu_usage_usec": 5089986 + }, + "prowlarr": { + "memory_current_bytes": 129814528, + "cpu_usage_usec": 6965660 + }, + "qbittorrent": { + "memory_current_bytes": 27082752, + "cpu_usage_usec": 660337 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223437 + } + } + }, + { + "elapsed_seconds": 37.140403833000164, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92352512, + "cpu_usage_usec": 5090059 + }, + "prowlarr": { + "memory_current_bytes": 130076672, + "cpu_usage_usec": 6968017 + }, + "qbittorrent": { + "memory_current_bytes": 27082752, + "cpu_usage_usec": 660337 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223437 + } + } + }, + { + "elapsed_seconds": 37.2416088760001, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92094464, + "cpu_usage_usec": 5090186 + }, + "prowlarr": { + "memory_current_bytes": 130076672, + "cpu_usage_usec": 6968017 + }, + "qbittorrent": { + "memory_current_bytes": 27082752, + "cpu_usage_usec": 660364 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223484 + } + } + }, + { + "elapsed_seconds": 37.342491993000294, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92094464, + "cpu_usage_usec": 5090186 + }, + "prowlarr": { + "memory_current_bytes": 130076672, + "cpu_usage_usec": 6968017 + }, + "qbittorrent": { + "memory_current_bytes": 27078656, + "cpu_usage_usec": 660364 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223484 + } + } + }, + { + "elapsed_seconds": 37.44349015700027, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92094464, + "cpu_usage_usec": 5090186 + }, + "prowlarr": { + "memory_current_bytes": 130076672, + "cpu_usage_usec": 6968017 + }, + "qbittorrent": { + "memory_current_bytes": 27078656, + "cpu_usage_usec": 660364 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223484 + } + } + }, + { + "elapsed_seconds": 37.54432688700035, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92094464, + "cpu_usage_usec": 5090186 + }, + "prowlarr": { + "memory_current_bytes": 130076672, + "cpu_usage_usec": 6968488 + }, + "qbittorrent": { + "memory_current_bytes": 27078656, + "cpu_usage_usec": 660364 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223484 + } + } + }, + { + "elapsed_seconds": 37.64494298600039, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92561408, + "cpu_usage_usec": 5121832 + }, + "prowlarr": { + "memory_current_bytes": 129818624, + "cpu_usage_usec": 6968809 + }, + "qbittorrent": { + "memory_current_bytes": 27078656, + "cpu_usage_usec": 660546 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223484 + } + } + }, + { + "elapsed_seconds": 37.74544049800079, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92561408, + "cpu_usage_usec": 5121832 + }, + "prowlarr": { + "memory_current_bytes": 129748992, + "cpu_usage_usec": 6968915 + }, + "qbittorrent": { + "memory_current_bytes": 26820608, + "cpu_usage_usec": 660568 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223484 + } + } + }, + { + "elapsed_seconds": 37.84644232700066, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92344320, + "cpu_usage_usec": 5121832 + }, + "prowlarr": { + "memory_current_bytes": 129748992, + "cpu_usage_usec": 6969204 + }, + "qbittorrent": { + "memory_current_bytes": 26820608, + "cpu_usage_usec": 660568 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223484 + } + } + }, + { + "elapsed_seconds": 37.94705465400057, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92344320, + "cpu_usage_usec": 5121832 + }, + "prowlarr": { + "memory_current_bytes": 129748992, + "cpu_usage_usec": 6969204 + }, + "qbittorrent": { + "memory_current_bytes": 26820608, + "cpu_usage_usec": 660568 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223484 + } + } + }, + { + "elapsed_seconds": 38.04792229100076, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92344320, + "cpu_usage_usec": 5121832 + }, + "prowlarr": { + "memory_current_bytes": 129748992, + "cpu_usage_usec": 6969242 + }, + "qbittorrent": { + "memory_current_bytes": 26820608, + "cpu_usage_usec": 660568 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223484 + } + } + }, + { + "elapsed_seconds": 38.148788234000676, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92344320, + "cpu_usage_usec": 5121832 + }, + "prowlarr": { + "memory_current_bytes": 129748992, + "cpu_usage_usec": 6969242 + }, + "qbittorrent": { + "memory_current_bytes": 26820608, + "cpu_usage_usec": 660568 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223484 + } + } + }, + { + "elapsed_seconds": 38.2498774300002, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92155904, + "cpu_usage_usec": 5121964 + }, + "prowlarr": { + "memory_current_bytes": 129748992, + "cpu_usage_usec": 6969242 + }, + "qbittorrent": { + "memory_current_bytes": 26820608, + "cpu_usage_usec": 660602 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223526 + } + } + }, + { + "elapsed_seconds": 38.350558482999986, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92155904, + "cpu_usage_usec": 5121964 + }, + "prowlarr": { + "memory_current_bytes": 129748992, + "cpu_usage_usec": 6969242 + }, + "qbittorrent": { + "memory_current_bytes": 26820608, + "cpu_usage_usec": 660602 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223526 + } + } + }, + { + "elapsed_seconds": 38.45139121500051, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92155904, + "cpu_usage_usec": 5121964 + }, + "prowlarr": { + "memory_current_bytes": 129748992, + "cpu_usage_usec": 6969242 + }, + "qbittorrent": { + "memory_current_bytes": 26820608, + "cpu_usage_usec": 660742 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223526 + } + } + }, + { + "elapsed_seconds": 38.55241747300079, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92155904, + "cpu_usage_usec": 5121964 + }, + "prowlarr": { + "memory_current_bytes": 129748992, + "cpu_usage_usec": 6969731 + }, + "qbittorrent": { + "memory_current_bytes": 26820608, + "cpu_usage_usec": 660742 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223526 + } + } + }, + { + "elapsed_seconds": 38.65289966900036, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93179904, + "cpu_usage_usec": 5172986 + }, + "prowlarr": { + "memory_current_bytes": 131018752, + "cpu_usage_usec": 7001180 + }, + "qbittorrent": { + "memory_current_bytes": 26820608, + "cpu_usage_usec": 660987 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223526 + } + } + }, + { + "elapsed_seconds": 38.75385540000025, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93179904, + "cpu_usage_usec": 5182921 + }, + "prowlarr": { + "memory_current_bytes": 130760704, + "cpu_usage_usec": 7001279 + }, + "qbittorrent": { + "memory_current_bytes": 26820608, + "cpu_usage_usec": 661008 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223526 + } + } + }, + { + "elapsed_seconds": 38.85481188600079, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93179904, + "cpu_usage_usec": 5182921 + }, + "prowlarr": { + "memory_current_bytes": 130744320, + "cpu_usage_usec": 7001608 + }, + "qbittorrent": { + "memory_current_bytes": 26820608, + "cpu_usage_usec": 661008 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223526 + } + } + }, + { + "elapsed_seconds": 38.95576968400019, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93179904, + "cpu_usage_usec": 5182921 + }, + "prowlarr": { + "memory_current_bytes": 130744320, + "cpu_usage_usec": 7001608 + }, + "qbittorrent": { + "memory_current_bytes": 26820608, + "cpu_usage_usec": 661054 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223526 + } + } + }, + { + "elapsed_seconds": 39.05662517900055, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93171712, + "cpu_usage_usec": 5182921 + }, + "prowlarr": { + "memory_current_bytes": 130744320, + "cpu_usage_usec": 7001666 + }, + "qbittorrent": { + "memory_current_bytes": 26820608, + "cpu_usage_usec": 661054 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223526 + } + } + }, + { + "elapsed_seconds": 39.157067708000795, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92913664, + "cpu_usage_usec": 5183784 + }, + "prowlarr": { + "memory_current_bytes": 131006464, + "cpu_usage_usec": 7002922 + }, + "qbittorrent": { + "memory_current_bytes": 26820608, + "cpu_usage_usec": 661054 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223526 + } + } + }, + { + "elapsed_seconds": 39.25760807500046, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92872704, + "cpu_usage_usec": 5203149 + }, + "prowlarr": { + "memory_current_bytes": 130748416, + "cpu_usage_usec": 7002922 + }, + "qbittorrent": { + "memory_current_bytes": 26820608, + "cpu_usage_usec": 661103 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223566 + } + } + }, + { + "elapsed_seconds": 39.35852413700013, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92872704, + "cpu_usage_usec": 5203149 + }, + "prowlarr": { + "memory_current_bytes": 130748416, + "cpu_usage_usec": 7002922 + }, + "qbittorrent": { + "memory_current_bytes": 26820608, + "cpu_usage_usec": 661103 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223566 + } + } + }, + { + "elapsed_seconds": 39.459464647999994, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92872704, + "cpu_usage_usec": 5203149 + }, + "prowlarr": { + "memory_current_bytes": 130547712, + "cpu_usage_usec": 7002922 + }, + "qbittorrent": { + "memory_current_bytes": 26820608, + "cpu_usage_usec": 661103 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223566 + } + } + }, + { + "elapsed_seconds": 39.56040386299992, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92872704, + "cpu_usage_usec": 5203149 + }, + "prowlarr": { + "memory_current_bytes": 130322432, + "cpu_usage_usec": 7003532 + }, + "qbittorrent": { + "memory_current_bytes": 26820608, + "cpu_usage_usec": 661103 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223566 + } + } + }, + { + "elapsed_seconds": 39.66134014399995, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92622848, + "cpu_usage_usec": 5204188 + }, + "prowlarr": { + "memory_current_bytes": 130322432, + "cpu_usage_usec": 7003837 + }, + "qbittorrent": { + "memory_current_bytes": 26820608, + "cpu_usage_usec": 661457 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223566 + } + } + }, + { + "elapsed_seconds": 39.76234137600022, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92622848, + "cpu_usage_usec": 5204188 + }, + "prowlarr": { + "memory_current_bytes": 130322432, + "cpu_usage_usec": 7003946 + }, + "qbittorrent": { + "memory_current_bytes": 26820608, + "cpu_usage_usec": 661483 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223566 + } + } + }, + { + "elapsed_seconds": 39.86337578600069, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92622848, + "cpu_usage_usec": 5204188 + }, + "prowlarr": { + "memory_current_bytes": 130322432, + "cpu_usage_usec": 7004216 + }, + "qbittorrent": { + "memory_current_bytes": 26820608, + "cpu_usage_usec": 661483 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223566 + } + } + }, + { + "elapsed_seconds": 39.964397609000116, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92360704, + "cpu_usage_usec": 5204188 + }, + "prowlarr": { + "memory_current_bytes": 129814528, + "cpu_usage_usec": 7004216 + }, + "qbittorrent": { + "memory_current_bytes": 26820608, + "cpu_usage_usec": 661627 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223566 + } + } + }, + { + "elapsed_seconds": 40.06535200200051, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92360704, + "cpu_usage_usec": 5204188 + }, + "prowlarr": { + "memory_current_bytes": 129814528, + "cpu_usage_usec": 7004266 + }, + "qbittorrent": { + "memory_current_bytes": 26820608, + "cpu_usage_usec": 661627 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223566 + } + } + }, + { + "elapsed_seconds": 40.16625219800062, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92360704, + "cpu_usage_usec": 5204188 + }, + "prowlarr": { + "memory_current_bytes": 129814528, + "cpu_usage_usec": 7004266 + }, + "qbittorrent": { + "memory_current_bytes": 26820608, + "cpu_usage_usec": 661627 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223621 + } + } + }, + { + "elapsed_seconds": 40.26714648400048, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92356608, + "cpu_usage_usec": 5204587 + }, + "prowlarr": { + "memory_current_bytes": 129814528, + "cpu_usage_usec": 7004266 + }, + "qbittorrent": { + "memory_current_bytes": 26820608, + "cpu_usage_usec": 661657 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223621 + } + } + }, + { + "elapsed_seconds": 40.36813399900075, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92356608, + "cpu_usage_usec": 5204587 + }, + "prowlarr": { + "memory_current_bytes": 129814528, + "cpu_usage_usec": 7004266 + }, + "qbittorrent": { + "memory_current_bytes": 26820608, + "cpu_usage_usec": 661657 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223621 + } + } + }, + { + "elapsed_seconds": 40.46910079999998, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92356608, + "cpu_usage_usec": 5204587 + }, + "prowlarr": { + "memory_current_bytes": 129814528, + "cpu_usage_usec": 7004637 + }, + "qbittorrent": { + "memory_current_bytes": 26820608, + "cpu_usage_usec": 661657 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223621 + } + } + }, + { + "elapsed_seconds": 40.570057330000054, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92356608, + "cpu_usage_usec": 5204587 + }, + "prowlarr": { + "memory_current_bytes": 129814528, + "cpu_usage_usec": 7004637 + }, + "qbittorrent": { + "memory_current_bytes": 26820608, + "cpu_usage_usec": 661657 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223621 + } + } + }, + { + "elapsed_seconds": 40.67046413500066, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92876800, + "cpu_usage_usec": 5212191 + }, + "prowlarr": { + "memory_current_bytes": 129757184, + "cpu_usage_usec": 7062945 + }, + "qbittorrent": { + "memory_current_bytes": 26820608, + "cpu_usage_usec": 662039 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223621 + } + } + }, + { + "elapsed_seconds": 40.77090968900029, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92876800, + "cpu_usage_usec": 5212191 + }, + "prowlarr": { + "memory_current_bytes": 129970176, + "cpu_usage_usec": 7113601 + }, + "qbittorrent": { + "memory_current_bytes": 26820608, + "cpu_usage_usec": 662071 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223621 + } + } + }, + { + "elapsed_seconds": 40.87154089100022, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92876800, + "cpu_usage_usec": 5212191 + }, + "prowlarr": { + "memory_current_bytes": 129884160, + "cpu_usage_usec": 7163147 + }, + "qbittorrent": { + "memory_current_bytes": 26820608, + "cpu_usage_usec": 662071 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223621 + } + } + }, + { + "elapsed_seconds": 40.97198301500066, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92876800, + "cpu_usage_usec": 5212191 + }, + "prowlarr": { + "memory_current_bytes": 130093056, + "cpu_usage_usec": 7214646 + }, + "qbittorrent": { + "memory_current_bytes": 26820608, + "cpu_usage_usec": 662090 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223621 + } + } + }, + { + "elapsed_seconds": 41.072484006000195, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92876800, + "cpu_usage_usec": 5212191 + }, + "prowlarr": { + "memory_current_bytes": 129814528, + "cpu_usage_usec": 7265271 + }, + "qbittorrent": { + "memory_current_bytes": 26820608, + "cpu_usage_usec": 662090 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223621 + } + } + }, + { + "elapsed_seconds": 41.17332804700072, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92876800, + "cpu_usage_usec": 5212260 + }, + "prowlarr": { + "memory_current_bytes": 129814528, + "cpu_usage_usec": 7277021 + }, + "qbittorrent": { + "memory_current_bytes": 26820608, + "cpu_usage_usec": 662090 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223688 + } + } + }, + { + "elapsed_seconds": 41.27426451300016, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92876800, + "cpu_usage_usec": 5212413 + }, + "prowlarr": { + "memory_current_bytes": 129531904, + "cpu_usage_usec": 7277021 + }, + "qbittorrent": { + "memory_current_bytes": 26820608, + "cpu_usage_usec": 662137 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223688 + } + } + }, + { + "elapsed_seconds": 41.37524292800026, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92876800, + "cpu_usage_usec": 5212413 + }, + "prowlarr": { + "memory_current_bytes": 129531904, + "cpu_usage_usec": 7277021 + }, + "qbittorrent": { + "memory_current_bytes": 26820608, + "cpu_usage_usec": 662137 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223688 + } + } + }, + { + "elapsed_seconds": 41.47630665500037, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92876800, + "cpu_usage_usec": 5212413 + }, + "prowlarr": { + "memory_current_bytes": 129531904, + "cpu_usage_usec": 7277622 + }, + "qbittorrent": { + "memory_current_bytes": 26820608, + "cpu_usage_usec": 662277 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223688 + } + } + }, + { + "elapsed_seconds": 41.5772320290007, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92876800, + "cpu_usage_usec": 5212413 + }, + "prowlarr": { + "memory_current_bytes": 129531904, + "cpu_usage_usec": 7277622 + }, + "qbittorrent": { + "memory_current_bytes": 26820608, + "cpu_usage_usec": 662277 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223688 + } + } + }, + { + "elapsed_seconds": 41.678570380000565, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92876800, + "cpu_usage_usec": 5212462 + }, + "prowlarr": { + "memory_current_bytes": 129531904, + "cpu_usage_usec": 7278560 + }, + "qbittorrent": { + "memory_current_bytes": 26820608, + "cpu_usage_usec": 662510 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223688 + } + } + }, + { + "elapsed_seconds": 41.77946293700006, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92876800, + "cpu_usage_usec": 5212462 + }, + "prowlarr": { + "memory_current_bytes": 129531904, + "cpu_usage_usec": 7278673 + }, + "qbittorrent": { + "memory_current_bytes": 26820608, + "cpu_usage_usec": 662536 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223688 + } + } + }, + { + "elapsed_seconds": 41.88049015100023, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92356608, + "cpu_usage_usec": 5212462 + }, + "prowlarr": { + "memory_current_bytes": 129486848, + "cpu_usage_usec": 7278965 + }, + "qbittorrent": { + "memory_current_bytes": 26820608, + "cpu_usage_usec": 662536 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223688 + } + } + }, + { + "elapsed_seconds": 41.98143124500075, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92356608, + "cpu_usage_usec": 5212462 + }, + "prowlarr": { + "memory_current_bytes": 129486848, + "cpu_usage_usec": 7279011 + }, + "qbittorrent": { + "memory_current_bytes": 26820608, + "cpu_usage_usec": 662536 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223688 + } + } + }, + { + "elapsed_seconds": 42.082382966000296, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92356608, + "cpu_usage_usec": 5212462 + }, + "prowlarr": { + "memory_current_bytes": 129486848, + "cpu_usage_usec": 7279011 + }, + "qbittorrent": { + "memory_current_bytes": 26820608, + "cpu_usage_usec": 662536 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223688 + } + } + }, + { + "elapsed_seconds": 42.183330929000476, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92356608, + "cpu_usage_usec": 5212462 + }, + "prowlarr": { + "memory_current_bytes": 129486848, + "cpu_usage_usec": 7279011 + }, + "qbittorrent": { + "memory_current_bytes": 26820608, + "cpu_usage_usec": 662536 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223762 + } + } + }, + { + "elapsed_seconds": 42.28376333899996, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92782592, + "cpu_usage_usec": 5257484 + }, + "prowlarr": { + "memory_current_bytes": 129486848, + "cpu_usage_usec": 7279011 + }, + "qbittorrent": { + "memory_current_bytes": 26820608, + "cpu_usage_usec": 662557 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223762 + } + } + }, + { + "elapsed_seconds": 42.38463495199994, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92753920, + "cpu_usage_usec": 5289895 + }, + "prowlarr": { + "memory_current_bytes": 129241088, + "cpu_usage_usec": 7279011 + }, + "qbittorrent": { + "memory_current_bytes": 26820608, + "cpu_usage_usec": 662557 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223762 + } + } + }, + { + "elapsed_seconds": 42.48550661200079, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92753920, + "cpu_usage_usec": 5289895 + }, + "prowlarr": { + "memory_current_bytes": 129503232, + "cpu_usage_usec": 7280060 + }, + "qbittorrent": { + "memory_current_bytes": 26820608, + "cpu_usage_usec": 662557 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223762 + } + } + }, + { + "elapsed_seconds": 42.58636977700007, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92753920, + "cpu_usage_usec": 5289895 + }, + "prowlarr": { + "memory_current_bytes": 129503232, + "cpu_usage_usec": 7280060 + }, + "qbittorrent": { + "memory_current_bytes": 26820608, + "cpu_usage_usec": 662557 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223762 + } + } + }, + { + "elapsed_seconds": 42.68736586600062, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93757440, + "cpu_usage_usec": 5311134 + }, + "prowlarr": { + "memory_current_bytes": 130297856, + "cpu_usage_usec": 7294209 + }, + "qbittorrent": { + "memory_current_bytes": 26820608, + "cpu_usage_usec": 662722 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223762 + } + } + }, + { + "elapsed_seconds": 42.78782739400049, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93663232, + "cpu_usage_usec": 5311134 + }, + "prowlarr": { + "memory_current_bytes": 129761280, + "cpu_usage_usec": 7294327 + }, + "qbittorrent": { + "memory_current_bytes": 26820608, + "cpu_usage_usec": 662770 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223762 + } + } + }, + { + "elapsed_seconds": 42.888731357000324, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93663232, + "cpu_usage_usec": 5311134 + }, + "prowlarr": { + "memory_current_bytes": 129761280, + "cpu_usage_usec": 7294593 + }, + "qbittorrent": { + "memory_current_bytes": 26820608, + "cpu_usage_usec": 662984 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223762 + } + } + }, + { + "elapsed_seconds": 42.98974408899994, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93663232, + "cpu_usage_usec": 5311134 + }, + "prowlarr": { + "memory_current_bytes": 129531904, + "cpu_usage_usec": 7294639 + }, + "qbittorrent": { + "memory_current_bytes": 26820608, + "cpu_usage_usec": 662984 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223762 + } + } + }, + { + "elapsed_seconds": 43.09060066800066, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93405184, + "cpu_usage_usec": 5311134 + }, + "prowlarr": { + "memory_current_bytes": 129531904, + "cpu_usage_usec": 7294639 + }, + "qbittorrent": { + "memory_current_bytes": 26820608, + "cpu_usage_usec": 662984 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223762 + } + } + }, + { + "elapsed_seconds": 43.191035626000485, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92979200, + "cpu_usage_usec": 5311197 + }, + "prowlarr": { + "memory_current_bytes": 129294336, + "cpu_usage_usec": 7295740 + }, + "qbittorrent": { + "memory_current_bytes": 26820608, + "cpu_usage_usec": 662984 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223803 + } + } + }, + { + "elapsed_seconds": 43.29204469300021, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92725248, + "cpu_usage_usec": 5311246 + }, + "prowlarr": { + "memory_current_bytes": 129294336, + "cpu_usage_usec": 7295740 + }, + "qbittorrent": { + "memory_current_bytes": 26820608, + "cpu_usage_usec": 663003 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223803 + } + } + }, + { + "elapsed_seconds": 43.39296169000045, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92725248, + "cpu_usage_usec": 5311246 + }, + "prowlarr": { + "memory_current_bytes": 129044480, + "cpu_usage_usec": 7295740 + }, + "qbittorrent": { + "memory_current_bytes": 26820608, + "cpu_usage_usec": 663003 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223803 + } + } + }, + { + "elapsed_seconds": 43.4940166840006, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92725248, + "cpu_usage_usec": 5311246 + }, + "prowlarr": { + "memory_current_bytes": 129044480, + "cpu_usage_usec": 7296423 + }, + "qbittorrent": { + "memory_current_bytes": 26820608, + "cpu_usage_usec": 663003 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223803 + } + } + }, + { + "elapsed_seconds": 43.595075592000285, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92725248, + "cpu_usage_usec": 5311246 + }, + "prowlarr": { + "memory_current_bytes": 129044480, + "cpu_usage_usec": 7296423 + }, + "qbittorrent": { + "memory_current_bytes": 26820608, + "cpu_usage_usec": 663003 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223803 + } + } + }, + { + "elapsed_seconds": 43.696299965000435, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92979200, + "cpu_usage_usec": 5311950 + }, + "prowlarr": { + "memory_current_bytes": 129044480, + "cpu_usage_usec": 7296586 + }, + "qbittorrent": { + "memory_current_bytes": 26820608, + "cpu_usage_usec": 663201 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223803 + } + } + }, + { + "elapsed_seconds": 43.79738188100055, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92979200, + "cpu_usage_usec": 5311950 + }, + "prowlarr": { + "memory_current_bytes": 129044480, + "cpu_usage_usec": 7296649 + }, + "qbittorrent": { + "memory_current_bytes": 26820608, + "cpu_usage_usec": 663221 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223803 + } + } + }, + { + "elapsed_seconds": 43.89782817500054, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92979200, + "cpu_usage_usec": 5311950 + }, + "prowlarr": { + "memory_current_bytes": 129044480, + "cpu_usage_usec": 7296925 + }, + "qbittorrent": { + "memory_current_bytes": 26820608, + "cpu_usage_usec": 663221 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223803 + } + } + }, + { + "elapsed_seconds": 43.99886609400073, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92979200, + "cpu_usage_usec": 5311950 + }, + "prowlarr": { + "memory_current_bytes": 129044480, + "cpu_usage_usec": 7297005 + }, + "qbittorrent": { + "memory_current_bytes": 26820608, + "cpu_usage_usec": 663221 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223803 + } + } + }, + { + "elapsed_seconds": 44.09985055600009, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92979200, + "cpu_usage_usec": 5311950 + }, + "prowlarr": { + "memory_current_bytes": 129044480, + "cpu_usage_usec": 7297005 + }, + "qbittorrent": { + "memory_current_bytes": 26820608, + "cpu_usage_usec": 663221 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223803 + } + } + }, + { + "elapsed_seconds": 44.200700231000155, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92979200, + "cpu_usage_usec": 5312000 + }, + "prowlarr": { + "memory_current_bytes": 129044480, + "cpu_usage_usec": 7297005 + }, + "qbittorrent": { + "memory_current_bytes": 26820608, + "cpu_usage_usec": 663221 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223879 + } + } + }, + { + "elapsed_seconds": 44.30112596500021, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92975104, + "cpu_usage_usec": 5312053 + }, + "prowlarr": { + "memory_current_bytes": 129044480, + "cpu_usage_usec": 7297005 + }, + "qbittorrent": { + "memory_current_bytes": 26820608, + "cpu_usage_usec": 663262 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223879 + } + } + }, + { + "elapsed_seconds": 44.40210524200029, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92975104, + "cpu_usage_usec": 5312053 + }, + "prowlarr": { + "memory_current_bytes": 129044480, + "cpu_usage_usec": 7297005 + }, + "qbittorrent": { + "memory_current_bytes": 26820608, + "cpu_usage_usec": 663412 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223879 + } + } + }, + { + "elapsed_seconds": 44.50344017900079, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 92975104, + "cpu_usage_usec": 5312053 + }, + "prowlarr": { + "memory_current_bytes": 129044480, + "cpu_usage_usec": 7297513 + }, + "qbittorrent": { + "memory_current_bytes": 26820608, + "cpu_usage_usec": 663412 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223879 + } + } + }, + { + "elapsed_seconds": 44.605906028999925, + "phase": "search", + "services": { + "jackett": { + "memory_current_bytes": 93495296, + "cpu_usage_usec": 5315177 + }, + "prowlarr": { + "memory_current_bytes": 129306624, + "cpu_usage_usec": 7298350 + }, + "qbittorrent": { + "memory_current_bytes": 26820608, + "cpu_usage_usec": 663556 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223879 + } + } + }, + { + "elapsed_seconds": 44.70647902700057, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 93880320, + "cpu_usage_usec": 5392020 + }, + "prowlarr": { + "memory_current_bytes": 129781760, + "cpu_usage_usec": 7369757 + }, + "qbittorrent": { + "memory_current_bytes": 28266496, + "cpu_usage_usec": 667515 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223879 + } + } + }, + { + "elapsed_seconds": 44.80706041300073, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 94576640, + "cpu_usage_usec": 5442222 + }, + "prowlarr": { + "memory_current_bytes": 129781760, + "cpu_usage_usec": 7389678 + }, + "qbittorrent": { + "memory_current_bytes": 27914240, + "cpu_usage_usec": 667546 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223879 + } + } + }, + { + "elapsed_seconds": 44.90760459100056, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 94928896, + "cpu_usage_usec": 5487257 + }, + "prowlarr": { + "memory_current_bytes": 129781760, + "cpu_usage_usec": 7389678 + }, + "qbittorrent": { + "memory_current_bytes": 27791360, + "cpu_usage_usec": 668893 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223879 + } + } + }, + { + "elapsed_seconds": 45.008448542000224, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 94928896, + "cpu_usage_usec": 5487257 + }, + "prowlarr": { + "memory_current_bytes": 129273856, + "cpu_usage_usec": 7389740 + }, + "qbittorrent": { + "memory_current_bytes": 27660288, + "cpu_usage_usec": 668893 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223879 + } + } + }, + { + "elapsed_seconds": 45.10942883900043, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 94408704, + "cpu_usage_usec": 5487257 + }, + "prowlarr": { + "memory_current_bytes": 129273856, + "cpu_usage_usec": 7389740 + }, + "qbittorrent": { + "memory_current_bytes": 27934720, + "cpu_usage_usec": 670192 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223879 + } + } + }, + { + "elapsed_seconds": 45.21037141800025, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 94408704, + "cpu_usage_usec": 5487310 + }, + "prowlarr": { + "memory_current_bytes": 129273856, + "cpu_usage_usec": 7389740 + }, + "qbittorrent": { + "memory_current_bytes": 27688960, + "cpu_usage_usec": 670192 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223949 + } + } + }, + { + "elapsed_seconds": 45.3109112380007, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 94289920, + "cpu_usage_usec": 5487398 + }, + "prowlarr": { + "memory_current_bytes": 129228800, + "cpu_usage_usec": 7389740 + }, + "qbittorrent": { + "memory_current_bytes": 33918976, + "cpu_usage_usec": 722135 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223949 + } + } + }, + { + "elapsed_seconds": 45.41141676999996, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 94289920, + "cpu_usage_usec": 5487398 + }, + "prowlarr": { + "memory_current_bytes": 129228800, + "cpu_usage_usec": 7389740 + }, + "qbittorrent": { + "memory_current_bytes": 45420544, + "cpu_usage_usec": 778407 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223949 + } + } + }, + { + "elapsed_seconds": 45.51244918800057, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 94289920, + "cpu_usage_usec": 5487398 + }, + "prowlarr": { + "memory_current_bytes": 129228800, + "cpu_usage_usec": 7390034 + }, + "qbittorrent": { + "memory_current_bytes": 47120384, + "cpu_usage_usec": 802487 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223949 + } + } + }, + { + "elapsed_seconds": 45.613341592000324, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 94289920, + "cpu_usage_usec": 5487398 + }, + "prowlarr": { + "memory_current_bytes": 129228800, + "cpu_usage_usec": 7390034 + }, + "qbittorrent": { + "memory_current_bytes": 46952448, + "cpu_usage_usec": 802487 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223949 + } + } + }, + { + "elapsed_seconds": 45.71401306500047, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 94289920, + "cpu_usage_usec": 5487398 + }, + "prowlarr": { + "memory_current_bytes": 129228800, + "cpu_usage_usec": 7390102 + }, + "qbittorrent": { + "memory_current_bytes": 47312896, + "cpu_usage_usec": 803889 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223949 + } + } + }, + { + "elapsed_seconds": 45.815008565000426, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 94289920, + "cpu_usage_usec": 5487398 + }, + "prowlarr": { + "memory_current_bytes": 129228800, + "cpu_usage_usec": 7390102 + }, + "qbittorrent": { + "memory_current_bytes": 44654592, + "cpu_usage_usec": 804357 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223949 + } + } + }, + { + "elapsed_seconds": 45.916055176000555, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 94289920, + "cpu_usage_usec": 5487398 + }, + "prowlarr": { + "memory_current_bytes": 129228800, + "cpu_usage_usec": 7390102 + }, + "qbittorrent": { + "memory_current_bytes": 44974080, + "cpu_usage_usec": 807622 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223949 + } + } + }, + { + "elapsed_seconds": 46.01711755800079, + "phase": "download", + "services": { + "jackett": { + "memory_current_bytes": 94289920, + "cpu_usage_usec": 5487398 + }, + "prowlarr": { + "memory_current_bytes": 129228800, + "cpu_usage_usec": 7390153 + }, + "qbittorrent": { + "memory_current_bytes": 44941312, + "cpu_usage_usec": 807622 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223949 + } + } + }, + { + "elapsed_seconds": 46.11762298300073, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 94289920, + "cpu_usage_usec": 5487398 + }, + "prowlarr": { + "memory_current_bytes": 129228800, + "cpu_usage_usec": 7390153 + }, + "qbittorrent": { + "memory_current_bytes": 27832320, + "cpu_usage_usec": 810848 + }, + "flaresolverr": { + "memory_current_bytes": 90533888, + "cpu_usage_usec": 2223949 + } + } + }, + { + "elapsed_seconds": 46.21802412300076, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 95498240, + "cpu_usage_usec": 5507649 + }, + "prowlarr": { + "memory_current_bytes": 115150848, + "cpu_usage_usec": 7441635 + }, + "qbittorrent": { + "memory_current_bytes": 11534336, + "cpu_usage_usec": 847462 + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 46.318864849999954, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 95272960, + "cpu_usage_usec": 5507669 + }, + "prowlarr": { + "memory_current_bytes": 9932800, + "cpu_usage_usec": 7494719 + }, + "qbittorrent": { + "memory_current_bytes": 11202560, + "cpu_usage_usec": 847462 + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 46.419757123000636, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 95068160, + "cpu_usage_usec": 5507669 + }, + "prowlarr": { + "memory_current_bytes": 9646080, + "cpu_usage_usec": 7495134 + }, + "qbittorrent": { + "memory_current_bytes": 11202560, + "cpu_usage_usec": 847462 + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 46.52059735900002, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 94867456, + "cpu_usage_usec": 5507669 + }, + "prowlarr": { + "memory_current_bytes": 9609216, + "cpu_usage_usec": 7495134 + }, + "qbittorrent": { + "memory_current_bytes": 11202560, + "cpu_usage_usec": 847462 + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 46.62141608999991, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 94806016, + "cpu_usage_usec": 5507669 + }, + "prowlarr": { + "memory_current_bytes": 9420800, + "cpu_usage_usec": 7495134 + }, + "qbittorrent": { + "memory_current_bytes": 10952704, + "cpu_usage_usec": 847462 + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 46.72225600799993, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 94806016, + "cpu_usage_usec": 5507709 + }, + "prowlarr": { + "memory_current_bytes": 9330688, + "cpu_usage_usec": 7495134 + }, + "qbittorrent": { + "memory_current_bytes": 10952704, + "cpu_usage_usec": 847462 + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 46.82269280700075, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 94806016, + "cpu_usage_usec": 5507709 + }, + "prowlarr": { + "memory_current_bytes": 9297920, + "cpu_usage_usec": 7495134 + }, + "qbittorrent": { + "memory_current_bytes": 10915840, + "cpu_usage_usec": 847462 + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 46.92310301700036, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 94773248, + "cpu_usage_usec": 5507709 + }, + "prowlarr": { + "memory_current_bytes": 8814592, + "cpu_usage_usec": 7495134 + }, + "qbittorrent": { + "memory_current_bytes": 10559488, + "cpu_usage_usec": 847462 + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 47.023501986000156, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 94773248, + "cpu_usage_usec": 5507709 + }, + "prowlarr": { + "memory_current_bytes": 8814592, + "cpu_usage_usec": 7495134 + }, + "qbittorrent": { + "memory_current_bytes": 10559488, + "cpu_usage_usec": 847462 + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 47.124069918000714, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 94584832, + "cpu_usage_usec": 5507709 + }, + "prowlarr": { + "memory_current_bytes": 8814592, + "cpu_usage_usec": 7495134 + }, + "qbittorrent": { + "memory_current_bytes": 10559488, + "cpu_usage_usec": 847462 + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 47.22458845800065, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 94793728, + "cpu_usage_usec": 5516561 + }, + "prowlarr": { + "memory_current_bytes": 8814592, + "cpu_usage_usec": 7495134 + }, + "qbittorrent": { + "memory_current_bytes": 10559488, + "cpu_usage_usec": 847462 + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 47.32500164800058, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 94662656, + "cpu_usage_usec": 5516561 + }, + "prowlarr": { + "memory_current_bytes": 8814592, + "cpu_usage_usec": 7495134 + }, + "qbittorrent": { + "memory_current_bytes": 10543104, + "cpu_usage_usec": 847462 + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 47.425826253000196, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 94662656, + "cpu_usage_usec": 5516561 + }, + "prowlarr": { + "memory_current_bytes": 8814592, + "cpu_usage_usec": 7495134 + }, + "qbittorrent": { + "memory_current_bytes": 10543104, + "cpu_usage_usec": 847462 + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 47.52671450200069, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 94662656, + "cpu_usage_usec": 5516561 + }, + "prowlarr": { + "memory_current_bytes": 8814592, + "cpu_usage_usec": 7495134 + }, + "qbittorrent": { + "memory_current_bytes": 10543104, + "cpu_usage_usec": 847462 + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 47.62777822499993, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 94662656, + "cpu_usage_usec": 5516561 + }, + "prowlarr": { + "memory_current_bytes": 8814592, + "cpu_usage_usec": 7495134 + }, + "qbittorrent": { + "memory_current_bytes": 10543104, + "cpu_usage_usec": 847462 + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 47.728197405000174, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 94662656, + "cpu_usage_usec": 5516592 + }, + "prowlarr": { + "memory_current_bytes": 8814592, + "cpu_usage_usec": 7495134 + }, + "qbittorrent": { + "memory_current_bytes": 10543104, + "cpu_usage_usec": 847462 + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 47.828610501000185, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 94662656, + "cpu_usage_usec": 5516592 + }, + "prowlarr": { + "memory_current_bytes": 8814592, + "cpu_usage_usec": 7495134 + }, + "qbittorrent": { + "memory_current_bytes": 10543104, + "cpu_usage_usec": 847462 + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 47.92952625900034, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 94662656, + "cpu_usage_usec": 5516592 + }, + "prowlarr": { + "memory_current_bytes": 8814592, + "cpu_usage_usec": 7495134 + }, + "qbittorrent": { + "memory_current_bytes": 10543104, + "cpu_usage_usec": 847462 + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 48.030295271000796, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 94662656, + "cpu_usage_usec": 5516592 + }, + "prowlarr": { + "memory_current_bytes": 8814592, + "cpu_usage_usec": 7495134 + }, + "qbittorrent": { + "memory_current_bytes": 10543104, + "cpu_usage_usec": 847462 + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 48.131271328000366, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 94662656, + "cpu_usage_usec": 5516592 + }, + "prowlarr": { + "memory_current_bytes": 8814592, + "cpu_usage_usec": 7495134 + }, + "qbittorrent": { + "memory_current_bytes": 10543104, + "cpu_usage_usec": 847462 + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 48.23170309300076, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 4288512, + "cpu_usage_usec": 5561550 + }, + "prowlarr": { + "memory_current_bytes": 8814592, + "cpu_usage_usec": 7495134 + }, + "qbittorrent": { + "memory_current_bytes": 10543104, + "cpu_usage_usec": 847462 + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 48.33262369300064, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 4145152, + "cpu_usage_usec": 5561550 + }, + "prowlarr": { + "memory_current_bytes": 8814592, + "cpu_usage_usec": 7495134 + }, + "qbittorrent": { + "memory_current_bytes": 10543104, + "cpu_usage_usec": 847462 + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 48.433408587000486, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 3166208, + "cpu_usage_usec": 5561550 + }, + "prowlarr": { + "memory_current_bytes": 8794112, + "cpu_usage_usec": 7495134 + }, + "qbittorrent": { + "memory_current_bytes": 10543104, + "cpu_usage_usec": 847462 + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 48.534600095000314, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 3166208, + "cpu_usage_usec": 5561550 + }, + "prowlarr": { + "memory_current_bytes": 8794112, + "cpu_usage_usec": 7495134 + }, + "qbittorrent": { + "memory_current_bytes": 10543104, + "cpu_usage_usec": 847462 + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 48.63538447800056, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 3166208, + "cpu_usage_usec": 5561550 + }, + "prowlarr": { + "memory_current_bytes": 8794112, + "cpu_usage_usec": 7495134 + }, + "qbittorrent": { + "memory_current_bytes": 10543104, + "cpu_usage_usec": 847462 + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 48.7361652970003, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 3166208, + "cpu_usage_usec": 5561550 + }, + "prowlarr": { + "memory_current_bytes": 8794112, + "cpu_usage_usec": 7495134 + }, + "qbittorrent": { + "memory_current_bytes": 10543104, + "cpu_usage_usec": 847462 + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 48.83701263600051, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 3166208, + "cpu_usage_usec": 5561550 + }, + "prowlarr": { + "memory_current_bytes": 8794112, + "cpu_usage_usec": 7495134 + }, + "qbittorrent": { + "memory_current_bytes": 10543104, + "cpu_usage_usec": 847462 + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 48.93782368800021, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 3166208, + "cpu_usage_usec": 5561550 + }, + "prowlarr": { + "memory_current_bytes": 8794112, + "cpu_usage_usec": 7495134 + }, + "qbittorrent": { + "memory_current_bytes": 10543104, + "cpu_usage_usec": 847462 + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 49.0386533410001, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 3166208, + "cpu_usage_usec": 5561550 + }, + "prowlarr": { + "memory_current_bytes": 8794112, + "cpu_usage_usec": 7495134 + }, + "qbittorrent": { + "memory_current_bytes": 10543104, + "cpu_usage_usec": 847462 + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 49.1394251720003, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 3166208, + "cpu_usage_usec": 5561550 + }, + "prowlarr": { + "memory_current_bytes": 8794112, + "cpu_usage_usec": 7495134 + }, + "qbittorrent": { + "memory_current_bytes": 10543104, + "cpu_usage_usec": 847462 + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 49.239843571000165, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 3166208, + "cpu_usage_usec": 5561550 + }, + "prowlarr": { + "memory_current_bytes": 8794112, + "cpu_usage_usec": 7495134 + }, + "qbittorrent": { + "unavailable": true + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 49.34015937500044, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 3153920, + "cpu_usage_usec": 5561550 + }, + "prowlarr": { + "unavailable": true + }, + "qbittorrent": { + "unavailable": true + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 49.440799180000795, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 3153920, + "cpu_usage_usec": 5561550 + }, + "prowlarr": { + "unavailable": true + }, + "qbittorrent": { + "unavailable": true + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 49.54145816200071, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 3153920, + "cpu_usage_usec": 5561550 + }, + "prowlarr": { + "unavailable": true + }, + "qbittorrent": { + "unavailable": true + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 49.64204459800021, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 3153920, + "cpu_usage_usec": 5561550 + }, + "prowlarr": { + "unavailable": true + }, + "qbittorrent": { + "unavailable": true + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 49.74289739699998, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 3153920, + "cpu_usage_usec": 5561550 + }, + "prowlarr": { + "unavailable": true + }, + "qbittorrent": { + "unavailable": true + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 49.84362213300028, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 3153920, + "cpu_usage_usec": 5561550 + }, + "prowlarr": { + "unavailable": true + }, + "qbittorrent": { + "unavailable": true + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 49.9442260550004, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 3153920, + "cpu_usage_usec": 5561550 + }, + "prowlarr": { + "unavailable": true + }, + "qbittorrent": { + "unavailable": true + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 50.044966735000344, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 3153920, + "cpu_usage_usec": 5561550 + }, + "prowlarr": { + "unavailable": true + }, + "qbittorrent": { + "unavailable": true + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 50.14570434899997, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 3153920, + "cpu_usage_usec": 5561550 + }, + "prowlarr": { + "unavailable": true + }, + "qbittorrent": { + "unavailable": true + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 50.246304095000596, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 3153920, + "cpu_usage_usec": 5561550 + }, + "prowlarr": { + "unavailable": true + }, + "qbittorrent": { + "unavailable": true + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 50.347008702000494, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 3153920, + "cpu_usage_usec": 5561550 + }, + "prowlarr": { + "unavailable": true + }, + "qbittorrent": { + "unavailable": true + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 50.44763092199992, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 3153920, + "cpu_usage_usec": 5561550 + }, + "prowlarr": { + "unavailable": true + }, + "qbittorrent": { + "unavailable": true + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 50.548072159000185, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 3153920, + "cpu_usage_usec": 5561550 + }, + "prowlarr": { + "unavailable": true + }, + "qbittorrent": { + "unavailable": true + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 50.64868657900024, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 3153920, + "cpu_usage_usec": 5561550 + }, + "prowlarr": { + "unavailable": true + }, + "qbittorrent": { + "unavailable": true + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 50.749304988000404, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 3153920, + "cpu_usage_usec": 5561550 + }, + "prowlarr": { + "unavailable": true + }, + "qbittorrent": { + "unavailable": true + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 50.85005036600069, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 3153920, + "cpu_usage_usec": 5561550 + }, + "prowlarr": { + "unavailable": true + }, + "qbittorrent": { + "unavailable": true + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 50.95069474800039, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 3153920, + "cpu_usage_usec": 5561550 + }, + "prowlarr": { + "unavailable": true + }, + "qbittorrent": { + "unavailable": true + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 51.051289622000695, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 3153920, + "cpu_usage_usec": 5561550 + }, + "prowlarr": { + "unavailable": true + }, + "qbittorrent": { + "unavailable": true + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 51.15194134800004, + "phase": "teardown", + "services": { + "jackett": { + "memory_current_bytes": 3153920, + "cpu_usage_usec": 5561550 + }, + "prowlarr": { + "unavailable": true + }, + "qbittorrent": { + "unavailable": true + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 51.252166611000575, + "phase": "teardown", + "services": { + "jackett": { + "unavailable": true + }, + "prowlarr": { + "unavailable": true + }, + "qbittorrent": { + "unavailable": true + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 51.3526065620008, + "phase": "teardown", + "services": { + "jackett": { + "unavailable": true + }, + "prowlarr": { + "unavailable": true + }, + "qbittorrent": { + "unavailable": true + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 51.453011129000515, + "phase": "teardown", + "services": { + "jackett": { + "unavailable": true + }, + "prowlarr": { + "unavailable": true + }, + "qbittorrent": { + "unavailable": true + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 51.55345749800017, + "phase": "teardown", + "services": { + "jackett": { + "unavailable": true + }, + "prowlarr": { + "unavailable": true + }, + "qbittorrent": { + "unavailable": true + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 51.65395027700015, + "phase": "teardown", + "services": { + "jackett": { + "unavailable": true + }, + "prowlarr": { + "unavailable": true + }, + "qbittorrent": { + "unavailable": true + }, + "flaresolverr": { + "unavailable": true + } + } + }, + { + "elapsed_seconds": 51.75415955000062, + "phase": "teardown", + "services": { + "jackett": { + "unavailable": true + }, + "prowlarr": { + "unavailable": true + }, + "qbittorrent": { + "unavailable": true + }, + "flaresolverr": { + "unavailable": true + } + } + } + ], + "trials": [ + { + "search_requests": 5, + "search_seconds": 8.520243766000021, + "download_seconds": 1.4918322479998096, + "payload_bytes": 16777216, + "sha256": "341aacac661ccb210720bedaa9ead5d668fe5ea41a73532fc147c71e34040df1" + }, + { + "search_requests": 5, + "search_seconds": 8.024731669000175, + "download_seconds": 1.4784432930000548, + "payload_bytes": 16777216, + "sha256": "341aacac661ccb210720bedaa9ead5d668fe5ea41a73532fc147c71e34040df1" + }, + { + "search_requests": 5, + "search_seconds": 8.019669891000376, + "download_seconds": 1.4765706400003182, + "payload_bytes": 16777216, + "sha256": "341aacac661ccb210720bedaa9ead5d668fe5ea41a73532fc147c71e34040df1" + } + ], + "metric": "memory.current bytes and cpu.stat usage_usec per cgroup; do not add to host PSS", + "errors": [], + "project": "helm-bench-62b4610f44", + "limits": { + "jackett": { + "memory_max": "268435456", + "cpu_max": "50000 100000", + "verified": true + }, + "prowlarr": { + "memory_max": "268435456", + "cpu_max": "50000 100000", + "verified": true + }, + "qbittorrent": { + "memory_max": "268435456", + "cpu_max": "50000 100000", + "verified": true + }, + "flaresolverr": { + "memory_max": "536870912", + "cpu_max": "50000 100000", + "verified": true + } + }, + "metadata": { + "engine": "podman", + "version": "5.8.9", + "project": "helm-bench-62b4610f44", + "containers": [ + { + "id": "5e50f574488e38298b6a51f6f99d3295df7d0dc3f189dd8c445f3314981e0d89", + "pid": 215251, + "image_id": "d39ca96018ff40dc20730d80f96195a784ec71b1fb647b86a6db1d01431c85c5", + "image": "sha256:d39ca96018ff40dc20730d80f96195a784ec71b1fb647b86a6db1d01431c85c5", + "memory_limit_bytes": 268435456, + "nano_cpus": 500000000, + "name": "helm-bench-62b4610f44-jackett" + }, + { + "id": "2daaffdf5455fa944dd6ee523b9d3343b1473106cec4fda6d020c51ee48d2d50", + "pid": 215390, + "image_id": "48cd1d7e2a8b73178829c03e0606b8c820d067d6f7d7d92328573eb311e3e521", + "image": "sha256:48cd1d7e2a8b73178829c03e0606b8c820d067d6f7d7d92328573eb311e3e521", + "memory_limit_bytes": 268435456, + "nano_cpus": 500000000, + "name": "helm-bench-62b4610f44-prowlarr" + }, + { + "id": "d9e3bc05e816c83b89d5edda051211870ddf5b4f9121e83d00d0911de06c605d", + "pid": 215609, + "image_id": "66af76dac14d022d43e060ee2970bf149309b463346c45a37fa844a6265bcdc0", + "image": "sha256:66af76dac14d022d43e060ee2970bf149309b463346c45a37fa844a6265bcdc0", + "memory_limit_bytes": 268435456, + "nano_cpus": 500000000, + "name": "helm-bench-62b4610f44-qbittorrent" + }, + { + "id": "aaf1746c6313245a93687cdaa0545b78078903ed9dc84cdfb9ba5d75429f21d8", + "pid": 215840, + "image_id": "894893ed4d4557764df3e74d27c5bc1b3944e5a33ed410e62ab7c744b348f415", + "image": "sha256:894893ed4d4557764df3e74d27c5bc1b3944e5a33ed410e62ab7c744b348f415", + "memory_limit_bytes": 536870912, + "nano_cpus": 500000000, + "name": "helm-bench-62b4610f44-flaresolverr" + } + ], + "attachment": "read_only; local workload does not exercise these services" + }, + "all_containers_stopped": true, + "success": true, + "cleanup_errors": [] +} diff --git a/pyproject.toml b/pyproject.toml index 34da5c6..b7ea7dd 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -8,7 +8,7 @@ version = "0.10.0" authors = [ { name="Piratebird" }, ] -description = "Torrent automation MVP" +description = "The Helm torrent automation CLI (unrelated to Kubernetes Helm)" readme = "README.md" requires-python = ">=3.8" classifiers = [ @@ -19,11 +19,11 @@ classifiers = [ dependencies = [ "requests>=2.31.0", "python-dotenv>=1.0.0", - "beautifulsoup4>=4.12.0", - "libtorrent>=2.0.0,<2.1.0" + "beautifulsoup4>=4.12.0" ] [project.optional-dependencies] +download = ["libtorrent>=2.0.0,<2.1.0"] dev = [ "pytest", "pytest-cov", @@ -35,11 +35,14 @@ dev = [ "Homepage" = "https://github.com/Piratebird/helm" [project.scripts] -helm = "helm.cli:main" +helm-torrent = "helm.cli:main" [tool.setuptools.packages.find] where = ["src"] +[tool.pytest.ini_options] +pythonpath = ["src"] + [tool.ruff] line-length = 120 target-version = "py38" diff --git a/requirements.txt b/requirements.txt index e1669e8..4a7051d 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,3 +1,3 @@ requests>=2.31.0 python-dotenv>=1.0.0 -libtorrent +beautifulsoup4>=4.12.0 diff --git a/setup.sh b/setup.sh index afc0f8b..519ef85 100755 --- a/setup.sh +++ b/setup.sh @@ -918,8 +918,8 @@ if [ "$run_mode" == "2" ]; then else run_compose stop || true fi - echo "Generating helm launcher script..." - cat << EOF > helm.sh + echo "Generating helm-torrent launcher script..." + cat << EOF > helm-torrent.sh #!/usr/bin/env bash ARGS="\$@" if [[ "\$*" != *"--oneshot"* ]] && [[ "\$*" != *"-o"* ]]; then @@ -933,12 +933,12 @@ else $COMPOSE_CMD --profile cli run --rm cli \$ARGS fi EOF - chmod +x helm.sh + chmod +x helm-torrent.sh echo "Containers stopped. Helm will spin them up automatically when you trigger a download." echo "" echo "To start using the app in its isolated CLI container, run:" - echo " ./helm.sh --oneshot" + echo " ./helm-torrent.sh --oneshot" echo "===========================================" else echo "Containers are left running 24/7 in the background." diff --git a/src/helm/cli.py b/src/helm/cli.py index 5514082..e7b5a3d 100644 --- a/src/helm/cli.py +++ b/src/helm/cli.py @@ -1,4 +1,5 @@ import argparse +import importlib import json import os import re @@ -9,18 +10,29 @@ from dotenv import load_dotenv +from helm.core.config_manager import CONTENT_PROFILES, NEGATIVE_KEYWORDS, load_config, worker_count # noqa: E402 +from helm.core.logger import configure_logging, tail_log # noqa: E402 from helm.core.secret_manager import get_secret, get_secrets_file # noqa: E402 +from helm.ui.colors import C_ERR, C_LOGO, C_RST, C_SUB, C_TEXT, logo # noqa: E402 -load_dotenv(get_secrets_file()) -from helm.core.config_manager import CONTENT_PROFILES, NEGATIVE_KEYWORDS, load_config # noqa: E402 -from helm.core.config_wizard import ensure_config # noqa: E402 -from helm.core.logger import get_logger # noqa: E402 -from helm.core.oneshot import wait_for_download # noqa: E402 -from helm.core.qbittorrent_client import add_magnet # noqa: E402 -from helm.core.torrent_filter import dedupe, filter_items # noqa: E402 -from helm.ui.colors import C_ERR, C_LOGO, C_RST, C_SUB, C_TEXT, logo # noqa: E402 -from helm.ui.tui import animated_search, interactive_indexer_selector, interactive_selector # noqa: E402 +def _lazy(module, name): + """Defer a heavy import so --help and headless commands start quickly.""" + + def call(*args, **kwargs): + return getattr(importlib.import_module(module), name)(*args, **kwargs) + + return call + + +add_magnet = _lazy("helm.core.qbittorrent_client", "add_magnet") +animated_search = _lazy("helm.ui.tui", "animated_search") +dedupe = _lazy("helm.core.torrent_filter", "dedupe") +ensure_config = _lazy("helm.core.config_wizard", "ensure_config") +filter_items = _lazy("helm.core.torrent_filter", "filter_items") +interactive_indexer_selector = _lazy("helm.ui.tui", "interactive_indexer_selector") +interactive_selector = _lazy("helm.ui.tui", "interactive_selector") +wait_for_download = _lazy("helm.core.oneshot", "wait_for_download") def _send_magnet(selected, lite_mode, json_mode=False, success_msg="Torrent sent successfully :)"): @@ -28,18 +40,21 @@ def _send_magnet(selected, lite_mode, json_mode=False, success_msg="Torrent sent if lite_mode: from helm.core.lite_downloader import download_magnet - download_magnet(selected.link) - return + return download_magnet(selected.link) try: add_magnet(selected.link) if not json_mode: print(f"{C_TEXT}{success_msg}{C_RST}") except Exception as e: - print(f"\n\033[33m[!] qBittorrent not available ({e}). Falling back to LITE MODE downloader...\033[0m\n") + print( + f"\n\033[33m[!] qBittorrent not available ({e}). Falling back to LITE MODE downloader...\033[0m\n", + file=sys.stderr, + ) from helm.core.lite_downloader import download_magnet - download_magnet(selected.link) + return download_magnet(selected.link) + return True def _cmd_status(): @@ -80,15 +95,31 @@ def _cmd_status(): print("---------------") -def main(): +def build_parser(): base_parser = argparse.ArgumentParser(add_help=False) global_opts = base_parser.add_argument_group("Global Options") global_opts.add_argument( "--config-dir", type=str, default=argparse.SUPPRESS, help="Override the configuration directory" ) global_opts.add_argument("--state-dir", type=str, default=argparse.SUPPRESS, help="Override the state directory") + global_opts.add_argument( + "--daemon", + action="store_true", + default=argparse.SUPPRESS, + help="Run a headless command in the background, or start a detached tmux UI", + ) + global_opts.add_argument( + "--session", default=argparse.SUPPRESS, help="Create a named reconnectable tmux UI session" + ) global_opts.add_argument("--status", action="store_true", help="List running containers and their Web UI URLs") global_opts.add_argument("--dl-dir", type=str, default=argparse.SUPPRESS, help="Override the downloads directory") + global_opts.add_argument( + "--lite-workers", + type=int, + choices=range(1, 13), + default=argparse.SUPPRESS, + help="Maximum concurrent Lite processes (default: HELM_LITE_WORKERS or 6)", + ) global_opts.add_argument( "-o", "--oneshot", @@ -108,7 +139,8 @@ def main(): ) parser = argparse.ArgumentParser( - description="Helm - Torrent automation MVP", + prog="helm-torrent", + description="The Helm - Torrent automation CLI", formatter_class=argparse.RawTextHelpFormatter, parents=[base_parser], ) @@ -131,7 +163,9 @@ def main(): "search", help="Search and download via CLI flags without TUI", parents=[base_parser] ) search_parser.add_argument("query", type=str, nargs="+", help="Search query") - search_parser.add_argument("-t", "--type", type=str, default="video", help="Content type (video, games, etc.)") + search_parser.add_argument( + "-t", "--type", type=str.lower, choices=sorted(CONTENT_PROFILES), default="video", help="Content type" + ) search_parser.add_argument( "-a", "--auto", action="store_true", help="Automatically select and send the top torrent" ) @@ -151,8 +185,42 @@ def main(): "bug-report", help="Zip the config and logs to the Desktop for reporting", parents=[base_parser] ) - # Parse arguments - args, unknown = parser.parse_known_args() + download_parser = subparsers.add_parser( + "download", help="Download a magnet, detail URL or .torrent file", parents=[base_parser] + ) + download_parser.add_argument("source") + watch_parser = subparsers.add_parser( + "watch", help="Queue stable .torrent and magnet files from a directory", parents=[base_parser] + ) + watch_parser.add_argument("directory") + watch_parser.add_argument("--interval", type=float, default=1) + watch_parser.add_argument("--once", action="store_true", help="Scan once and submit queued downloads") + watch_parser.add_argument( + "--enqueue-only", action="store_true", help="Leave processing to a running serve/watch worker" + ) + for name in ("serve", "files"): + service_parser = subparsers.add_parser( + name, + help="Authenticated job API and completed-file streaming" + if name == "serve" + else "Read-only completed-file server", + parents=[base_parser], + ) + service_parser.add_argument("--host", default="127.0.0.1") + service_parser.add_argument("--port", type=int, default=8765) + attach_parser = subparsers.add_parser("attach", help="Reconnect to a named tmux UI", parents=[base_parser]) + attach_parser.add_argument("name", nargs="?", default="main") + daemon_parser = subparsers.add_parser( + "daemon", help="List or stop managed background commands", parents=[base_parser] + ) + daemon_parser.add_argument("action", choices=["status", "stop"]) + daemon_parser.add_argument("id", nargs="?") + + return parser + + +def _parse_args(parser): + args = parser.parse_args() if getattr(args, "status", False): args.command = "status" @@ -167,7 +235,9 @@ def main(): args.oneshot = False if args.command == "search": - args.query = " ".join(args.query) + args.query = " ".join(args.query).strip() + if not args.query: + parser.error("search query must not be empty") else: args.query = None args.type = "video" @@ -183,52 +253,113 @@ def main(): if getattr(args, "dl_dir", None): os.environ["HELM_DL_DIR"] = os.path.abspath(args.dl_dir) - get_logger("") # Initialize root logger after directory overrides - - if args.command == "status": - # Container status is a read-only query: it must never spin up the - # ephemeral stack, prompt for config, or require an API key. Reap it - # as early as possible so agents can call it non-interactively. - _cmd_status() - return - - if args.command == "init": - from helm.core.init_env import bootstrap_env - - try: - bootstrap_env() - except (KeyboardInterrupt, EOFError): - print(f"\n{C_SUB}later bozo!{C_RST}") - raise SystemExit(0) from None - - if args.command == "paths": + try: + workers = worker_count(getattr(args, "lite_workers", None)) + except ValueError as error: + parser.error(str(error)) + os.environ["HELM_LITE_WORKERS"] = str(workers) + + load_dotenv(get_secrets_file()) + configure_logging() + return args + + +def _dispatch_background(args, parser): + """Handle tmux and daemon management commands; return True when one ran.""" + daemon_mode = getattr(args, "daemon", False) + session = getattr(args, "session", None) + if args.command == "attach": + from helm.core.runtime import attach_session + + attach_session(args.name) + return True + if args.command == "daemon": + from helm.core.runtime import daemon_records, stop_daemon + + if args.action == "status": + print(json.dumps(daemon_records(), indent=2)) + elif not args.id: + parser.error("daemon stop requires an id") + else: + print(json.dumps({"stopped": stop_daemon(args.id)})) + return True + if session or (daemon_mode and args.command == "ui"): + if args.command not in ("ui", "indexers"): + parser.error("--session is supported for ui/indexers; headless commands use --daemon") + from helm.core.runtime import start_session + + start_session(session or "main", sys.argv[1:]) + return True + if daemon_mode: + if args.command not in ("search", "download", "watch", "serve", "files"): + parser.error("--daemon requires a headless command or ui") + if args.command == "search" and not (args.auto or args.json): + parser.error("background searches require --auto or --json") + from helm.core.runtime import start_daemon + + start_daemon(sys.argv[1:]) + return True + return False + + +def _run_download(source, lite): + """Run one queued download, also waiting if a service worker already owns it.""" + from helm.core.jobs import JobStore, process_one + + store = JobStore() + job = store.enqueue(source, lite) + while store.get(job["id"])["status"] in ("pending", "running"): + if not process_one(store): + time.sleep(1) + final = store.get(job["id"]) + print(json.dumps({"id": final["id"], "status": final["status"], "error": final["error"]})) + return 0 if final["status"] in ("succeeded", "submitted") else 1 + + +def _run_headless(args, parser): + config = load_config() + lite = args.lite or config.get("LITE_MODE_ONLY", False) + if not lite and not (get_secret("QB_PASSWORD") or config.get("QB_WEBUI") or os.getenv("QB_WEBUI")): + lite = True + if args.command == "watch": + from helm.core.watch import run_watch + + return run_watch(args.directory, lite, args.interval, args.once, args.enqueue_only) + if args.command in ("serve", "files"): + if not 0 <= args.port <= 65535: + parser.error("port must be between 0 and 65535") + from helm.core.server import run_server + + return run_server(args.host, args.port, lite, read_only=args.command == "files") + return _run_download(args.source, lite) + + +def _run_utility(command): + if command == "paths": from helm.core.config_manager import get_config_dir, get_dl_dir, get_log_dir print("\033[1m\033[36mHelm Data Locations:\033[0m") print(f" Configuration: {get_config_dir()}") print(f" State/Logs: {get_log_dir()}") print(f" Downloads: {get_dl_dir()}") - raise SystemExit(0) from None + return - if args.command == "logs": + if command == "logs": from helm.core.config_manager import get_log_dir log_file = os.path.join(get_log_dir(), "helm.log") if os.path.exists(log_file): print("--- Last 20 lines ---") try: - with open(log_file, "r", encoding="utf-8") as f: - lines = f.readlines() - for line in lines[-20:]: - sys.stdout.write(line) - print("\n---------------------") + sys.stdout.write(tail_log(log_file)) + print("\n---------------------") except Exception as e: print(f"Could not read log file: {e}") else: print("Log file does not exist yet.") - raise SystemExit(0) from None + return - if args.command == "bug-report": + if command == "bug-report": import zipfile from helm.core.config_manager import get_config_file, get_log_dir @@ -249,11 +380,46 @@ def main(): cfg_data = json.load(f) zipf.writestr("config.json", json.dumps(redact_config(cfg_data), indent=4)) except Exception: - zipf.write(config_file, arcname="config.json") + print("Could not redact config.json; omitting it from the bug report.", file=sys.stderr) if os.path.exists(log_file): - zipf.write(log_file, arcname="helm.log") + from helm.core.secret_manager import redact_text + + with open(log_file, "r", encoding="utf-8", errors="replace") as source, zipf.open( + "helm.log", "w" + ) as target: + for line in source: + target.write(redact_text(line).encode("utf-8")) print(f"Bug report successfully created at: {zip_path}") print("Please attach this zip file when creating an issue on GitHub.") + return + + +def main(): + parser = build_parser() + args = _parse_args(parser) + if _dispatch_background(args, parser): + return + if args.command in ("watch", "serve", "files", "download"): + raise SystemExit(_run_headless(args, parser)) + + if args.command == "status": + # Container status is a read-only query: it must never spin up the + # ephemeral stack, prompt for config, or require an API key. Reap it + # as early as possible so agents can call it non-interactively. + _cmd_status() + return + + if args.command == "init": + from helm.core.init_env import bootstrap_env + + try: + bootstrap_env() + except (KeyboardInterrupt, EOFError): + print(f"\n{C_SUB}later bozo!{C_RST}") + raise SystemExit(0) from None + + if args.command in ("paths", "logs", "bug-report"): + _run_utility(args.command) raise SystemExit(0) from None if not args.lite: @@ -266,7 +432,7 @@ def main(): and not os.getenv("PROWLARR_API_KEY") and not get_secret("PROWLARR_API_KEY") ): - if args.json: + if args.json or os.environ.get("HELM_DAEMONIZED") == "1": # Machine-readable output must never interleave prompts; fall # back to Lite Mode silently instead of asking the user. args.lite = True @@ -297,107 +463,118 @@ def main(): else: ensure_config() - if args.oneshot: - from helm.core.oneshot import spin_up_oneshot, teardown_oneshot + # Lite searches never start a container stack, even with --oneshot. + args.oneshot = args.oneshot and not args.lite + from helm.core.oneshot import spin_up_oneshot, teardown_oneshot - try: - spin_up_oneshot() - except KeyboardInterrupt: - print(f"\n{C_SUB}later bozo!{C_RST}") + started = False + + def cleanup(): + nonlocal started + if started: + started = False + teardown_oneshot() + elif not args.oneshot and not args.lite: + # Ctrl-E explicitly requests cleanup for an existing permanent stack. teardown_oneshot() - raise SystemExit(0) from None - if args.command == "indexers": - if args.lite: - print(f"{C_ERR}Cannot manage Indexers in Lite Mode.{C_RST}", file=sys.stderr) - raise SystemExit(1) from None - ensure_config() + try: + if args.oneshot: + # Mark ownership before startup so partial startup is cleaned up too. + started = True + spin_up_oneshot() + _run_session(args, cleanup) + finally: + if started: + cleanup() - config = load_config() - use_prowlarr = getattr(args, "prowlarr", False) - use_jackett = getattr(args, "jackett", False) +def _manage_indexers(args): + if args.lite: + print(f"{C_ERR}Cannot manage Indexers in Lite Mode.{C_RST}", file=sys.stderr) + raise SystemExit(1) from None + ensure_config() - if not use_prowlarr and not use_jackett: - manager_type = config.get("INDEXER_MANAGER", "jackett") - elif use_prowlarr: - manager_type = "prowlarr" - else: - manager_type = "jackett" + config = load_config() - try: - if manager_type == "prowlarr": - from helm.core.indexer_manager import ProwlarrManager + use_prowlarr = getattr(args, "prowlarr", False) + use_jackett = getattr(args, "jackett", False) - manager = ProwlarrManager() - mgr_name = "Prowlarr" - else: - from helm.core.indexer_manager import JackettManager + if not use_prowlarr and not use_jackett: + manager_type = config.get("INDEXER_MANAGER", "jackett") + elif use_prowlarr: + manager_type = "prowlarr" + else: + manager_type = "jackett" - manager = JackettManager() - mgr_name = "Jackett" - except Exception as e: - print(f"{C_ERR}Failed to initialize Manager: {e}{C_RST}", file=sys.stderr) - raise SystemExit(1) from None + try: + if manager_type == "prowlarr": + from helm.core.indexer_manager import ProwlarrManager - sys.stdout.write(f"{C_LOGO}Fetching indexers from {mgr_name}...{C_RST}\r\n") - sys.stdout.flush() - all_indexers = manager.get_all_indexers() + manager = ProwlarrManager() + mgr_name = "Prowlarr" + else: + from helm.core.indexer_manager import JackettManager - while True: - try: - selected_indexer = interactive_indexer_selector(all_indexers) - if selected_indexer: - if selected_indexer["configured"]: - sys.stdout.write(f"\r\n{C_TEXT}Removing {selected_indexer['title']}...{C_RST}\r\n") + manager = JackettManager() + mgr_name = "Jackett" + except Exception as e: + print(f"{C_ERR}Failed to initialize Manager: {e}{C_RST}", file=sys.stderr) + raise SystemExit(1) from None + + sys.stdout.write(f"{C_LOGO}Fetching indexers from {mgr_name}...{C_RST}\r\n") + sys.stdout.flush() + all_indexers = manager.get_all_indexers() + + while True: + try: + selected_indexer = interactive_indexer_selector(all_indexers) + if selected_indexer: + if selected_indexer["configured"]: + sys.stdout.write(f"\r\n{C_TEXT}Removing {selected_indexer['title']}...{C_RST}\r\n") + sys.stdout.flush() + try: + manager.remove_indexer(selected_indexer["id"]) + selected_indexer["configured"] = False + except Exception as e: + sys.stdout.write(f"\r\n{C_ERR}Failed to remove: {e}{C_RST}\r\n") + sys.stdout.flush() + time.sleep(2) + else: + if selected_indexer.get("type", "public") != "public": + sys.stdout.write( + f"\r\n{C_ERR}Cannot add {selected_indexer['type']} trackers via CLI as they require credentials. Please use the Jackett Web UI ({manager.url}).{C_RST}\r\n" + ) + sys.stdout.flush() + time.sleep(3) + else: + sys.stdout.write(f"\r\n{C_TEXT}Adding {selected_indexer['title']}...{C_RST}\r\n") sys.stdout.flush() try: - manager.remove_indexer(selected_indexer["id"]) - selected_indexer["configured"] = False + manager.add_indexer(selected_indexer["id"]) + selected_indexer["configured"] = True except Exception as e: - sys.stdout.write(f"\r\n{C_ERR}Failed to remove: {e}{C_RST}\r\n") - sys.stdout.flush() - time.sleep(2) - else: - if selected_indexer.get("type", "public") != "public": - sys.stdout.write( - f"\r\n{C_ERR}Cannot add {selected_indexer['type']} trackers via CLI as they require credentials. Please use the Jackett Web UI ({manager.url}).{C_RST}\r\n" - ) + error_msg = str(e) + if "500" in error_msg: + error_msg = "Jackett rejected the default config. Please configure this indexer manually via the Jackett Web UI." + sys.stdout.write(f"\r\n{C_ERR}Failed to add: {error_msg}{C_RST}\r\n") sys.stdout.flush() time.sleep(3) - else: - sys.stdout.write(f"\r\n{C_TEXT}Adding {selected_indexer['title']}...{C_RST}\r\n") - sys.stdout.flush() - try: - manager.add_indexer(selected_indexer["id"]) - selected_indexer["configured"] = True - except Exception as e: - error_msg = str(e) - if "500" in error_msg: - error_msg = "Jackett rejected the default config. Please configure this indexer manually via the Jackett Web UI." - sys.stdout.write(f"\r\n{C_ERR}Failed to add: {error_msg}{C_RST}\r\n") - sys.stdout.flush() - time.sleep(3) - except KeyboardInterrupt: - sys.stdout.write(f"\n{C_SUB}Exiting indexer management.{C_RST}\n") - sys.stdout.flush() - try: - choice = ( - input(f"\033[1m{C_TEXT}? Would you like to proceed to search? [Y/n]:{C_RST} ").strip().lower() - ) - if choice == "n": - if args.oneshot: - from helm.core.oneshot import teardown_oneshot + except KeyboardInterrupt: + sys.stdout.write(f"\n{C_SUB}Exiting indexer management.{C_RST}\n") + sys.stdout.flush() + try: + choice = input(f"\033[1m{C_TEXT}? Would you like to proceed to search? [Y/n]:{C_RST} ").strip().lower() + if choice == "n": + raise SystemExit(0) from None + except (KeyboardInterrupt, EOFError): + print(f"\n{C_SUB}later bozo!{C_RST}") + raise SystemExit(0) from None - teardown_oneshot() - raise SystemExit(0) from None - except (KeyboardInterrupt, EOFError): - print(f"\n{C_SUB}later bozo!{C_RST}") - if args.oneshot: - from helm.core.oneshot import teardown_oneshot - teardown_oneshot() - raise SystemExit(0) from None +def _run_session(args, teardown_oneshot): + if args.command == "indexers": + _manage_indexers(args) mode_str = " (ONE-SHOT MODE)" if args.oneshot else "" @@ -422,8 +599,6 @@ def main(): search_query = input(f"\033[1m{C_TEXT}? What would you like to search for:{C_RST} ").strip() except (KeyboardInterrupt, EOFError): print(f"\n{C_SUB}later bozo!{C_RST}") - if args.oneshot: - teardown_oneshot() raise SystemExit(0) from None if not search_query: @@ -437,8 +612,6 @@ def main(): ) except KeyboardInterrupt: print(f"\n{C_SUB}later bozo!{C_RST}") - if args.oneshot: - teardown_oneshot() raise SystemExit(0) from None if selected_cats == "BACK": @@ -478,8 +651,6 @@ def main(): ) except KeyboardInterrupt: print(f"\n{C_SUB}later bozo!{C_RST}") - if args.oneshot: - teardown_oneshot() raise SystemExit(0) from None source_name = "Lite mode" if args.lite else "Jackett & Lite" @@ -495,15 +666,23 @@ def main(): if not filtered: if args.json: print(json.dumps([])) - if args.oneshot: - teardown_oneshot() raise SystemExit(1) from None else: print(f"\n{C_ERR}No torrents were found :({C_RST}", file=sys.stderr) + if not all_items and args.lite: + print( + "Lite sources may be unreachable or have no matches. " + "Try a specific query and check 'helm-torrent logs' for source errors.", + file=sys.stderr, + ) + elif all_items: + print( + f"All {len(all_items)} results were removed by filters " + f"(minimum seeders: {min_seeds}). Review min_seeds and content type.", + file=sys.stderr, + ) # If we have arguments, we exit. Else we go back to prompt. if args.query: - if args.oneshot: - teardown_oneshot() raise SystemExit(1) from None else: input("Press Enter to try again...") @@ -525,16 +704,17 @@ def main(): ] print(json.dumps(json_output, indent=2)) sys.stdout.flush() - if args.oneshot: - teardown_oneshot() raise SystemExit(0) from None if args.auto: selected = filtered[0] - _send_magnet(selected, args.lite, args.json, success_msg="Top torrent sent successfully :)") + if ( + _send_magnet(selected, args.lite, args.json, success_msg="Top torrent sent successfully :)") + is False + ): + raise SystemExit(1) if args.oneshot and not args.lite: wait_for_download() - teardown_oneshot() raise SystemExit(0) from None state = "RESULTS" @@ -556,15 +736,17 @@ def main(): continue print() - _send_magnet(selected, args.lite, args.json) + if _send_magnet(selected, args.lite, args.json) is False: + raise SystemExit(1) if (args.oneshot or do_teardown) and not args.lite: wait_for_download() - teardown_oneshot() + if not args.oneshot: + teardown_oneshot() break except KeyboardInterrupt: print(f"\n{C_SUB}later bozo!{C_RST}") - if args.oneshot or do_teardown: + if do_teardown and not args.oneshot and not args.lite: try: teardown_oneshot() except Exception: @@ -579,23 +761,9 @@ def main(): import sys print("\n\033[33m[!] Process interrupted by user.\033[0m", file=sys.stderr) - if "-o" in sys.argv or "--oneshot" in sys.argv: - try: - from helm.core.oneshot import teardown_oneshot - - teardown_oneshot() - except Exception: - pass sys.exit(130) except Exception as e: import sys print(f"\n\033[31m[!] An unexpected error occurred: {e}\033[0m", file=sys.stderr) - if "-o" in sys.argv or "--oneshot" in sys.argv: - try: - from helm.core.oneshot import teardown_oneshot - - teardown_oneshot() - except Exception: - pass sys.exit(1) diff --git a/src/helm/core/benchmark.py b/src/helm/core/benchmark.py new file mode 100644 index 0000000..fac245e --- /dev/null +++ b/src/helm/core/benchmark.py @@ -0,0 +1,437 @@ +"""Repeatable Linux PSS sampling of local search and loopback BitTorrent work. + +No public trackers or external torrent content are used. Optional container +attachment is read-only and is reported separately from the local workload. +""" + +import argparse +import gc +import hashlib +import json +import os +import platform +import resource +import select +import statistics +import subprocess +import sys +import tempfile +import time +from pathlib import Path + +from helm.core.runtime import child_environment + +ENGINE_NAMES = {"dockerd", "containerd", "conmon", "pasta", "slirp4netns", "rootlesskit"} + + +def parse_pss(text): + for line in text.splitlines(): + fields = line.split() + if fields and fields[0] == "Pss:": + if len(fields) != 3 or fields[2] != "kB": + raise ValueError("Expected Pss in Linux kB units") + return int(fields[1]) * 1024 + raise ValueError("Pss is missing") + + +def process_snapshot(proc_root=Path("/proc")): + processes = {} + for directory in proc_root.iterdir(): + if not directory.name.isdigit(): + continue + try: + stat = (directory / "stat").read_text() + tail = stat.rsplit(")", 1)[1].split() + name = (directory / "comm").read_text().strip() + processes[int(directory.name)] = (int(tail[1]), name) + except (OSError, ValueError, IndexError): + continue + return processes + + +def descendants(roots, processes): + selected = set(roots) + while True: + more = {pid for pid, (parent, _) in processes.items() if parent in selected} + combined = selected | more + if combined == selected: + return selected + selected = combined + + +def memory_sample(root_pid, container_pids=(), include_engine=False, proc_root=Path("/proc")): + processes = process_snapshot(proc_root) + workload = descendants([root_pid], processes) + stack = descendants(container_pids, processes) - workload + engine_roots = [pid for pid, (_, name) in processes.items() if name in ENGINE_NAMES] if include_engine else [] + overhead = descendants(engine_roots, processes) - workload - stack + groups = {"workload": workload, "attached_stack": stack, "engine": overhead} + sample = {"missing_pids": []} + for name, pids in groups.items(): + total = 0 + for pid in pids: + try: + total += parse_pss((proc_root / str(pid) / "smaps_rollup").read_text()) + except (OSError, ValueError): + if pid in processes: + sample["missing_pids"].append(pid) + sample[name + "_pss_bytes"] = total + sample["accounted_pss_bytes"] = sum(sample[name + "_pss_bytes"] for name in groups) + sample["complete"] = not sample["missing_pids"] + return sample + + +def summarize(samples): + summary = {} + for phase in sorted({sample["phase"] for sample in samples}): + selected = [sample for sample in samples if sample["phase"] == phase] + summary[phase] = {"sample_count": len(selected), "incomplete_samples": sum(not s["complete"] for s in selected)} + for metric in ("workload_pss_bytes", "attached_stack_pss_bytes", "engine_pss_bytes", "accounted_pss_bytes"): + values = [sample[metric] for sample in selected if sample["complete"]] + summary[phase][metric] = { + "median": statistics.median(values) if values else None, + "peak": max(values) if values else None, + } + return summary + + +def container_metadata(engine, project): + def command(*args): + return subprocess.run([engine, *args], check=True, capture_output=True, text=True, timeout=15).stdout + + ids = command("ps", "-q", "--filter", f"label=com.docker.compose.project={project}").split() + containers = [] + for identifier in ids: + raw = json.loads(command("inspect", identifier))[0] + host = raw.get("HostConfig", {}) + # Deliberately exclude environment variables, mounts and credentials. + containers.append( + { + "id": raw["Id"], + "pid": raw["State"]["Pid"], + "image_id": raw.get("Image"), + "image": raw.get("Config", {}).get("Image"), + "memory_limit_bytes": host.get("Memory"), + "nano_cpus": host.get("NanoCpus"), + "name": raw.get("Name"), + } + ) + return { + "engine": engine, + "version": command("version", "--format", "{{.Server.Version}}").strip(), + "project": project, + "containers": containers, + "attachment": "read_only; local workload does not exercise these services", + } + + +def cpu_usage(): + own = resource.getrusage(resource.RUSAGE_SELF) + children = resource.getrusage(resource.RUSAGE_CHILDREN) + return {"user": own.ru_utime + children.ru_utime, "system": own.ru_stime + children.ru_stime} + + +def cpu_delta(before): + after = cpu_usage() + user = max(0, after["user"] - before["user"]) + system = max(0, after["system"] - before["system"]) + return {"cpu_user_seconds": user, "cpu_system_seconds": system, "cpu_seconds": user + system} + + +def phase(name, **details): + print(json.dumps({"phase": name, **details}), flush=True) + + +def local_download(directory, size_bytes, timeout): + import libtorrent as lt + + seed_dir = directory / "seed" + dest_dir = directory / "download" + seed_dir.mkdir() + dest_dir.mkdir() + source = seed_dir / "payload.bin" + # Deterministic generated content, never downloaded from an external source. + block = bytes(range(256)) * 4096 + with source.open("wb") as stream: + remaining = size_bytes + while remaining: + data = block[: min(remaining, len(block))] + stream.write(data) + remaining -= len(data) + files = lt.file_storage() + lt.add_files(files, str(source)) + torrent = lt.create_torrent(files, 256 * 1024) + lt.set_piece_hashes(torrent, str(seed_dir)) + info = lt.torrent_info(torrent.generate()) + settings = { + "listen_interfaces": "127.0.0.1:0", + "enable_dht": False, + "enable_lsd": False, + "enable_upnp": False, + "enable_natpmp": False, + "enable_outgoing_utp": False, + "enable_incoming_utp": False, + "allow_multiple_connections_per_ip": True, + } + seed = lt.session(settings) + client = lt.session({**settings, "download_rate_limit": 2 * 1024 * 1024}) + try: + seed_params = lt.add_torrent_params() + seed_params.ti = info + seed_params.save_path = str(seed_dir) + seed_params.flags |= lt.torrent_flags.seed_mode + seed_params.flags &= ~lt.torrent_flags.paused + seed_params.flags &= ~lt.torrent_flags.auto_managed + seed.add_torrent(seed_params) + download_params = lt.add_torrent_params() + download_params.ti = info + download_params.save_path = str(dest_dir) + download_params.flags &= ~lt.torrent_flags.paused + download_params.flags &= ~lt.torrent_flags.auto_managed + handle = client.add_torrent(download_params) + deadline = time.monotonic() + timeout + while not handle.status().is_seeding: + if time.monotonic() >= deadline: + raise TimeoutError("Loopback transfer did not complete") + handle.connect_peer(("127.0.0.1", seed.listen_port())) + time.sleep(0.05) + # Flush data to disk before validating the generated payload. + handle.flush_cache() + time.sleep(0.1) + expected = hashlib.sha256(source.read_bytes()).hexdigest() + actual = hashlib.sha256((dest_dir / "payload.bin").read_bytes()).hexdigest() + if actual != expected: + raise ValueError("Downloaded payload checksum mismatch") + return {"payload_bytes": size_bytes, "sha256": actual, "libtorrent_version": binding_version(lt)} + finally: + seed.pause() + client.pause() + + +def binding_version(binding): + # Termux's binding exposes __version__ but no version attribute. + return getattr(binding, "__version__", None) or getattr(binding, "version", None) or "unknown" + + +def workload(payload_bytes, timeout, fixture_plugins=12, fixture_results=100, search_workers=6): + from helm.core.lite_plugin_loader import plugin_jobs + from helm.core.search_runner import run_searches + + with tempfile.TemporaryDirectory(prefix="helm-benchmark-workload-") as temporary: + directory = Path(temporary) + plugins = directory / "plugins" + plugins.mkdir() + for number in range(fixture_plugins): + (plugins / f"fixture{number}.py").write_text( + "from novaprinter import prettyPrinter\nclass fixture:\n" + f" name = 'Local fixture {number}'\n" + " def search(self, query, cat='all'):\n" + f" for index in range({fixture_results}):\n" + " prettyPrinter({'name': query + str(index), 'link': 'magnet:?xt=urn:btih:' + '%040x' % index, 'seeds': 10})\n" + ) + cpu = cpu_usage() + phase("idle") + time.sleep(0.4) + phase("idle", **cpu_delta(cpu)) + cpu = cpu_usage() + phase("search") + started = time.monotonic() + results = run_searches(plugin_jobs([str(plugins)]), "generated fixture", "all", max_workers=search_workers) + if len(results) != fixture_plugins * fixture_results: + raise RuntimeError("Fixture search failed") + phase("search", search_seconds=time.monotonic() - started, result_count=len(results), **cpu_delta(cpu)) + time.sleep(0.2) + cpu = cpu_usage() + phase("download") + started = time.monotonic() + details = local_download(directory, payload_bytes, timeout) + phase("download", download_seconds=time.monotonic() - started, **details, **cpu_delta(cpu)) + cpu = cpu_usage() + phase("teardown") + del results + gc.collect() + time.sleep(0.4) + phase("teardown", **cpu_delta(cpu)) + + +def run_trial( + interval, + payload_bytes, + timeout, + attachment=None, + include_engine=False, + fixture_plugins=12, + fixture_results=100, + search_workers=6, +): + environment = child_environment() + with tempfile.TemporaryDirectory(prefix="helm-benchmark-state-") as temporary: + environment.update(HELM_CONFIG_DIR=temporary + "/config", HELM_STATE_DIR=temporary + "/state") + process = subprocess.Popen( + [ + sys.executable, + "-m", + "helm.core.benchmark", + "--worker", + str(payload_bytes), + str(timeout), + str(fixture_plugins), + str(fixture_results), + str(search_workers), + ], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + env=environment, + start_new_session=True, + ) + from helm.core.search_runner import stop_worker + + samples, events = [], [] + current = "startup" + pending_bytes = b"" + started = time.monotonic() + pids = [item["pid"] for item in (attachment or {}).get("containers", [])] + try: + while process.poll() is None: + if time.monotonic() - started > timeout + 40: + raise TimeoutError("Benchmark workload exceeded its budget") + ready, _, _ = select.select([process.stdout], [], [], interval) + if ready: + pending_bytes += os.read(process.stdout.fileno(), 65536) + while b"\n" in pending_bytes: + line, pending_bytes = pending_bytes.split(b"\n", 1) + if line: + event = json.loads(line) + current = event["phase"] + events.append(event) + sample = memory_sample(process.pid, pids, include_engine) + samples.append({"elapsed_seconds": time.monotonic() - started, "phase": current, **sample}) + stdout, stderr = process.communicate(timeout=1) + for line in stdout.splitlines(): + events.append(json.loads(line)) + if process.returncode: + raise RuntimeError("Benchmark workload failed: " + stderr[-4096:]) + finally: + stop_worker(process) + # Post-exit sample measures reaped workload processes, not host engine shutdown. + samples.append( + { + "elapsed_seconds": time.monotonic() - started, + "phase": "exited", + **memory_sample(process.pid, pids, include_engine), + } + ) + return {"samples": samples, "events": events, "summary": summarize(samples)} + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--repeats", type=int, default=3) + parser.add_argument("--interval", type=float, default=0.05) + parser.add_argument("--payload-mib", type=int, default=4) + parser.add_argument("--timeout", type=float, default=20) + parser.add_argument("--fixture-plugins", type=int, default=12) + parser.add_argument("--fixture-results", type=int, default=100) + parser.add_argument("--search-workers", type=int, choices=range(1, 13), default=6) + parser.add_argument("--engine", choices=["docker", "podman"]) + parser.add_argument("--project", default="helm") + parser.add_argument("--include-engine", action="store_true") + args = parser.parse_args(argv) + if ( + args.repeats < 1 + or args.interval <= 0 + or args.payload_mib < 1 + or args.timeout <= 0 + or args.fixture_plugins < 1 + or args.fixture_results < 1 + ): + parser.error("repeats, interval, payload size and timeout must be positive") + if not Path("/proc/self/smaps_rollup").exists(): + parser.error("This PSS benchmark requires Linux /proc (including compatible Termux hosts)") + attachment = container_metadata(args.engine, args.project) if args.engine else None + try: + revision = subprocess.run( + ["git", "rev-parse", "HEAD"], capture_output=True, text=True, check=True + ).stdout.strip() + dirty = bool( + subprocess.run(["git", "status", "--porcelain"], capture_output=True, text=True, check=True).stdout + ) + except (OSError, subprocess.CalledProcessError): + revision, dirty = None, None + source_root = Path(__file__).resolve().parents[1] + fingerprints = { + str(path.relative_to(source_root)): hashlib.sha256(path.read_bytes()).hexdigest() + for path in sorted(source_root.rglob("*.py")) + } + cpu_model = platform.processor() + try: + for line in Path("/proc/cpuinfo").read_text().splitlines(): + if line.startswith("model name"): + cpu_model = line.partition(":")[2].strip() + break + except OSError: + pass + report = { + "schema_version": 1, + "mode": "local_fixture_search_and_loopback_bittorrent", + "metric": "PSS bytes; same metric for every component", + "environment": { + "platform": platform.platform(), + "python": sys.version, + "cpu_count": os.cpu_count(), + "cpu_model": cpu_model, + "source_sha256": fingerprints, + "cgroup_version": 2 if Path("/sys/fs/cgroup/cgroup.controllers").exists() else 1, + "revision": revision, + "dirty": dirty, + }, + "interval_seconds": args.interval, + "payload_bytes": args.payload_mib * 1024**2, + "fixture_plugins": args.fixture_plugins, + "fixture_results_per_plugin": args.fixture_results, + "search_workers": args.search_workers, + "attachment": attachment, + "include_engine": args.include_engine, + "limitations": [ + "Fixture search is offline; not a live indexer latency measurement", + "Download uses generated content and loopback peers; not internet swarm performance", + "PSS excludes filesystem cache and kernel/container networking allocations", + "Engine processes are whole-host shared costs when included", + "Attached stack is sampled read-only; its lifecycle is not exercised", + ], + } + report["trials"] = [ + run_trial( + args.interval, + args.payload_mib * 1024**2, + args.timeout, + attachment, + args.include_engine, + args.fixture_plugins, + args.fixture_results, + args.search_workers, + ) + for _ in range(args.repeats) + ] + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2) + "\n") + print( + json.dumps( + { + "output": str(args.output), + "trials": len(report["trials"]), + "summaries": [trial["summary"] for trial in report["trials"]], + }, + indent=2, + ) + ) + return 0 + + +if __name__ == "__main__": + if sys.argv[1:2] == ["--worker"]: + workload(int(sys.argv[2]), float(sys.argv[3]), int(sys.argv[4]), int(sys.argv[5]), int(sys.argv[6])) + else: + raise SystemExit(main()) diff --git a/src/helm/core/config_manager.py b/src/helm/core/config_manager.py index 4bb175c..77af526 100644 --- a/src/helm/core/config_manager.py +++ b/src/helm/core/config_manager.py @@ -22,6 +22,7 @@ "JACKETT_PASSWORD", "PROWLARR_API_KEY", "QB_PASSWORD", + "HELM_SERVER_TOKEN", ] ) @@ -149,6 +150,14 @@ def get_log_dir(): return os.path.join(base, "helm", "logs") +def get_state_dir(): + if "HELM_STATE_DIR" in os.environ: + return os.environ["HELM_STATE_DIR"] + if sys.platform == "darwin": + return os.path.expanduser("~/Library/Application Support/helm/state") + return os.path.dirname(get_log_dir()) + + def get_dl_dir(): if "HELM_DL_DIR" in os.environ: return os.environ["HELM_DL_DIR"] @@ -158,6 +167,21 @@ def get_dl_dir(): return os.path.expanduser("~/Downloads/helm") +def worker_count(value=None): + value = os.environ.get("HELM_LITE_WORKERS", "6") if value is None else value + try: + count = int(value) + except (TypeError, ValueError) as error: + raise ValueError("Lite worker count must be an integer from 1 to 12") from error + if not 1 <= count <= 12: + raise ValueError("Lite worker count must be an integer from 1 to 12") + return count + + +def get_qb_url(): + return (os.getenv("QB_WEBUI") or load_config().get("QB_WEBUI") or "http://localhost:18080").rstrip("/") + + def get_config_file(): config_dir = get_config_dir() os.makedirs(config_dir, exist_ok=True) diff --git a/src/helm/core/device_profile.py b/src/helm/core/device_profile.py new file mode 100644 index 0000000..1df6756 --- /dev/null +++ b/src/helm/core/device_profile.py @@ -0,0 +1,143 @@ +"""On-device PSS, CPU and cancellation measurements; honest battery accounting.""" + +import argparse +import json +import os +import platform +import tempfile +from pathlib import Path + +from helm.core.benchmark import run_trial +from helm.core.runtime import process_alive +from helm.core.search_runner import SearchJob, run_searches + + +def battery_sysfs(root=Path("/sys/class/power_supply")): + for directory in root.glob("*"): + try: + if (directory / "type").read_text().strip().lower() != "battery": + continue + sample = {"available": True} + for filename in ("energy_now", "charge_counter", "voltage_now", "current_now", "status"): + path = directory / filename + if path.is_file(): + value = path.read_text().strip() + sample[filename] = value if filename == "status" else int(value) + return sample + except (OSError, ValueError): + continue + return {"available": False, "reason": "No readable battery sysfs sensors"} + + +def battery_adb(text): + values = {} + for line in text.splitlines(): + key, separator, value = line.strip().partition(":") + if not separator or key in values: + continue + if key in ("Charge counter", "voltage", "status", "level", "temperature"): + try: + values[key] = int(value.strip()) + except ValueError: + pass + elif key in ("USB powered", "AC powered", "Wireless powered"): + values[key] = value.strip().lower() == "true" + return values + + +def energy_delta(before, after): + # Android charge counters are microampere-hours and dumpsys voltage is mV. + # Charging measurements are explicitly inconclusive, not app energy usage. + charging = any(before.get(key) or after.get(key) for key in ("USB powered", "AC powered", "Wireless powered")) + if charging or before.get("status") in (2, 5) or after.get("status") in (2, 5): + return {"consumption_wh": None, "reason": "Device charging; net battery change cannot measure workload energy"} + if before.get("status") != 3 or after.get("status") != 3: + return {"consumption_wh": None, "reason": "Discharging state was not verified"} + if all(key in before and key in after for key in ("Charge counter", "voltage")): + charge = before["Charge counter"] - after["Charge counter"] + voltage = (before["voltage"] + after["voltage"]) / 2 + if charge < 0: + return {"consumption_wh": None, "reason": "Charge counter increased"} + return { + "consumption_wh": charge * voltage / 1e9, + "scope": "Whole-device net battery estimate; not application-attributed", + } + return {"consumption_wh": None, "reason": "Charge counter or voltage unavailable"} + + +def cleanup_probe(): + with tempfile.TemporaryDirectory(prefix="helm-cleanup-probe-") as temporary: + directory = Path(temporary) + pidfile = directory / "stalled.pid" + stalled = directory / "stalled.py" + stalled.write_text( + f"import os,time\nfrom pathlib import Path\nPath({str(pidfile)!r}).write_text(str(os.getpid()))\nwhile True: time.sleep(1)\n" + ) + healthy = directory / "healthy.py" + healthy.write_text( + "from novaprinter import prettyPrinter\nclass healthy:\n name='healthy'\n def search(self, query, cat='all'):\n prettyPrinter({'name':'generated','link':'magnet:?xt=urn:btih:'+'a'*40})\n" + ) + result = run_searches( + [SearchJob("stalled", "plugin", str(stalled)), SearchJob("healthy", "plugin", str(healthy))], + "generated", + timeout=3, + max_workers=2, + ) + pid = int(pidfile.read_text()) if pidfile.exists() else None + outcome = {item.source: item.status for item in result.outcomes} + alive = process_alive(pid) if pid else None + passed = outcome == {"stalled": "timeout", "healthy": "success"} and alive is False + return { + "passed": passed, + "outcomes": outcome, + "retained_results": len(result), + "stalled_process_running_after_return": alive, + } + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--workers", type=int, nargs="+", default=[2, 6]) + parser.add_argument("--repeats", type=int, default=3) + args = parser.parse_args(argv) + if args.repeats < 1 or any(not 1 <= value <= 12 for value in args.workers): + parser.error("positive repeats and worker counts 1–12 required") + report = { + "schema_version": 1, + "platform": platform.platform(), + "machine": platform.machine(), + "battery_before": battery_sysfs(), + "profiles": [], + } + original = {key: os.environ.get(key) for key in ("HELM_CONFIG_DIR", "HELM_STATE_DIR")} + try: + with tempfile.TemporaryDirectory(prefix="helm-device-profile-") as temporary: + os.environ["HELM_CONFIG_DIR"] = str(Path(temporary) / "config") + os.environ["HELM_STATE_DIR"] = str(Path(temporary) / "state") + for workers in args.workers: + trials = [ + run_trial(0.1, 4 * 1024**2, 30, fixture_plugins=12, fixture_results=100, search_workers=workers) + for _ in range(args.repeats) + ] + report["profiles"].append({"workers": workers, "trials": trials}) + report["cleanup"] = cleanup_probe() + finally: + for key, value in original.items(): + if value is None: + os.environ.pop(key, None) + else: + os.environ[key] = value + report["battery_after"] = battery_sysfs() + report["energy"] = { + "consumption_wh": None, + "reason": "Use external ADB battery samples if Android denies app sensor access", + } + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2) + "\n") + print(json.dumps({"output": str(args.output), "cleanup": report["cleanup"]}), flush=True) + return 0 if report["cleanup"]["passed"] else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/src/helm/core/http.py b/src/helm/core/http.py index 4e888a1..356415a 100644 --- a/src/helm/core/http.py +++ b/src/helm/core/http.py @@ -1,16 +1,19 @@ -import requests +"""Connection reuse within each worker thread without sharing mutable cookies.""" + +import threading -_MAX_SOCKETS = 32 +import requests -_session = requests.Session() -_adapter = requests.adapters.HTTPAdapter(pool_connections=_MAX_SOCKETS, pool_maxsize=_MAX_SOCKETS) -_session.mount("https://", _adapter) -_session.mount("http://", _adapter) +_MAX_SOCKETS = 8 +_local = threading.local() def get_shared_session() -> requests.Session: - """Return the process-wide session so keep-alive connections are reused across fetchers. - - The session is not used for cookies/auth, so sharing it across worker threads is safe. - """ - return _session + session = getattr(_local, "session", None) + if session is None: + session = requests.Session() + adapter = requests.adapters.HTTPAdapter(pool_connections=_MAX_SOCKETS, pool_maxsize=_MAX_SOCKETS) + session.mount("https://", adapter) + session.mount("http://", adapter) + _local.session = session + return session diff --git a/src/helm/core/init_env.py b/src/helm/core/init_env.py index 33aae3b..0eed37d 100644 --- a/src/helm/core/init_env.py +++ b/src/helm/core/init_env.py @@ -2,7 +2,7 @@ import subprocess import time -from helm.core.config_manager import get_config_dir, get_dl_dir, get_log_dir +from helm.core.config_manager import get_config_dir, get_dl_dir, get_state_dir DOCKER_COMPOSE_BASE = """ services: @@ -152,7 +152,7 @@ def bootstrap_env(): print("===========================================") config_dir = get_config_dir() - state_dir = os.path.dirname(get_log_dir()) + state_dir = get_state_dir() dl_dir = get_dl_dir() project_name = "helm" @@ -348,4 +348,4 @@ def bootstrap_env(): print("\nTearing down containers for Ephemeral (One-Shot) mode...") subprocess.run(compose_cmd + ["-f", compose_path, "stop"], check=False) - print("\nSetup is complete! You can now use helm.") + print("\nSetup is complete! You can now use helm-torrent.") diff --git a/src/helm/core/jobs.py b/src/helm/core/jobs.py new file mode 100644 index 0000000..79c9c7f --- /dev/null +++ b/src/helm/core/jobs.py @@ -0,0 +1,380 @@ +"""Durable headless download queue with process-isolated, cancellable workers.""" + +import contextlib +import hashlib +import os +import sqlite3 +import subprocess +import sys +import threading +import time +import uuid +from pathlib import Path, PurePosixPath +from urllib.parse import urlsplit + +from helm.core.config_manager import get_dl_dir, get_state_dir +from helm.core.runtime import child_environment, process_alive, process_start +from helm.core.secret_manager import redact_text +from helm.core.torrent_links import MAX_METADATA, metadata_source, validate_magnet + +TERMINAL = {"succeeded", "failed", "cancelled"} +RETRYABLE = ("failed", "cancelled") +# Seconds a submitted job may be absent from qBittorrent before it counts as removed. +MISSING_GRACE = 300 + + +class JobStore: + def __init__(self, path=None): + self.path = Path(path or Path(get_state_dir()) / "jobs.sqlite3").absolute() + self.path.parent.mkdir(parents=True, exist_ok=True) + # Create the file privately first: SQLite copies its mode to -wal/-shm. + os.close(os.open(str(self.path), os.O_RDWR | os.O_CREAT, 0o600)) + os.chmod(self.path, 0o600) + with self.connect() as connection: + # HTTP threads, the queue thread and worker processes share this file. + connection.execute("PRAGMA journal_mode=WAL") + connection.executescript(""" + CREATE TABLE IF NOT EXISTS jobs ( + id TEXT PRIMARY KEY, fingerprint TEXT UNIQUE, source TEXT NOT NULL, + lite INTEGER NOT NULL, status TEXT NOT NULL DEFAULT 'pending', + created REAL, updated REAL, owner_pid INTEGER, owner_start TEXT, + error TEXT, result TEXT + ); + CREATE TABLE IF NOT EXISTS files ( + path TEXT PRIMARY KEY, job_id TEXT, size INTEGER, completed REAL + ); + CREATE INDEX IF NOT EXISTS jobs_status_created ON jobs(status, created); + """) + + @contextlib.contextmanager + def connect(self): + connection = sqlite3.connect(str(self.path), timeout=10) + connection.row_factory = sqlite3.Row + try: + with connection: + yield connection + finally: + connection.close() + + def _prepare(self, source, lite): + """Validate one source and return its stored form and dedupe fingerprint.""" + source = str(source).strip() + parts = urlsplit(source) + scheme = parts.scheme.lower() + if scheme == "magnet": + validate_magnet(source) + elif scheme in ("http", "https"): + if not parts.hostname: + raise ValueError("HTTP(S) link has no host") + else: + source = self._spool(source) + return source, hashlib.sha256((str(bool(lite)) + "\0" + source).encode()).hexdigest() + + def _spool(self, source): + path = Path(source) + if path.suffix.lower() != ".torrent" or not path.is_file(): + raise ValueError("Expected a magnet, HTTP(S) link or local .torrent file") + with path.open("rb") as stream: + data = stream.read(MAX_METADATA + 1) + metadata_source(data) + spool = self.path.parent / "spool" + spool.mkdir(exist_ok=True) + cached = spool / (hashlib.sha256(data).hexdigest() + ".torrent") + if not cached.exists(): + temporary = spool / (uuid.uuid4().hex + ".tmp") + fd = os.open(str(temporary), os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + try: + with os.fdopen(fd, "wb") as stream: + stream.write(data) + os.replace(temporary, cached) + finally: + if temporary.exists(): + temporary.unlink() + return str(cached) + + def enqueue(self, source, lite=False): + return self.enqueue_many([source], lite)[0] + + def enqueue_many(self, sources, lite=False): + """Queue every source or none: validation happens before the transaction.""" + prepared = [self._prepare(source, lite) for source in sources] + rows = [] + now = time.time() + with self.connect() as connection: + connection.execute("BEGIN IMMEDIATE") + for source, fingerprint in prepared: + connection.execute( + "INSERT OR IGNORE INTO jobs(id,fingerprint,source,lite,created,updated) VALUES(?,?,?,?,?,?)", + (uuid.uuid4().hex, fingerprint, source, int(lite), now, now), + ) + row = connection.execute("SELECT * FROM jobs WHERE fingerprint=?", (fingerprint,)).fetchone() + # A finished failure may be retried, but never while its worker can still write. + if row["status"] in RETRYABLE and not process_alive(row["owner_pid"], row["owner_start"]): + connection.execute( + "UPDATE jobs SET status='pending',updated=?,error=NULL,result=NULL," + "owner_pid=NULL,owner_start=NULL WHERE id=?", + (now, row["id"]), + ) + row = connection.execute("SELECT * FROM jobs WHERE id=?", (row["id"],)).fetchone() + rows.append(dict(row)) + return rows + + def get(self, identifier): + with self.connect() as connection: + row = connection.execute("SELECT * FROM jobs WHERE id=?", (identifier,)).fetchone() + return dict(row) if row else None + + def list(self, limit=100): + with self.connect() as connection: + return [ + dict(row) for row in connection.execute("SELECT * FROM jobs ORDER BY created DESC LIMIT ?", (limit,)) + ] + + def with_status(self, status): + with self.connect() as connection: + return [ + dict(row) for row in connection.execute("SELECT * FROM jobs WHERE status=? ORDER BY created", (status,)) + ] + + def update(self, identifier, status, error=None, result=None): + with self.connect() as connection: + connection.execute( + "UPDATE jobs SET status=?,updated=?,error=?,result=? WHERE id=? AND (status!='cancelled' OR ?='cancelled')", + (status, time.time(), redact_text(error) if error else None, result, identifier, status), + ) + + def claim(self): + with self.connect() as connection: + connection.execute("BEGIN IMMEDIATE") + running = connection.execute("SELECT id,owner_pid,owner_start FROM jobs WHERE status='running'").fetchall() + for row in running: + if not process_alive(row["owner_pid"], row["owner_start"]): + connection.execute( + "UPDATE jobs SET status='pending',owner_pid=NULL,owner_start=NULL WHERE id=?", (row["id"],) + ) + row = connection.execute("SELECT * FROM jobs WHERE status='pending' ORDER BY created LIMIT 1").fetchone() + if row is None: + return None + connection.execute( + "UPDATE jobs SET status='running',owner_pid=?,owner_start=?,updated=? WHERE id=?", + (os.getpid(), process_start(os.getpid()), time.time(), row["id"]), + ) + return self.get(row["id"]) + + def release(self, identifier): + """Record that no worker process can still write to this job.""" + with self.connect() as connection: + connection.execute("UPDATE jobs SET owner_pid=NULL,owner_start=NULL WHERE id=?", (identifier,)) + + def cancel(self, identifier): + with self.connect() as connection: + connection.execute("BEGIN IMMEDIATE") + row = connection.execute("SELECT status FROM jobs WHERE id=?", (identifier,)).fetchone() + if row is None: + raise KeyError(identifier) + if row["status"] in TERMINAL: + return False + connection.execute("UPDATE jobs SET status='cancelled',updated=? WHERE id=?", (time.time(), identifier)) + return True + + def register_files(self, identifier, paths): + root = Path(get_dl_dir()).resolve() + with self.connect() as connection: + for value in paths: + path = Path(value).resolve() + if root not in path.parents or not path.is_file(): + continue + relative = str(path.relative_to(root)) + connection.execute( + "INSERT OR REPLACE INTO files(path,job_id,size,completed) VALUES(?,?,?,?)", + (relative, identifier, path.stat().st_size, time.time()), + ) + + def files(self): + with self.connect() as connection: + return [dict(row) for row in connection.execute("SELECT * FROM files ORDER BY path")] + + def file_entry(self, relative): + with self.connect() as connection: + row = connection.execute("SELECT * FROM files WHERE path=?", (relative,)).fetchone() + return dict(row) if row else None + + +def public_job(job): + return { + key: redact_text(job[key]) if isinstance(job[key], str) else job[key] + for key in ("id", "source", "status", "created", "updated", "error", "result") + } + + +def job_tag(identifier): + return "helm-job-" + identifier + + +def execute_job(store, identifier): + from helm.core.lite_downloader import download_magnet + from helm.core.qbittorrent_client import SHARED_TAG, add_magnet + + job = store.get(identifier) + if job is None or job["status"] != "running": + return 1 + try: + if job["lite"]: + if not download_magnet(job["source"], on_complete=lambda paths: store.register_files(identifier, paths)): + raise RuntimeError("Built-in download did not complete") + store.update(identifier, "succeeded", result="Download completed") + else: + add_magnet(job["source"], tag=SHARED_TAG + "," + job_tag(identifier)) + store.update(identifier, "submitted", result="Accepted by qBittorrent") + return 0 + except Exception as error: + store.update(identifier, "failed", error=error) + return 1 + + +def cancel_job(store, identifier): + """Cancel a job, and its qBittorrent torrent when one may have been submitted.""" + from helm.core.logger import get_logger + + job = store.get(identifier) + if job is None: + raise KeyError(identifier) + changed = store.cancel(identifier) + if changed and not job["lite"] and job["status"] in ("running", "submitted"): + from helm.core.qbittorrent_client import delete_tagged + + try: + delete_tagged(job_tag(identifier)) + except Exception: + get_logger(__name__).warning("Cannot remove cancelled job %s from qBittorrent", identifier, exc_info=True) + return changed + + +def process_one(store, stop=None, cancel_poll=1.0): + from helm.core.search_runner import stop_worker + + stop = stop or threading.Event() + job = store.claim() + if job is None: + return False + identifier = job["id"] + logs = store.path.parent / "jobs" + process = None + try: + logs.mkdir(exist_ok=True) + fd = os.open(str(logs / (identifier + ".log")), os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600) + with os.fdopen(fd, "wb") as stream: + try: + process = subprocess.Popen( + [sys.executable, "-m", "helm.core.jobs", "--worker", str(store.path), identifier], + stdin=subprocess.DEVNULL, + stdout=stream, + stderr=stream, + env=child_environment(), + start_new_session=os.name == "posix", + ) + except OSError as error: + store.update(identifier, "failed", error=error) + return True + next_poll = time.monotonic() + cancel_poll + while process.poll() is None: + if stop.wait(0.1): + stop_worker(process) + if store.get(identifier)["status"] == "running": + store.update(identifier, "pending", result="Interrupted; queued for resume") + return True + if time.monotonic() >= next_poll: + next_poll += cancel_poll + if store.get(identifier)["status"] == "cancelled": + return True + if store.get(identifier)["status"] == "running": + store.update(identifier, "failed", error="Download worker exited without a result; see its job log") + finally: + if process is not None: + stop_worker(process) + store.release(identifier) + return True + + +def host_path(save_path, name): + """Map a path reported by qBittorrent, possibly inside its container, to this host.""" + from helm.core.config_manager import load_config + + mount = PurePosixPath(os.getenv("QB_DOWNLOADS_ROOT") or load_config().get("QB_DOWNLOADS_ROOT") or "/downloads") + reported = PurePosixPath(save_path or mount) / name + if mount in reported.parents: + return Path(get_dl_dir()) / reported.relative_to(mount) + return Path(reported) + + +def reconcile_qbittorrent(store): + from helm.core.qbittorrent_client import qb_request, tagged_torrents + + pending = store.with_status("submitted") + if not pending: + return + by_tag = {} + for torrent in tagged_torrents(): + for tag in torrent.get("tags", "").split(","): + by_tag.setdefault(tag.strip(), []).append(torrent) + for job in pending: + torrents = by_tag.get(job_tag(job["id"]), []) + if not torrents: + if time.time() - job["updated"] > MISSING_GRACE: + store.update(job["id"], "failed", error="Torrent is no longer present in qBittorrent") + continue + if not all(torrent.get("progress", 0) >= 1 for torrent in torrents): + continue + paths = [] + for torrent in torrents: + files = qb_request("GET", "/api/v2/torrents/files", params={"hash": torrent["hash"]}).json() + paths.extend( + str(host_path(torrent.get("save_path"), item["name"])) for item in files if item.get("progress") == 1 + ) + store.register_files(job["id"], paths) + store.update(job["id"], "succeeded", result="qBittorrent download completed") + + +def queue_loop(store, stop, reconcile_every=5): + from helm.core.logger import get_logger + + logger = get_logger(__name__) + failures = 0 + next_reconcile = 0.0 + while not stop.is_set(): + try: + busy = process_one(store, stop) + failures = 0 + except Exception: + # The service keeps accepting work, so its worker must outlive a bad job. + failures += 1 + logger.exception("Download queue iteration failed") + stop.wait(min(30, 2**failures)) + continue + if stop.is_set(): + break + if time.monotonic() >= next_reconcile: + next_reconcile = time.monotonic() + reconcile_every + try: + reconcile_qbittorrent(store) + except Exception: + logger.debug("Cannot reconcile qBittorrent jobs", exc_info=True) + if not busy: + stop.wait(0.5) + + +def exit_with_parent(parent, interval=1): + """Stop an orphaned worker: a force-killed service cannot reap its process group.""" + while os.getppid() == parent: + time.sleep(interval) + os._exit(1) + + +if __name__ == "__main__": + if len(sys.argv) != 4 or sys.argv[1] != "--worker": + raise SystemExit("Internal job worker") + from helm.core.logger import configure_logging + + threading.Thread(target=exit_with_parent, args=(os.getppid(),), daemon=True).start() + configure_logging(file_logging=False, verbose=True) + raise SystemExit(execute_job(JobStore(sys.argv[2]), sys.argv[3])) diff --git a/src/helm/core/lite_downloader.py b/src/helm/core/lite_downloader.py index 2eb74bf..2e8ce54 100644 --- a/src/helm/core/lite_downloader.py +++ b/src/helm/core/lite_downloader.py @@ -3,18 +3,22 @@ import time -def download_magnet(magnet_link, save_path="./downloads"): +def download_magnet(magnet_link, save_path=None, on_complete=None): try: import libtorrent as lt except ImportError: print("\n\033[33m[!] libtorrent is not installed.\033[0m") - print("To use the built-in lite downloader, please install it (e.g., 'pip install libtorrent').") + print("To use the built-in lite downloader, install 'helm-torrent[download]' where supported.") print(f"\n\033[1mMagnet Link:\033[0m {magnet_link}\n") print("Copy the above link and paste it into your torrent client.") return False - if not os.path.exists(save_path): - os.makedirs(save_path) + if save_path is None: + from helm.core.config_manager import get_dl_dir + + save_path = get_dl_dir() + save_path = os.path.abspath(os.path.expanduser(os.fspath(save_path))) + os.makedirs(save_path, exist_ok=True) settings = { "listen_interfaces": "0.0.0.0:0", @@ -24,25 +28,31 @@ def download_magnet(magnet_link, save_path="./downloads"): "enable_natpmp": True, "announce_to_all_trackers": True, "announce_to_all_tiers": True, + # Configure bootstrap nodes before starting DHT. Some libtorrent builds + # (including Termux's) omit the deprecated add_dht_router binding. + "dht_bootstrap_nodes": ( + "router.bittorrent.com:6881,router.utorrent.com:6881,dht.transmissionbt.com:6881,dht.aelitis.com:6881" + ), } - ses = lt.session(settings) + from helm.core.torrent_links import resolve_torrent - # Add common DHT routers to bootstrap finding peers quickly - ses.add_dht_router("router.bittorrent.com", 6881) - ses.add_dht_router("router.utorrent.com", 6881) - ses.add_dht_router("dht.transmissionbt.com", 6881) - ses.add_dht_router("dht.aelitis.com", 6881) + source = resolve_torrent(magnet_link) + ses = lt.session(settings) print("\n\033[1m\033[34mAdding magnet link to libtorrent session...\033[0m") - # Parse the magnet URI properly for libtorrent 2.x - params = lt.parse_magnet_uri(magnet_link) - params.save_path = save_path - handle = ses.add_torrent(params) + try: + # Parse the magnet URI properly for libtorrent 2.x + if source.data: + params = lt.add_torrent_params() + params.ti = lt.torrent_info(lt.bdecode(source.data)) + else: + params = lt.parse_magnet_uri(source.magnet) + params.save_path = save_path + handle = ses.add_torrent(params) - sys.stdout.write("Downloading Metadata") + sys.stdout.write("Downloading Metadata") - try: timeout = 60 elapsed = 0 while not handle.status().has_metadata: @@ -53,7 +63,6 @@ def download_magnet(magnet_link, save_path="./downloads"): if elapsed >= timeout: print("\n\n\033[31m[!] Timeout reaching metadata. The torrent might be dead or blocked.\033[0m") print(f"Fallback Magnet Link: {magnet_link}") - ses.pause() return False print("\nMetadata downloaded. Starting torrent download...") @@ -88,15 +97,19 @@ def download_magnet(magnet_link, save_path="./downloads"): sys.stdout.write( f"\033[33mEnsure you have write permissions to {os.path.abspath(save_path)}\033[0m\n" ) - ses.pause() return False time.sleep(1) + if on_complete: + info = handle.torrent_file() + files = info.files() + on_complete([os.path.join(save_path, files.file_path(index)) for index in range(files.num_files())]) print("\n\n\033[32m\033[1mDownload complete!\033[0m") except KeyboardInterrupt: print("\n\n\033[33mDownload interrupted by user. Cleaning up session...\033[0m") - ses.pause() return False + finally: + ses.pause() return True diff --git a/src/helm/core/lite_fetcher.py b/src/helm/core/lite_fetcher.py index 1880989..cd3b808 100644 --- a/src/helm/core/lite_fetcher.py +++ b/src/helm/core/lite_fetcher.py @@ -1,5 +1,4 @@ import asyncio -import concurrent.futures import datetime import os import xml.etree.ElementTree as ET @@ -9,8 +8,9 @@ from helm.core.config_manager import get_config_dir from helm.core.http import get_shared_session +from helm.core.lite_plugin_loader import PLUGIN_SEARCH_TIMEOUT from helm.core.logger import get_logger -from helm.core.rss_fetcher import TorrentItem +from helm.core.rss_fetcher import SearchResults, SourceOutcome, TorrentItem, source_status logger = get_logger(__name__) @@ -72,9 +72,10 @@ def _fetch_apibay(query: str) -> List[TorrentItem]: except Exception as e: logger.debug(f"Event: Apibay connection failed: {e}") + return SearchResults(items, [SourceOutcome("Apibay", source_status(e), len(items))]) logger.info(f"Event: Apibay returned {len(items)} results") - return items + return SearchResults(items, [SourceOutcome("Apibay", "success" if items else "empty", len(items))]) def _fetch_torrents_csv(query: str) -> List[TorrentItem]: @@ -83,6 +84,7 @@ def _fetch_torrents_csv(query: str) -> List[TorrentItem]: torrents_csv_url = "https://torrents-csv.com/service/search" try: r = get_shared_session().get(torrents_csv_url, params={"q": query, "size": "100"}, timeout=15) + r.raise_for_status() if r.status_code == 200: data = r.json() for item in data.get("torrents", []): @@ -111,9 +113,10 @@ def _fetch_torrents_csv(query: str) -> List[TorrentItem]: items.append(TorrentItem(title, magnet, seeders, leechers, size, pubdate, "Torrents-csv")) except Exception as e: logger.debug(f"Event: Torrents-csv connection failed: {e}") + return SearchResults(items, [SourceOutcome("Torrents-csv", source_status(e), len(items))]) logger.info(f"Event: Torrents-csv returned {len(items)} results") - return items + return SearchResults(items, [SourceOutcome("Torrents-csv", "success" if items else "empty", len(items))]) def _fetch_nyaa(query: str) -> List[TorrentItem]: @@ -122,6 +125,7 @@ def _fetch_nyaa(query: str) -> List[TorrentItem]: nyaa_url = f"https://nyaa.si/?page=rss&q={quote(query)}&c=0_0&f=0" try: r = get_shared_session().get(nyaa_url, timeout=15) + r.raise_for_status() if r.status_code == 200: root = ET.fromstring(r.content) for item in root.findall("./channel/item"): @@ -159,58 +163,38 @@ def _fetch_nyaa(query: str) -> List[TorrentItem]: items.append(TorrentItem(title, magnet, seeders, leechers, size, pubdate, "Nyaa")) except Exception as e: logger.debug(f"Event: Nyaa connection failed: {e}") + return SearchResults(items, [SourceOutcome("Nyaa", source_status(e), len(items))]) logger.info(f"Event: Nyaa returned {len(items)} results") - return items + return SearchResults(items, [SourceOutcome("Nyaa", "success" if items else "empty", len(items))]) -def _collect_plugins(query: str) -> List[TorrentItem]: - """Run the bundled/user search plugins (parallel) via the plugin loader.""" - from helm.core.lite_plugin_loader import run_plugins - - plugin_dirs = [ - os.path.join(get_config_dir(), "plugins"), # User plugins (XDG config dir) - os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "plugins"), # Bundled plugins +def _plugin_dirs(): + return [ + os.path.join(get_config_dir(), "plugins"), + os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "plugins"), ] - plugin_results = run_plugins(query, plugin_dirs) or [] - logger.info(f"Event: Native plugins returned {len(plugin_results)} results") - return list(plugin_results) - -def _collect_all(query: str) -> List[TorrentItem]: - """Fetch every lite source concurrently and merge the results. +def _collect_all(query, content_type="video"): + from helm.core.lite_plugin_loader import plugin_jobs + from helm.core.search_runner import SearchJob, run_searches - Sources run in a single bounded pool so one hung socket slows a search to a - single request timeout instead of a serial chain of failures. - """ - sources = [ - _fetch_apibay, - _fetch_torrents_csv, - _fetch_nyaa, - _collect_plugins, + jobs = [ + SearchJob("Apibay", "inline", "apibay"), + SearchJob("Torrents-csv", "inline", "csv"), + SearchJob("Nyaa", "inline", "nyaa"), ] - pool = concurrent.futures.ThreadPoolExecutor(max_workers=len(sources)) - futures = [pool.submit(source, query) for source in sources] - # Give each source the full budget; sockets themselves time out at ~15s, - # so this bound only protects against an abandoned straggler. Done futures - # are drained eagerly; stragglers keep their private thread-local state and - # can never contaminate this or any later search. - done, _ = concurrent.futures.wait(futures, timeout=25) - pool.shutdown(wait=False) - - pooled = [] - for future in done: - try: - pooled.extend(future.result()) - except Exception: - logger.debug("Event: Failed to collect lite source results", exc_info=True) - return pooled - - -def search_lite(query): + jobs.extend(plugin_jobs(_plugin_dirs())) + return run_searches(jobs, query, content_type, timeout=PLUGIN_SEARCH_TIMEOUT) + + +def search_lite(query, content_type="video"): """Lite mode fetcher using public APIs (e.g., apibay) without needing Jackett.""" - return _collect_all(query) + query = query.strip() + if not query: + return [] + return _collect_all(query, content_type) async def search_all_plugins(query, content_type="video"): @@ -218,4 +202,4 @@ async def search_all_plugins(query, content_type="video"): All I/O is delegated to the worker pool inside :func:`search_lite`. """ - return await asyncio.get_running_loop().run_in_executor(None, search_lite, query) + return await asyncio.get_running_loop().run_in_executor(None, search_lite, query, content_type) diff --git a/src/helm/core/lite_plugin_loader.py b/src/helm/core/lite_plugin_loader.py index d7a7080..614d992 100644 --- a/src/helm/core/lite_plugin_loader.py +++ b/src/helm/core/lite_plugin_loader.py @@ -1,11 +1,12 @@ -import concurrent.futures import importlib.util import os import sys from helm.core.logger import get_logger +from helm.core.rss_fetcher import SearchResults, SourceOutcome, source_status logger = get_logger(__name__) +PLUGIN_SEARCH_TIMEOUT = 30 # Ensure our plugins directory is in the path so helpers and novaprinter can be imported sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "../plugins"))) @@ -13,95 +14,102 @@ import novaprinter # noqa: E402 +def plugin_jobs(plugin_dirs): + from helm.core.search_runner import SearchJob + + jobs = [] + for directory in plugin_dirs: + if not os.path.isdir(directory): + continue + for filename in sorted(os.listdir(directory)): + if ( + filename.endswith(".py") + and not filename.startswith("__") + and filename not in ("helpers.py", "novaprinter.py", "piratebay.py") + ): + jobs.append(SearchJob(filename[:-3], "plugin", os.path.join(directory, filename))) + return jobs + + +def load_plugin(filepath): + directory = os.path.dirname(filepath) + if directory not in sys.path: + sys.path.insert(0, directory) + module_name = os.path.basename(filepath)[:-3] + spec = importlib.util.spec_from_file_location(module_name, filepath) + if spec is None or spec.loader is None: + raise ImportError("Cannot load plugin") + mod = importlib.util.module_from_spec(spec) + sys.modules[module_name] = mod + mod.print = lambda *args, **kwargs: get_logger(module_name).debug(" ".join(str(a) for a in args)) + spec.loader.exec_module(mod) + for attr in vars(mod).values(): + if isinstance(attr, type) and attr.__module__ == module_name and hasattr(attr, "search"): + return attr() + raise ValueError("Plugin has no search class") + + def load_plugins(plugin_dir): plugins = [] - if not os.path.exists(plugin_dir): - return plugins - - # Also add user plugin dirs to sys.path so they can import helpers natively - if plugin_dir not in sys.path: - sys.path.insert(0, plugin_dir) - - for file in os.listdir(plugin_dir): - # Ignore our SDK files, standard dunder files, and plugins whose sources - # are already fetched inline by the lite pipeline (piratebay == apibay). - if ( - file.endswith(".py") - and not file.startswith("__") - and file - not in ( - "helpers.py", - "novaprinter.py", - "piratebay.py", - ) - ): - filepath = os.path.join(plugin_dir, file) - module_name = file[:-3] - try: - spec = importlib.util.spec_from_file_location(module_name, filepath) - if spec and spec.loader: - mod = importlib.util.module_from_spec(spec) - sys.modules[module_name] = mod - - # Intercept standard logging by configuring the root logger - get_logger("") - - # Intercept third-party prints by injecting a custom print into the module's globals - mod.print = lambda *args, **kwargs: get_logger(module_name).debug(" ".join(str(a) for a in args)) # noqa: B023 - - spec.loader.exec_module(mod) - - # Search for the plugin class inside the module. - # Usually the class has a 'search' method and is not a built-in. - for attr_name in dir(mod): - if attr_name.startswith("__"): - continue - attr = getattr(mod, attr_name) - if isinstance(attr, type) and hasattr(attr, "search"): - plugins.append(attr()) - break - except Exception: - logger.debug(f"Event: Failed to load plugin {file}", exc_info=True) - + for job in plugin_jobs([plugin_dir]): + try: + plugins.append(load_plugin(job.target)) + except Exception: + logger.debug("Failed to load %s", job.source, exc_info=True) return plugins -def _execute_plugin(plugin, query): +def plugin_categories(plugin, content_type): + supported = getattr(plugin, "supported_categories", {"all": "all"}) + aliases = { + "video": ("movies", "tv", "anime"), + "books": ("books",), + "games": ("games",), + "software": ("software",), + "music": ("music",), + } + selected = [] + for category in content_type.split(","): + candidates = aliases.get(category, (category,)) + matching = [key for key in candidates if key in supported] + if not matching: + matching = ["all"] if "all" in supported else [] + for key in matching: + if key not in selected: + selected.append(key) + # all already includes narrower categories; avoid duplicate requests. + return ["all"] if "all" in selected else selected + + +def _execute_plugin(plugin, query, content_type="all"): name = getattr(plugin, "name", plugin.__class__.__name__) collector = novaprinter.get_results() - collector.clear() # pooled worker threads keep their thread-local between runs + collector.clear() + novaprinter.get_errors().clear() before = len(collector) + status = None try: - plugin.search(query) - except Exception: + for category in plugin_categories(plugin, content_type): + if category == "all": + plugin.search(query) + else: + plugin.search(query, category) + except Exception as error: + status = source_status(error) logger.debug(f"Event: Error running plugin {name}", exc_info=True) + errors = novaprinter.get_errors() + if errors and status is None: + status = errors[0] after = len(collector) for item in collector: item.indexer = name logger.info(f"Event: Plugin {name} returned {after - before} results") - return collector + # Pool workers can run several plugins. Return a snapshot before the next + # plugin clears that worker's thread-local collector. + return SearchResults(collector, [SourceOutcome(name, status or ("success" if collector else "empty"), after)]) -def run_plugins(query, plugin_dirs): - plugins = [] - for d in plugin_dirs: - plugins.extend(load_plugins(d)) - - executor = concurrent.futures.ThreadPoolExecutor(max_workers=10) - futures = [executor.submit(_execute_plugin, p, query) for p in plugins] - # Give slow-but-alive plugins up to 30s; each plugin's own HTTP requests - # already time out at ~15s so a hung socket is the only straggler. - done, _ = concurrent.futures.wait(futures, timeout=30) - # Abandon stragglers so the UI stays snappy. Their future writes land in a - # private thread-local collector (never the return value), so they cannot - # contaminate this or any later search. - executor.shutdown(wait=False) - - results = [] - for future in done: - try: - results.extend(future.result()) - except Exception: - logger.debug("Event: Failed to collect plugin results", exc_info=True) +def run_plugins(query, plugin_dirs, content_type="all"): + from helm.core.search_runner import run_searches - return results + return run_searches(plugin_jobs(plugin_dirs), query, content_type, timeout=PLUGIN_SEARCH_TIMEOUT) diff --git a/src/helm/core/logger.py b/src/helm/core/logger.py index 93ef22e..710cf73 100644 --- a/src/helm/core/logger.py +++ b/src/helm/core/logger.py @@ -7,18 +7,7 @@ from logging.handlers import RotatingFileHandler from helm.core.config_manager import get_log_dir - -LOG_DIR = get_log_dir() -os.makedirs(LOG_DIR, exist_ok=True) -LOG_FILE = os.path.join(LOG_DIR, "helm.log") - -# Migrate old log file if it exists -old_log = os.path.join(os.path.expanduser("~"), ".helm_data", "logs", "helm.log") -if os.path.exists(old_log) and not os.path.exists(LOG_FILE): - try: - shutil.move(old_log, LOG_FILE) - except Exception: - pass +from helm.core.secret_manager import redact_config, redact_text class JSONFormatter(logging.Formatter): @@ -64,7 +53,7 @@ def format(self, record): ]: log_obj[key] = value - return json.dumps(log_obj) + return json.dumps(redact_config(log_obj)) class FileOnlyFilter(logging.Filter): @@ -83,7 +72,7 @@ def format(self, record): formatted = f"[{timestamp}] [{level}] [{module}] - {message}" if record.exc_info: formatted += f"\n{self.formatException(record.exc_info)}" - return formatted + return redact_text(formatted) class ConsoleFormatter(logging.Formatter): @@ -92,36 +81,67 @@ def format(self, record): level = record.levelname.ljust(5) module = record.name message = record.getMessage() - return f"[{timestamp}] [{level}] [{module}] - {message}" + return redact_text(f"[{timestamp}] [{level}] [{module}] - {message}") def get_logger(name: str): + # Importing modules must not create files before CLI path overrides are known. logger = logging.getLogger(name) - if logger.hasHandlers(): - return logger - logger.setLevel(logging.DEBUG) - logger.propagate = False - - use_json = os.environ.get("HELM_LOG_JSON", "false").lower() == "true" - file_formatter = JSONFormatter() if use_json else PlainTextFormatter() - console_formatter = ConsoleFormatter() - - # Console Handler (stderr, so stdout stays clean for --json / TUI output) - console_handler = logging.StreamHandler(sys.stderr) - is_verbose = "--verbose" in sys.argv or os.environ.get("HELM_VERBOSE", "false").lower() == "true" - console_handler.setLevel(logging.DEBUG if is_verbose else logging.WARNING) - # Use console formatter which strips tracebacks to keep TUI clean, unless verbose - console_handler.setFormatter(file_formatter if is_verbose else console_formatter) - # Keep file_only messages out of the console/TUI; they still reach the log file. - console_handler.addFilter(FileOnlyFilter()) - - # File Handler - file_handler = RotatingFileHandler(LOG_FILE, maxBytes=5 * 1024 * 1024, backupCount=3) - file_handler.setLevel(logging.DEBUG) - file_handler.setFormatter(file_formatter) + if not logger.handlers: + logger.addHandler(logging.NullHandler()) + return logger - logger.addHandler(console_handler) - logger.addHandler(file_handler) - return logger +def configure_logging(file_logging=True, verbose=None): + root = logging.getLogger() + root.setLevel(logging.DEBUG) + for handler in list(root.handlers): + if getattr(handler, "_helm_handler", False): + root.removeHandler(handler) + handler.close() + formatter = JSONFormatter() if os.environ.get("HELM_LOG_JSON", "false").lower() == "true" else PlainTextFormatter() + if verbose is None: + verbose = os.environ.get("HELM_VERBOSE", "false").lower() == "true" + console = logging.StreamHandler(sys.stderr) + console.setLevel(logging.DEBUG if verbose else logging.WARNING) + console.setFormatter(formatter if verbose else ConsoleFormatter()) + console.addFilter(FileOnlyFilter()) + handlers = [console] + if file_logging: + directory = get_log_dir() + os.makedirs(directory, exist_ok=True) + path = os.path.join(directory, "helm.log") + old = os.path.expanduser("~/.helm_data/logs/helm.log") + if os.path.isfile(old) and not os.path.exists(path): + try: + shutil.move(old, path) + except OSError: + pass + handler = RotatingFileHandler(path, maxBytes=5 * 1024 * 1024, backupCount=3) + handler.setLevel(logging.DEBUG) + handler.setFormatter(formatter) + handlers.append(handler) + for handler in handlers: + handler._helm_handler = True + root.addHandler(handler) + + +def tail_log(path, lines=20, max_bytes=1024 * 1024): + """Read a bounded suffix; never scan an entire large log to display its tail.""" + if lines < 1 or max_bytes < 1: + return "" + with open(path, "rb") as stream: + stream.seek(0, os.SEEK_END) + end = stream.tell() + data = b"" + position = end + while position and data.count(b"\n") <= lines and len(data) < max_bytes: + amount = min(8192, position, max_bytes - len(data)) + position -= amount + stream.seek(position) + data = stream.read(amount) + data + if position and b"\n" in data: + data = data.split(b"\n", 1)[1] + result = b"\n".join(data.splitlines()[-lines:]).decode("utf-8", errors="replace") + return redact_text(result) + ("\n" if result else "") diff --git a/src/helm/core/oneshot.py b/src/helm/core/oneshot.py index 9aba24c..3ee0ff5 100644 --- a/src/helm/core/oneshot.py +++ b/src/helm/core/oneshot.py @@ -36,9 +36,9 @@ def spin_up_oneshot(): print("\n\033[1m\033[36mInitializing One-Shot Ephemeral Stack...\033[0m") print("\033[3mBringing up Jackett, Prowlarr, Flaresolverr, and qBittorrent via docker compose...\033[0m") - from helm.core.config_manager import get_log_dir + from helm.core.config_manager import get_state_dir - state_dir = os.path.dirname(get_log_dir()) + state_dir = get_state_dir() compose_file = os.path.join(state_dir, "docker-compose.yml") compose_flags = ["-f", compose_file] if os.path.exists(compose_file) else [] diff --git a/src/helm/core/qbittorrent_client.py b/src/helm/core/qbittorrent_client.py index a48a4a6..ffa9cfb 100644 --- a/src/helm/core/qbittorrent_client.py +++ b/src/helm/core/qbittorrent_client.py @@ -8,75 +8,111 @@ """ import os +import threading import requests +from helm.core.config_manager import get_qb_url, load_config +from helm.core.logger import get_logger from helm.core.secret_manager import get_secret +from helm.core.torrent_links import resolve_torrent + +logger = get_logger(__name__) + +# Applied to every Helm job so reconciliation needs one list call per pass. +SHARED_TAG = "helm" _session = None +_session_key = None +_session_lock = threading.Lock() -def login_qbittorrent(): +def login_qbittorrent(force=False): """ logs in to qbittorrent web ui and returns a sessio with the fresh SID cookie """ - global _session - if _session is not None: - return _session - - qb_webui = os.getenv("QB_WEBUI", "http://localhost:8080") - qb_username = os.getenv("QB_USERNAME", "admin") + global _session, _session_key + qb_webui = get_qb_url() + qb_username = os.getenv("QB_USERNAME") or load_config().get("QB_USERNAME", "admin") qb_password = get_secret("QB_PASSWORD") - if not qb_password: - raise Exception("Please set QB_PASSWORD in .env file !!") - - session = requests.Session() - - # Check if auth is already bypassed (e.g. via AuthSubnetWhitelist) - version_url = f"{qb_webui}/api/v2/app/version" - try: - r_test = session.get(version_url) - if r_test.status_code == 200: - print("Auth bypassed via subnet whitelist !!") - _session = session - return session - except Exception: - pass - - login_url = f"{qb_webui}/api/v2/auth/login" - data = {"username": qb_username, "password": qb_password} - r = session.post(login_url, data=data) - - if r.status_code == 200 or r.status_code == 204: - # Verify authentication by making a secondary request + key = (qb_webui, qb_username, qb_password) + with _session_lock: + if _session is not None and _session_key == key and not force: + return _session + if not qb_password: + raise Exception("Please set QB_PASSWORD in .env file !!") + + session = requests.Session() + + # Check if auth is already bypassed (e.g. via AuthSubnetWhitelist) + version_url = f"{qb_webui}/api/v2/app/version" try: - r_verify = session.get(version_url) - if r_verify.status_code != 200: - raise ConnectionError("Secondary verification request failed, authentication was not successful.") - except Exception as e: - # catching errors like pokemons - raise ConnectionError(f"Failed to verify qbittorrent authentication: {e}") # noqa: B904 + r_test = session.get(version_url, timeout=10) + if r_test.status_code == 200: + logger.info("qBittorrent subnet authentication accepted") + _session, _session_key = session, key + return session + except Exception: + pass + + login_url = f"{qb_webui}/api/v2/auth/login" + data = {"username": qb_username, "password": qb_password} + r = session.post(login_url, data=data, timeout=10) + + if r.status_code == 200 or r.status_code == 204: + # Verify authentication by making a secondary request + try: + r_verify = session.get(version_url, timeout=10) + if r_verify.status_code != 200: + raise ConnectionError("Secondary verification request failed, authentication was not successful.") + except Exception as e: + # catching errors like pokemons + raise ConnectionError(f"Failed to verify qbittorrent authentication: {e}") # noqa: B904 + else: + raise ConnectionError(f"Failed to login to qbittorrent: HTTP {r.status_code} {r.text}") + + logger.info("qBittorrent authentication accepted") + _session, _session_key = session, key + return session + + +def qb_request(method, path, **kwargs): + """Call the Web API, logging in again once if the SID cookie has expired.""" + kwargs.setdefault("timeout", 15) + url = get_qb_url() + path + response = login_qbittorrent().request(method, url, **kwargs) + if response.status_code == 403: + response = login_qbittorrent(force=True).request(method, url, **kwargs) + response.raise_for_status() + return response + + +def add_magnet(magnet, save_path=None, tag=None): + """Resolve a link or local metadata and submit it through qBittorrent's API.""" + source = resolve_torrent(magnet) + data = {} + if save_path: + data["savepath"] = save_path + if tag: + data["tags"] = tag + if source.data: + files = {"torrents": ("download.torrent", source.data, "application/x-bittorrent")} + response = qb_request("POST", "/api/v2/torrents/add", data=data, files=files) else: - raise ConnectionError(f"Failed to login to qbittorrent: HTTP {r.status_code} {r.text}") + data["urls"] = source.magnet + response = qb_request("POST", "/api/v2/torrents/add", data=data) + if response.text.strip().lower() in ("fails.", "fail", "error"): + raise RuntimeError("qBittorrent rejected torrent metadata") + logger.info("Torrent accepted by qBittorrent") + return True - print("Logged in to qbittorrent web ui !!") - _session = session - return session +def tagged_torrents(tag=SHARED_TAG): + return qb_request("GET", "/api/v2/torrents/info", params={"tag": tag}).json() -def add_magnet(magnet): - """ - adds a magnet link to qbitorrent using a logged-in session - """ - qb_webui = os.getenv("QB_WEBUI", "http://localhost:8080") - session = login_qbittorrent() - add_url = f"{qb_webui}/api/v2/torrents/add" - r = session.post(add_url, data={"urls": magnet}) - - if r.status_code in (200, 202): - # add some decorations later like check-mark - print(f"Magnet added: {magnet}") - elif r.status_code == 409: - print("\033[33mMagnet is already in your qBittorrent download list!\033[0m") - else: - print(f"Failed to add magnet: {r.status_code} | {r.text}") + +def delete_tagged(tag): + """Remove a tag's torrents, keeping any data already written to disk.""" + hashes = [torrent["hash"] for torrent in tagged_torrents(tag)] + if hashes: + qb_request("POST", "/api/v2/torrents/delete", data={"hashes": "|".join(hashes), "deleteFiles": "false"}) diff --git a/src/helm/core/rss_fetcher.py b/src/helm/core/rss_fetcher.py index adf489a..e464143 100644 --- a/src/helm/core/rss_fetcher.py +++ b/src/helm/core/rss_fetcher.py @@ -7,7 +7,10 @@ import email.utils import os +import urllib.error import xml.etree.ElementTree as ET +from dataclasses import dataclass +from typing import List import requests @@ -17,6 +20,38 @@ logger = get_logger(__name__) +@dataclass +class SourceOutcome: + source: str + status: str + count: int = 0 + + +class SearchResults(list): + """List-compatible results with diagnostics owned by this search only.""" + + def __init__(self, items=(), outcomes=()) -> None: + super().__init__(items) + self.outcomes: List[SourceOutcome] = list(outcomes) + + def extend(self, items) -> None: + super().extend(items) + self.outcomes.extend(getattr(items, "outcomes", ())) + + +def source_status(error): + """Report a safe category rather than exposing URLs or credentials.""" + if isinstance(error, (requests.exceptions.Timeout, TimeoutError)): + return "timeout" + if isinstance(error, (requests.exceptions.HTTPError, urllib.error.HTTPError)): + return "http_error" + if isinstance(error, (ValueError, TypeError, KeyError, AttributeError, ET.ParseError)): + return "parse_error" + if isinstance(error, (requests.exceptions.RequestException, urllib.error.URLError)): + return "connection_error" + return "error" + + class TorrentItem: def __init__(self, title, link, seeders, leechers=0, size=0, pubdate=None, indexer="Unknown"): self.title = title @@ -206,7 +241,7 @@ def search_prowlarr(query, content_type="video"): return [] -def search_indexers(query, content_type="video"): +def search_indexers(query, content_type="video", fallback_lite=True): """ Search using the configured Indexer Manager. @@ -241,6 +276,9 @@ def dedupe(items): if items: return dedupe(items) + if not fallback_lite: + return [] + logger.info("Event: Media Server search failed or returned 0 results, falling back to Lite mode...") import asyncio diff --git a/src/helm/core/runtime.py b/src/helm/core/runtime.py new file mode 100644 index 0000000..228674e --- /dev/null +++ b/src/helm/core/runtime.py @@ -0,0 +1,212 @@ +"""Detached commands and reconnectable terminal sessions without shell expansion.""" + +import json +import os +import re +import shutil +import signal +import subprocess +import sys +import time +import uuid +from pathlib import Path + +from helm.core.config_manager import get_state_dir +from helm.core.secret_manager import redact_text + +# Paths and settings a tmux server started earlier would otherwise not see. Secrets +# are excluded because new-session arguments are visible in the process list. +SESSION_ENVIRONMENT = ( + "PYTHONPATH", + "HELM_CONFIG_DIR", + "HELM_STATE_DIR", + "HELM_DL_DIR", + "HELM_LITE_WORKERS", + "HELM_LOG_JSON", + "HELM_VERBOSE", +) + + +def child_environment(base=None): + """Return an environment that can import this package in a subprocess.""" + environment = dict(os.environ if base is None else base) + root = str(Path(__file__).resolve().parents[2]) + inherited = environment.get("PYTHONPATH") + # An empty entry would put the working directory on the child's import path. + environment["PYTHONPATH"] = root + os.pathsep + inherited if inherited else root + return environment + + +def process_start(pid): + try: + text = Path(f"/proc/{pid}/stat").read_text() + fields = text.rsplit(")", 1)[1].split() + if fields[0] == "Z": + return None + return fields[19] + except (OSError, IndexError): + return None + + +def process_alive(pid, identity=None): + try: + os.kill(int(pid), 0) + except (OSError, ValueError, TypeError): + return False + actual = process_start(pid) + if Path("/proc").is_dir(): + return actual is not None and (identity is None or actual == identity) + return identity is None + + +def private_json(path, value): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_name(path.name + "." + uuid.uuid4().hex + ".tmp") + fd = os.open(str(temporary), os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + try: + with os.fdopen(fd, "w") as stream: + json.dump(value, stream, indent=2) + stream.write("\n") + os.replace(temporary, path) + finally: + if temporary.exists(): + temporary.unlink() + + +def child_arguments(arguments): + result = [] + skip = False + for argument in arguments: + if skip: + skip = False + continue + if argument == "--daemon": + continue + if argument == "--session": + skip = True + continue + if argument.startswith("--session="): + continue + result.append(argument) + return result + + +def start_daemon(arguments): + directory = Path(get_state_dir()) / "daemons" + directory.mkdir(parents=True, exist_ok=True) + identifier = uuid.uuid4().hex[:12] + log = directory / (identifier + ".log") + descriptor = os.open(str(log), os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + environment = child_environment() + environment["HELM_DAEMONIZED"] = "1" + with os.fdopen(descriptor, "wb") as stream: + process = subprocess.Popen( + [sys.executable, "-m", "helm.cli", *child_arguments(arguments)], + stdin=subprocess.DEVNULL, + stdout=stream, + stderr=stream, + start_new_session=os.name == "posix", + env=environment, + ) + identity = process_start(process.pid) + private_json( + directory / (identifier + ".json"), + { + "id": identifier, + "pid": process.pid, + "identity": identity, + "created": time.time(), + "command": redact_text(" ".join(child_arguments(arguments))), + "log": str(log), + }, + ) + # Reap immediate failures so a failed detach is not reported as success. + time.sleep(0.1) + code = process.poll() + if code is not None and code != 0: + raise RuntimeError(f"Background command failed ({code}); see {log}") + return identifier + + +def daemon_records(): + directory = Path(get_state_dir()) / "daemons" + records = [] + for path in sorted(directory.glob("*.json")): + try: + record = json.loads(path.read_text()) + record["running"] = process_alive(record["pid"], record["identity"]) + records.append(record) + except (OSError, ValueError, KeyError): + continue + return records + + +def stop_daemon(identifier, timeout=5): + if not re.fullmatch(r"[a-f0-9]{12}", identifier): + raise ValueError("Invalid daemon id") + path = Path(get_state_dir()) / "daemons" / (identifier + ".json") + record = json.loads(path.read_text()) + pid, identity = record["pid"], record["identity"] + if not process_alive(pid, identity): + return False + if identity is None: + raise RuntimeError("Cannot verify this process identity; stop it through the operating system") + os.kill(pid, signal.SIGTERM) + deadline = time.monotonic() + timeout + while process_alive(pid, identity) and time.monotonic() < deadline: + time.sleep(0.05) + if process_alive(pid, identity): + try: + # The daemon leads its session; job workers notice their parent is gone. + if os.name == "posix": + os.killpg(pid, signal.SIGKILL) + else: + os.kill(pid, signal.SIGTERM) + except ProcessLookupError: + pass + return True + + +def session_name(value): + if not re.fullmatch(r"[A-Za-z0-9_-]{1,40}", value): + raise ValueError("Session names must contain 1–40 letters, digits, hyphens or underscores") + return "helm-torrent-" + value + + +def tmux_command(*arguments, check=True): + if shutil.which("tmux") is None: + raise RuntimeError("Install tmux to create or attach a terminal session (Termux: pkg install tmux)") + return subprocess.run( + ["tmux", "-L", os.environ.get("HELM_TMUX_SOCKET", "helm-torrent"), *arguments], + check=check, + capture_output=True, + text=True, + timeout=10, + ) + + +def start_session(name, arguments): + target = session_name(name) + exists = tmux_command("has-session", "-t", "=" + target, check=False) + if exists.returncode == 0: + raise ValueError("Session already exists; use helm-torrent attach " + name) + command = [sys.executable, "-m", "helm.cli", *child_arguments(arguments)] + if not any(argument in ("ui", "search", "indexers") for argument in command[3:]): + command.append("ui") + environment = child_environment() + forwarded = [ + item for key in SESSION_ENVIRONMENT if key in environment for item in ("-e", key + "=" + environment[key]) + ] + tmux_command("new-session", "-d", "-s", target, "-c", os.getcwd(), *forwarded, "--", *command) + return target + + +def attach_session(name): + target = session_name(name) + result = tmux_command("has-session", "-t", "=" + target, check=False) + if result.returncode: + raise ValueError("No running Helm session named " + name) + os.execvp( + "tmux", ["tmux", "-L", os.environ.get("HELM_TMUX_SOCKET", "helm-torrent"), "attach-session", "-t", "=" + target] + ) diff --git a/src/helm/core/search_runner.py b/src/helm/core/search_runner.py new file mode 100644 index 0000000..2352071 --- /dev/null +++ b/src/helm/core/search_runner.py @@ -0,0 +1,174 @@ +"""Isolated Lite jobs with a shared deadline and bounded process cleanup.""" + +import concurrent.futures +import contextlib +import io +import json +import os +import signal +import subprocess +import sys +import threading +import time +from dataclasses import asdict, dataclass + +from helm.core.config_manager import worker_count +from helm.core.logger import get_logger +from helm.core.rss_fetcher import SearchResults, SourceOutcome, TorrentItem, source_status +from helm.core.runtime import child_environment + +logger = get_logger(__name__) + + +@dataclass +class SearchJob: + source: str + kind: str + target: str + + +def stop_worker(process): + """Reap a worker and its POSIX process group, even after the leader exits.""" + if os.name == "posix": + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + elif os.name == "nt": + try: + subprocess.run( + ["taskkill", "/PID", str(process.pid), "/T", "/F"], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=1, + check=False, + ) + except (OSError, subprocess.TimeoutExpired): + pass + if process.poll() is None: + process.kill() + elif process.poll() is None: + process.kill() + try: + process.communicate(timeout=1) + except subprocess.TimeoutExpired: + process.kill() + process.communicate(timeout=1) + + +def run_searches(jobs, query, content_type="video", timeout=30, max_workers=None): + max_workers = worker_count(max_workers) + if timeout <= 0: + raise ValueError("Search budget must be positive") + deadline = time.monotonic() + timeout + cancelled = threading.Event() + active = set() + lock = threading.Lock() + + def run(job): + if cancelled.is_set() or time.monotonic() >= deadline: + return SearchResults([], [SourceOutcome(job.source, "budget_exhausted")]) + environment = child_environment() + process = None + try: + with lock: + if cancelled.is_set(): + return SearchResults([], [SourceOutcome(job.source, "cancelled")]) + process = subprocess.Popen( + [sys.executable, "-m", "helm.core.search_runner", "--worker"], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + env=environment, + start_new_session=os.name == "posix", + ) + active.add(process) + payload = json.dumps({"job": asdict(job), "query": query, "content_type": content_type}) + while not cancelled.is_set(): + remaining = deadline - time.monotonic() + if remaining <= 0: + return SearchResults([], [SourceOutcome(job.source, "timeout")]) + try: + stdout, stderr = process.communicate(input=payload, timeout=min(remaining, 0.1)) + if stderr: + logger.debug("Worker %s: %s", job.source, stderr[-4096:]) + if process.returncode: + raise RuntimeError("Search worker exited without results") + data = json.loads(stdout) + return SearchResults( + [TorrentItem(**item) for item in data["items"]], + [SourceOutcome(**outcome) for outcome in data["outcomes"]], + ) + except subprocess.TimeoutExpired: + payload = None # communicate resumes the original input/output + return SearchResults([], [SourceOutcome(job.source, "cancelled")]) + except Exception as error: + logger.debug("Worker %s failed", job.source, exc_info=True) + return SearchResults([], [SourceOutcome(job.source, source_status(error))]) + finally: + if process is not None: + stop_worker(process) + with lock: + active.discard(process) + + pool = concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) + futures = [] + try: + futures = [pool.submit(run, job) for job in jobs] + results = SearchResults() + # Input order keeps source precedence stable between identical searches. + for future in futures: + results.extend(future.result()) + return results + finally: + cancelled.set() + for future in futures: + future.cancel() + # Workers observe cancellation every 100ms. No abandoned executor threads. + pool.shutdown(wait=True) + with lock: + for process in active: + stop_worker(process) + + +def execute_job(job, query, content_type): + if job.kind == "inline": + from helm.core import lite_fetcher + + functions = { + "apibay": lite_fetcher._fetch_apibay, + "csv": lite_fetcher._fetch_torrents_csv, + "nyaa": lite_fetcher._fetch_nyaa, + } + return functions[job.target](query) + if job.kind == "plugin": + from helm.core.lite_plugin_loader import _execute_plugin, load_plugin + + plugin = load_plugin(job.target) + return _execute_plugin(plugin, query, content_type) + raise ValueError("Unknown search job kind") + + +def worker(): + from helm.core.logger import configure_logging + + # The parent captures and files these diagnostics at DEBUG. Workers never + # rotate a shared log file or write directly into the user's console. + configure_logging(file_logging=False, verbose=True) + request = json.load(sys.stdin) + job = SearchJob(**request["job"]) + try: + # Plugins must not interleave prints with the worker protocol. + with contextlib.redirect_stdout(io.StringIO()): + result = execute_job(job, request["query"], request["content_type"]) + except Exception as error: + logger.debug("Job failed", exc_info=True) + result = SearchResults([], [SourceOutcome(job.source, source_status(error))]) + json.dump({"items": [vars(item) for item in result], "outcomes": [asdict(o) for o in result.outcomes]}, sys.stdout) + + +if __name__ == "__main__": + if sys.argv[1:] != ["--worker"]: + raise SystemExit("This module is an internal search worker") + worker() diff --git a/src/helm/core/secret_manager.py b/src/helm/core/secret_manager.py index 08dc605..8b139b6 100644 --- a/src/helm/core/secret_manager.py +++ b/src/helm/core/secret_manager.py @@ -17,11 +17,14 @@ """ import os +import re import tempfile +from urllib.parse import quote, quote_plus from helm.core.config_manager import SECRET_KEYS, get_config_dir _SECRETS_CACHE = None +_SECRETS_CACHE_PATH = None def get_secrets_file(): @@ -34,11 +37,12 @@ def _ensure_parent_dir(): def load_secrets(): """Return a dict of all stored secrets, reading the file fresh if not cached.""" - global _SECRETS_CACHE - if _SECRETS_CACHE is not None: + global _SECRETS_CACHE, _SECRETS_CACHE_PATH + secrets_path = get_secrets_file() + if _SECRETS_CACHE is not None and _SECRETS_CACHE_PATH == secrets_path: return dict(_SECRETS_CACHE) - secrets_path = get_secrets_file() + _SECRETS_CACHE_PATH = secrets_path if not os.path.exists(secrets_path): _SECRETS_CACHE = {} return {} @@ -137,13 +141,42 @@ def migrate_config_secrets(config): return config +def redact_text(value): + """Redact known secret values, URL credentials, query keys and auth headers.""" + text = str(value) + secrets = list(load_secrets().values()) + [os.environ.get(key, "") for key in SECRET_KEYS] + encoded = { + variant for secret in secrets if secret for variant in (secret, quote(secret, safe=""), quote_plus(secret)) + } + for secret in sorted(encoded, key=len, reverse=True): + text = text.replace(secret, "***REDACTED***") + text = re.sub(r"(https?://)[^/@\s]+:[^/@\s]+@", r"\1***REDACTED***@", text, flags=re.I) + text = re.sub(r"(authorization\s*[:=]\s*)(?:bearer|basic)\s+[^\s,;]+", r"\1***REDACTED***", text, flags=re.I) + text = re.sub( + r"((?:[\w-]*(?:api[_-]?key|password|passwd|secret|token))[\"']?\s*[:=]\s*[\"']?)([^\s&\"',;)}]+)", + r"\1***REDACTED***", + text, + flags=re.I, + ) + return text + + def redact_config(config): - """Return a copy of *config* with every secret value replaced.""" - redacted = dict(config) - for key in SECRET_KEYS: - if key in redacted: - redacted[key] = "***REDACTED***" - return redacted + """Redact nested settings and credential-bearing URLs without changing input.""" + + def clean(value): + if isinstance(value, dict): + return { + key: "***REDACTED***" + if re.search(r"api.?key|password|passwd|secret|token", str(key), re.I) + else clean(item) + for key, item in value.items() + } + if isinstance(value, (list, tuple)): + return [clean(item) for item in value] + return redact_text(value) if isinstance(value, str) else value + + return clean(config) def sanitize_link(link): diff --git a/src/helm/core/server.py b/src/helm/core/server.py new file mode 100644 index 0000000..783b97f --- /dev/null +++ b/src/helm/core/server.py @@ -0,0 +1,244 @@ +"""Authenticated local job API and range streaming for verified finished files.""" + +import hmac +import ipaddress +import json +import os +import re +import secrets +import signal +import stat +import sys +import threading +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path +from urllib.parse import quote, unquote, urlsplit + +from helm.core.config_manager import get_dl_dir +from helm.core.jobs import JobStore, cancel_job, public_job, queue_loop +from helm.core.logger import get_logger +from helm.core.secret_manager import get_secret, set_secrets +from helm.core.torrent_links import validate_magnet + +logger = get_logger(__name__) + + +# Bounds how long a stalled client can hold a handler thread. +REQUEST_TIMEOUT = 30 + + +def is_loopback(host): + try: + return ipaddress.ip_address(host).is_loopback + except ValueError: + return host == "localhost" + + +def byte_range(header, size): + if header is None: + return 0, max(0, size - 1), False + match = re.fullmatch(r"bytes=(\d*)-(\d*)", header) + if not match or size <= 0: + raise ValueError("Invalid range") + first, last = match.groups() + if not first: + if not last or int(last) <= 0: + raise ValueError("Invalid suffix range") + return max(0, size - int(last)), size - 1, True + start = int(first) + end = min(size - 1, int(last)) if last else size - 1 + if start > end or start >= size: + raise ValueError("Range outside file") + return start, end, True + + +def api_handler(store, token, read_only=False): + class Handler(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + timeout = REQUEST_TIMEOUT + + def log_message(self, format, *args): + logger.info("HTTP %s", format % args) + + def authorized(self): + value = self.headers.get("Authorization", "") + if not hmac.compare_digest(value.encode(), ("Bearer " + token).encode()): + self.send_json(401, {"error": "Bearer authentication required"}) + self.close_connection = True + return False + return True + + def send_json(self, status, value): + body = json.dumps(value).encode() + self.send_response(status) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.send_header("Cache-Control", "no-store") + self.end_headers() + if self.command != "HEAD": + self.wfile.write(body) + + def do_POST(self): + if not self.authorized(): + return + if read_only: + self.send_json(403, {"error": "This file server is read-only"}) + self.close_connection = True + return + if urlsplit(self.path).path != "/jobs": + self.send_json(404, {"error": "Not found"}) + self.close_connection = True + return + try: + length = int(self.headers.get("Content-Length", "0")) + if not 0 < length <= 65536: + self.send_json(413, {"error": "JSON body must be between 1 and 65536 bytes"}) + self.close_connection = True + return + if self.headers.get("Content-Type", "").split(";", 1)[0] != "application/json": + raise ValueError("Expected application/json") + data = json.loads(self.rfile.read(length)) + source = data.get("source") + if not isinstance(source, str): + raise ValueError("A source string is required") + scheme = urlsplit(source).scheme.lower() + if scheme == "magnet": + validate_magnet(source) + elif scheme not in ("http", "https") or not urlsplit(source).hostname: + raise ValueError("Only magnet and HTTP(S) links can be submitted remotely") + job = store.enqueue(source, self.server.lite) + self.send_json(202, public_job(job)) + except (ValueError, TypeError, AttributeError, RecursionError): + # The body may be unread, so it cannot be left to parse as a request. + self.close_connection = True + self.send_json(400, {"error": "Invalid source or JSON body"}) + + def do_DELETE(self): + if not self.authorized(): + return + identifier = urlsplit(self.path).path[len("/jobs/") :] if self.path.startswith("/jobs/") else "" + if read_only: + self.send_json(403, {"error": "This file server is read-only"}) + return + if not re.fullmatch(r"[a-f0-9]{32}", identifier): + self.send_json(404, {"error": "Not found"}) + return + try: + changed = cancel_job(store, identifier) + self.send_json(200 if changed else 409, {"cancelled": changed}) + except KeyError: + self.send_json(404, {"error": "Job not found"}) + + def do_HEAD(self): + self.do_GET() + + def do_GET(self): + if not self.authorized(): + return + path = urlsplit(self.path).path + if path == "/health": + self.send_json(200, {"status": "ok", "read_only": read_only}) + elif path == "/jobs": + self.send_json(200, [public_job(job) for job in store.list()]) + elif path.startswith("/jobs/"): + job = store.get(path[len("/jobs/") :]) + self.send_json(200 if job else 404, public_job(job) if job else {"error": "Job not found"}) + elif path == "/files": + self.send_json(200, store.files()) + elif path.startswith("/files/"): + self.stream_file(unquote(path[len("/files/") :])) + else: + self.send_json(404, {"error": "Not found"}) + + def stream_file(self, relative): + root = Path(get_dl_dir()).resolve() + file = root / relative + try: + resolved = file.resolve() + if store.file_entry(relative) is None or root not in resolved.parents or file.is_symlink(): + self.send_json(404, {"error": "Completed file not found"}) + return + # O_NOFOLLOW and fstat close the race between the checks and the open. + descriptor = os.open(str(resolved), os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0)) + with os.fdopen(descriptor, "rb") as stream: + details = os.fstat(stream.fileno()) + if not stat.S_ISREG(details.st_mode): + self.send_json(404, {"error": "Completed file not found"}) + return + size = details.st_size + try: + start, end, partial = byte_range(self.headers.get("Range"), size) + except ValueError: + self.send_response(416) + self.send_header("Content-Range", f"bytes */{size}") + self.send_header("Content-Length", "0") + self.end_headers() + return + count = 0 if size == 0 else end - start + 1 + self.send_response(206 if partial else 200) + self.send_header("Content-Type", "application/octet-stream") + self.send_header("Content-Length", str(count)) + self.send_header("Accept-Ranges", "bytes") + self.send_header("Cache-Control", "no-store") + self.send_header("Content-Disposition", "inline; filename*=UTF-8''" + quote(resolved.name)) + if partial: + self.send_header("Content-Range", f"bytes {start}-{end}/{size}") + self.end_headers() + if self.command == "HEAD" or not count: + return + # A file truncated mid-send must not leave the client awaiting bytes. + if self.connection.sendfile(stream, start, count) != count: + self.close_connection = True + except FileNotFoundError: + self.send_json(404, {"error": "Completed file not found"}) + except OSError: + self.close_connection = True + + return Handler + + +def make_server(host, port, store=None, token=None, lite=False, read_only=False): + store = store or JobStore() + token = token or get_secret("HELM_SERVER_TOKEN") + if not token: + token = secrets.token_urlsafe(32) + set_secrets({"HELM_SERVER_TOKEN": token}) + if len(token) < 16: + raise ValueError("HELM_SERVER_TOKEN must have at least 16 characters") + server = ThreadingHTTPServer((host, port), api_handler(store, token, read_only)) + server.daemon_threads = True + server.lite = lite + return server, store + + +def run_server(host="127.0.0.1", port=8765, lite=False, read_only=False, stop=None): + server, store = make_server(host, port, lite=lite, read_only=read_only) + stop = stop or threading.Event() + previous_signals = {} + if threading.current_thread() is threading.main_thread(): + for signum in (signal.SIGTERM, signal.SIGINT): + previous_signals[signum] = signal.signal(signum, lambda *_: stop.set()) + worker = None + if not read_only: + worker = threading.Thread(target=queue_loop, args=(store, stop), name="helm-http-queue") + worker.start() + print( + f"Listening on http://{host}:{server.server_port}; Bearer token: HELM_SERVER_TOKEN in secrets.env or environment", + flush=True, + ) + if not is_loopback(host): + print("Warning: plain HTTP exposes the token on this network; use a VPN or TLS proxy.", file=sys.stderr) + serving = threading.Thread(target=server.serve_forever, name="helm-http", daemon=True) + serving.start() + try: + stop.wait() + finally: + stop.set() + server.shutdown() + serving.join() + server.server_close() + if worker: + worker.join() + for signum, handler in previous_signals.items(): + signal.signal(signum, handler) + return 0 diff --git a/src/helm/core/stack_benchmark.py b/src/helm/core/stack_benchmark.py new file mode 100644 index 0000000..d0e1e2e --- /dev/null +++ b/src/helm/core/stack_benchmark.py @@ -0,0 +1,560 @@ +"""Disposable production stack exercise with cgroup verification and raw samples.""" + +import argparse +import hashlib +import json +import os +import re +import secrets +import socket +import subprocess +import tempfile +import threading +import time +import uuid +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path +from urllib.parse import parse_qs, urlsplit + +import requests + +from helm.core.benchmark import container_metadata +from helm.core.secret_manager import redact_text +from helm.core.torrent_links import metadata_source + +DEFAULT_IMAGES = { + "jackett": "sha256:d39ca96018ff40dc20730d80f96195a784ec71b1fb647b86a6db1d01431c85c5", + "prowlarr": "sha256:48cd1d7e2a8b73178829c03e0606b8c820d067d6f7d7d92328573eb311e3e521", + "qbittorrent": "sha256:66af76dac14d022d43e060ee2970bf149309b463346c45a37fa844a6265bcdc0", + "flaresolverr": "sha256:894893ed4d4557764df3e74d27c5bc1b3944e5a33ed410e62ab7c744b348f415", +} +# qBittorrent prints its first-run WebUI password in a sentence generic redaction misses. +TEMPORARY_PASSWORD = re.compile(r"(temporary password[^:\n]*:\s*)\S+", re.IGNORECASE) +PORTS = {"jackett": 9117, "prowlarr": 9696, "qbittorrent": 18080, "flaresolverr": 8191} + + +def load_images(manifest=None, overrides=()): + """Merge the recorded defaults with a JSON manifest and service=image overrides.""" + images = dict(DEFAULT_IMAGES) + if manifest: + images.update(json.loads(Path(manifest).read_text())) + for override in overrides: + name, separator, image = override.partition("=") + if not separator or not image: + raise ValueError("Image overrides use service=image") + images[name] = image + unknown = set(images) - set(PORTS) + if unknown: + raise ValueError("Unknown services: " + ", ".join(sorted(unknown))) + return images + + +def scrub_logs(text, secrets_to_remove): + for value in secrets_to_remove: + text = text.replace(value, "***REDACTED***") + return redact_text(TEMPORARY_PASSWORD.sub(r"\1***REDACTED***", text)) + + +def command(engine, *arguments, timeout=120): + return subprocess.run( + [engine, *arguments], check=True, capture_output=True, text=True, timeout=timeout + ).stdout.strip() + + +def cgroup_path(pid): + text = Path(f"/proc/{pid}/cgroup").read_text() + relative = next(line.split("::", 1)[1] for line in text.splitlines() if line.startswith("0::")) + path = Path("/sys/fs/cgroup") / relative.lstrip("/") + if Path("/sys/fs/cgroup") not in path.resolve().parents: + raise ValueError("Cgroup path escaped cgroup root") + return path + + +def read_cgroup(path): + memory = int((path / "memory.current").read_text()) + cpu = dict(line.split() for line in (path / "cpu.stat").read_text().splitlines()) + return {"memory_current_bytes": memory, "cpu_usage_usec": int(cpu["usage_usec"])} + + +def verify_limits(path, memory_bytes, cpus=0.5): + memory = (path / "memory.max").read_text().strip() + quota, period = (path / "cpu.max").read_text().split() + effective = None if quota == "max" else int(quota) / int(period) + return { + "memory_max": memory, + "cpu_max": f"{quota} {period}", + "verified": memory == str(memory_bytes) and effective is not None and abs(effective - cpus) < 0.00001, + } + + +def fixture_handler(source): + class Handler(BaseHTTPRequestHandler): + def log_message(self, *args): + pass + + def do_GET(self): + query = parse_qs(urlsplit(self.path).query).get("q", ["Helm Benchmark"])[0] + import html + + body = ( + f'' + f'
{html.escape(query)} Linux ISO' + f'Download{source["size"]} B
' + ).encode() + self.send_response(200) + self.send_header("Content-Type", "text/html; charset=utf-8") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + return Handler + + +def peer_addresses(routes, hosts): + """Order host addresses by directness: the network gateway, then the alias.""" + addresses = [] + for line in routes.splitlines(): + fields = line.split() + if fields[:2] == ["default", "via"]: + addresses.append(fields[2]) + addresses.extend(line.split()[0] for line in hosts.splitlines() if line.strip()) + return list(dict.fromkeys(addresses)) + + +def free_port(): + with socket.socket() as probe: + probe.bind(("0.0.0.0", 0)) + return probe.getsockname()[1] + + +def seed_payload(directory, size_bytes): + import libtorrent as lt + + directory.mkdir() + payload = directory / "generated-payload.bin" + block = bytes(range(256)) * 4096 + with payload.open("wb") as stream: + remaining = size_bytes + while remaining: + chunk = block[: min(remaining, len(block))] + stream.write(chunk) + remaining -= len(chunk) + storage = lt.file_storage() + lt.add_files(storage, str(payload)) + create = lt.create_torrent(storage, 256 * 1024) + lt.set_piece_hashes(create, str(directory)) + data = lt.bencode(create.generate()) + session = lt.session( + { + # libtorrent expands 0.0.0.0 per interface; port 0 would differ on each. + "listen_interfaces": f"0.0.0.0:{free_port()}", + "enable_dht": False, + "enable_lsd": False, + "enable_upnp": False, + "enable_natpmp": False, + "enable_incoming_utp": False, + "enable_outgoing_utp": False, + } + ) + params = lt.add_torrent_params() + params.ti = lt.torrent_info(lt.bdecode(data)) + params.save_path = str(directory) + params.flags |= lt.torrent_flags.seed_mode + params.flags &= ~lt.torrent_flags.paused + params.flags &= ~lt.torrent_flags.auto_managed + session.add_torrent(params) + return session, data, hashlib.sha256(payload.read_bytes()).hexdigest() + + +class Stack: + def __init__(self, engine, directory, fixture_port, images=None): + self.engine = engine + self.directory = Path(directory) + self.images = images or DEFAULT_IMAGES + self.project = "helm-bench-" + uuid.uuid4().hex[:10] + self.ids = {} + self.urls = {} + self.cgroups = {} + self.limits = {} + self.keys = {name: secrets.token_hex(16) for name in ("jackett", "prowlarr")} + self.fixture_port = fixture_port + self.network_created = False + + def prepare(self): + for name in PORTS: + (self.directory / name).mkdir() + (self.directory / "downloads").mkdir() + jackett = self.directory / "jackett" / "Jackett" + jackett.mkdir() + (jackett / "ServerConfig.json").write_text( + json.dumps( + { + "Port": 9117, + "AllowExternal": True, + "APIKey": self.keys["jackett"], + "UpdateDisabled": True, + "FlareSolverrUrl": f"http://{self.project}-flaresolverr:8191", + } + ) + ) + definitions = self.directory / "jackett" / "cardigann" / "definitions" + definitions.mkdir(parents=True) + (definitions / "helmbenchmark.yml").write_text(f"""--- +id: helmbenchmark +name: Helm Benchmark Fixture +description: Generated local benchmark content +language: en-US +type: public +encoding: UTF-8 +links: + - http://host.docker.internal:{self.fixture_port}/ +caps: + categorymappings: + - {{id: 1, cat: PC/ISO}} + modes: + search: [q] +settings: [] +search: + paths: + - path: search + inputs: + q: "{{{{ .Keywords }}}}" + rows: + selector: tr.result + fields: + category: + text: 1 + title: + selector: a.title + details: + selector: a.title + attribute: href + download: + selector: a.download + attribute: href + size: + selector: td.size + seeders: + text: 1 + leechers: + text: 0 + date: + text: now +""") + (self.directory / "prowlarr" / "config.xml").write_text( + f"*9696{self.keys['prowlarr']}ExternalDisabledForLocalAddressesFalseinfoDocker" + ) + qb = self.directory / "qbittorrent" / "qBittorrent" + qb.mkdir() + (qb / "qBittorrent.conf").write_text(r"""[BitTorrent] +Session\BTProtocol=TCP +Session\DHTEnabled=false +Session\LSDEnabled=false +Session\PeXEnabled=false +Session\DefaultSavePath=/downloads +[Preferences] +WebUI\Username=admin +WebUI\LocalHostAuth=false +WebUI\AuthSubnetWhitelistEnabled=true +WebUI\AuthSubnetWhitelist=127.0.0.1/32, 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16 +WebUI\HostHeaderValidation=false +""") + + def start(self): + command(self.engine, "network", "create", "--label", "com.docker.compose.project=" + self.project, self.project) + self.network_created = True + for name, port in PORTS.items(): + memory_mib = 512 if name == "flaresolverr" else 256 + args = [ + "run", + "-d", + "--name", + self.project + "-" + name, + "--network", + self.project, + "--label", + "com.docker.compose.project=" + self.project, + "--label", + "com.docker.compose.service=" + name, + "--memory", + f"{memory_mib}m", + "--cpus", + "0.5", + "--security-opt", + "label=disable", + "--add-host", + "host.docker.internal:host-gateway", + "-p", + f"127.0.0.1::{port}", + ] + if name != "flaresolverr": + user = 0 if self.engine == "podman" else os.getuid() + group = 0 if self.engine == "podman" else os.getgid() + args += ["-e", f"PUID={user}", "-e", f"PGID={group}", "-v", str(self.directory / name) + ":/config"] + if name == "qbittorrent": + args += ["-e", "WEBUI_PORT=18080", "-v", str(self.directory / "downloads") + ":/downloads"] + args.append(self.images[name]) + identifier = command(self.engine, *args) + self.ids[name] = identifier + published = command(self.engine, "port", identifier, f"{port}/tcp").splitlines()[0] + self.urls[name] = "http://" + published + self.wait_ready() + for name, identifier in self.ids.items(): + raw = json.loads(command(self.engine, "inspect", identifier))[0] + path = cgroup_path(raw["State"]["Pid"]) + self.cgroups[name] = path + self.limits[name] = verify_limits(path, (512 if name == "flaresolverr" else 256) * 1024**2) + if not self.limits[name]["verified"]: + raise RuntimeError("Effective cgroup limits differ for " + name) + + def wait_ready(self, timeout=120): + paths = { + "jackett": "/UI/Dashboard", + "prowlarr": "/ping", + "qbittorrent": "/api/v2/app/version", + "flaresolverr": "/", + } + deadline = time.monotonic() + timeout + for name, path in paths.items(): + while True: + try: + response = requests.get(self.urls[name] + path, timeout=2) + if response.status_code in (200, 401): + break + except requests.RequestException: + pass + if time.monotonic() >= deadline: + raise TimeoutError("Production service did not become ready: " + name) + time.sleep(0.5) + + def configure_indexers(self): + session = requests.Session() + # The config API redirects to the login page until this sets a session cookie. + session.get(self.urls["jackett"] + "/UI/Dashboard", timeout=20).raise_for_status() + url = self.urls["jackett"] + "/api/v2.0/indexers/helmbenchmark/config" + response = session.get(url, timeout=10) + response.raise_for_status() + response = session.post(url, json=response.json(), timeout=20) + response.raise_for_status() + base = self.urls["prowlarr"] + headers = {"X-Api-Key": self.keys["prowlarr"]} + response = requests.get(base + "/api/v1/indexer/schema", headers=headers, timeout=20) + response.raise_for_status() + schema = next(item for item in response.json() if item.get("implementation") == "Torznab") + schema.update(name="Helm local benchmark", enable=True, appProfileId=1, priority=25) + for field in schema["fields"]: + if field["name"] == "baseUrl": + field["value"] = f"http://{self.project}-jackett:9117" + elif field["name"] == "apiPath": + field["value"] = "/api/v2.0/indexers/helmbenchmark/results/torznab/api" + elif field["name"] == "apiKey": + field["value"] = self.keys["jackett"] + response = requests.post(base + "/api/v1/indexer", headers=headers, json=schema, timeout=30) + response.raise_for_status() + + def stop(self): + if self.ids: + command(self.engine, "stop", "--time", "5", *self.ids.values(), timeout=40) + + def cleanup(self): + errors = [] + if self.ids: + try: + command(self.engine, "rm", "-f", *self.ids.values(), timeout=40) + except Exception as error: + errors.append(redact_text(error)) + if self.network_created: + try: + command(self.engine, "network", "rm", self.project) + except Exception as error: + errors.append(redact_text(error)) + return errors + + +def run_engine(engine, repeats=1, images=None, payload_mib=16): + phase = ["startup"] + samples = [] + stop = threading.Event() + source = {"magnet": "", "size": payload_mib * 1024**2} + fixture = ThreadingHTTPServer(("0.0.0.0", 0), fixture_handler(source)) + fixture_thread = threading.Thread(target=fixture.serve_forever, daemon=True) + fixture_thread.start() + report = { + "engine": engine, + "samples": samples, + "trials": [], + "metric": "memory.current bytes and cpu.stat usage_usec per cgroup; do not add to host PSS", + "errors": [], + } + temporary = tempfile.TemporaryDirectory(prefix="helm-stack-") + stack = Stack(engine, temporary.name, fixture.server_port, images) + seeder = None + sampler = None + started = time.monotonic() + + def sample_loop(): + while not stop.is_set(): + services = {} + for name, path in list(stack.cgroups.items()): + try: + services[name] = read_cgroup(path) + except (OSError, ValueError): + services[name] = {"unavailable": True} + samples.append({"elapsed_seconds": time.monotonic() - started, "phase": phase[0], "services": services}) + stop.wait(0.1) + + try: + stack.prepare() + stack.start() + report["project"] = stack.project + report["limits"] = stack.limits + report["metadata"] = container_metadata(engine, stack.project) + # Reach the host through addresses the container routes, without exposing peers publicly. + hosts = command(engine, "exec", stack.ids["qbittorrent"], "getent", "hosts", "host.docker.internal") + routes = command(engine, "exec", stack.ids["qbittorrent"], "ip", "route", "show", "default") + gateways = peer_addresses(routes, hosts) + seeder, data, checksum = seed_payload(Path(temporary.name) / "seed", payload_mib * 1024**2) + resolved = metadata_source(data) + peers = "|".join(f"{address}:{seeder.listen_port()}" for address in gateways) + source["magnet"] = resolved.magnet + f"&x.pe={gateways[0]}:{seeder.listen_port()}" + stack.configure_indexers() + sampler = threading.Thread(target=sample_loop) + sampler.start() + for trial in range(repeats): + phase[0] = "idle" + time.sleep(1) + phase[0] = "search" + search_started = time.monotonic() + releases = [] + for number in range(5): + response = requests.get( + stack.urls["prowlarr"] + "/api/v1/search", + headers={"X-Api-Key": stack.keys["prowlarr"]}, + params={"query": f"Helm Benchmark {trial} {number}", "type": "search"}, + timeout=30, + ) + response.raise_for_status() + releases = response.json() + if not releases: + raise RuntimeError("Production Prowlarr→Jackett fixture search returned no results") + search_seconds = time.monotonic() - search_started + phase[0] = "download" + download_started = time.monotonic() + qb = stack.urls["qbittorrent"] + response = requests.post( + qb + "/api/v2/torrents/add", + files={"torrents": ("generated.torrent", data, "application/x-bittorrent")}, + data={"savepath": "/downloads", "tags": "helm-benchmark"}, + timeout=15, + ) + response.raise_for_status() + # qBittorrent answers 200 with this body when it refuses a torrent. + if response.text.strip().lower().startswith("fails"): + raise RuntimeError("Production qBittorrent rejected the generated torrent: " + response.text[:200]) + # Generated torrents are hybrid, and qBittorrent keys those by the v2 hash. + deadline = time.monotonic() + 45 + torrent_hash = None + next_peer_add = 0.0 + while True: + response = requests.get(qb + "/api/v2/torrents/info", params={"tag": "helm-benchmark"}, timeout=5) + response.raise_for_status() + entries = response.json() + if entries: + torrent_hash = entries[0]["hash"] + if entries[0].get("progress") == 1: + break + if time.monotonic() >= next_peer_add: + next_peer_add = time.monotonic() + 5 + requests.post( + qb + "/api/v2/torrents/addPeers", + data={"hashes": torrent_hash, "peers": peers}, + timeout=5, + ).raise_for_status() + if time.monotonic() >= deadline: + state = [{key: entry.get(key) for key in ("state", "progress", "num_seeds")} for entry in entries] + raise TimeoutError(f"Production qBittorrent could not complete the generated payload: {state}") + time.sleep(0.2) + target = Path(temporary.name) / "downloads" / "generated-payload.bin" + actual = hashlib.sha256(target.read_bytes()).hexdigest() + if actual != checksum: + raise ValueError("Production download checksum mismatch") + report["trials"].append( + { + "search_requests": 5, + "search_seconds": search_seconds, + "download_seconds": time.monotonic() - download_started, + "payload_bytes": payload_mib * 1024**2, + "sha256": actual, + } + ) + requests.post( + qb + "/api/v2/torrents/delete", data={"hashes": torrent_hash, "deleteFiles": "true"}, timeout=10 + ).raise_for_status() + phase[0] = "teardown" + stack.stop() + time.sleep(0.5) + report["all_containers_stopped"] = all( + not json.loads(command(engine, "inspect", identifier))[0]["State"]["Running"] + for identifier in stack.ids.values() + ) + report["success"] = report["all_containers_stopped"] + except Exception as error: + report["success"] = False + report["errors"].append(redact_text(error)) + for name, identifier in stack.ids.items(): + try: + text = command(engine, "logs", "--tail", "25", identifier) + # Keys are private to this run; remove them even from diagnostic logs. + report.setdefault("failure_logs", {})[name] = scrub_logs(text[-4096:], stack.keys.values()) + except Exception: + pass + finally: + stop.set() + if sampler: + sampler.join() + if seeder: + seeder.pause() + report["cleanup_errors"] = stack.cleanup() + fixture.shutdown() + fixture.server_close() + fixture_thread.join() + try: + temporary.cleanup() + except OSError as error: + report["cleanup_errors"].append(redact_text(error)) + return report + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--engine", choices=["docker", "podman"], required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--repeats", type=int, default=3) + parser.add_argument("--payload-mib", type=int, default=16) + parser.add_argument("--image-manifest", type=Path, help="JSON object mapping services to image references") + parser.add_argument("--image", action="append", default=[], metavar="SERVICE=IMAGE", help="Override one image") + args = parser.parse_args(argv) + if args.repeats < 1 or args.payload_mib < 1: + parser.error("repeats and payload size must be positive") + try: + images = load_images(args.image_manifest, args.image) + except (OSError, ValueError) as error: + parser.error(str(error)) + result = run_engine(args.engine, args.repeats, images, args.payload_mib) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(result, indent=2) + "\n") + print( + json.dumps( + { + "engine": args.engine, + "success": result["success"], + "errors": result["errors"], + "cleanup_errors": result["cleanup_errors"], + } + ) + ) + return 0 if result["success"] and not result["cleanup_errors"] else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/src/helm/core/torrent_links.py b/src/helm/core/torrent_links.py new file mode 100644 index 0000000..8549791 --- /dev/null +++ b/src/helm/core/torrent_links.py @@ -0,0 +1,227 @@ +"""Resolve magnet, torrent metadata, and HTML detail links with bounded I/O.""" + +import base64 +import hashlib +import re +import time +from dataclasses import dataclass +from pathlib import Path +from urllib.parse import parse_qs, quote, urljoin, urlsplit + +from bs4 import BeautifulSoup + +from helm.core.http import get_shared_session + +MAX_METADATA = 8 * 1024 * 1024 + + +@dataclass +class TorrentSource: + magnet: str + data: bytes = b"" + + +def validate_magnet(value): + if len(value) > 65536 or urlsplit(value).scheme.lower() != "magnet": + raise ValueError("Expected a magnet URI") + topics = parse_qs(urlsplit(value).query).get("xt", []) + valid = any( + re.fullmatch(r"urn:btih:(?:[a-fA-F0-9]{40}|[A-Z2-7a-z]{32})", topic) + or re.fullmatch(r"urn:btmh:1220[a-fA-F0-9]{64}", topic) + for topic in topics + ) + if not valid: + raise ValueError("Magnet URI has no supported info hash") + return value + + +def decode_metadata(data): + """Decode bounded bencode, retaining the exact encoded info dictionary.""" + if not data or len(data) > MAX_METADATA: + raise ValueError("Torrent metadata is empty or exceeds 8 MiB") + position = 0 + info_bytes = None + + def read(depth=0): + nonlocal position, info_bytes + if depth > 64 or position >= len(data): + raise ValueError("Invalid torrent metadata nesting") + marker = data[position : position + 1] + if marker == b"i": + end = data.index(b"e", position) + raw = data[position + 1 : end] + if not re.fullmatch(rb"0|-?[1-9][0-9]*", raw): + raise ValueError("Invalid bencode integer") + position = end + 1 + return int(raw) + if marker in (b"d", b"l"): + position += 1 + result = {} if marker == b"d" else [] + while position < len(data) and data[position : position + 1] != b"e": + if marker == b"d": + key = read(depth + 1) + if not isinstance(key, bytes) or key in result: + raise ValueError("Invalid dictionary key") + start = position + result[key] = read(depth + 1) + if depth == 0 and key == b"info": + info_bytes = data[start:position] + else: + result.append(read(depth + 1)) + if position >= len(data): + raise ValueError("Unterminated bencode container") + position += 1 + return result + if marker.isdigit(): + end = data.index(b":", position) + raw = data[position:end] + if not re.fullmatch(rb"0|[1-9][0-9]*", raw): + raise ValueError("Invalid bencode string length") + length = int(raw) + position = end + 1 + if position + length > len(data): + raise ValueError("Truncated bencode string") + value = data[position : position + length] + position += length + return value + raise ValueError("Invalid bencode marker") + + try: + root = read() + except (ValueError, IndexError, OverflowError) as error: + raise ValueError("Invalid torrent metadata") from error + if ( + position != len(data) + or not isinstance(root, dict) + or not isinstance(root.get(b"info"), dict) + or info_bytes is None + ): + raise ValueError("Torrent metadata has no info dictionary") + info = root[b"info"] + if ( + not isinstance(info.get(b"name"), bytes) + or not isinstance(info.get(b"piece length"), int) + or info[b"piece length"] <= 0 + ): + raise ValueError("Invalid torrent info fields") + if b"pieces" not in info and info.get(b"meta version") != 2: + raise ValueError("Torrent has no piece hashes") + if b"pieces" in info: + pieces = info[b"pieces"] + if not isinstance(pieces, bytes) or not pieces or len(pieces) % 20: + raise ValueError("Invalid torrent piece hashes") + length = info.get(b"length") + files = info.get(b"files") + if not (isinstance(length, int) and length >= 0) and not valid_files(files): + raise ValueError("Invalid torrent file list") + return root, info_bytes + + +def valid_files(files): + if not isinstance(files, list) or not files: + return False + for entry in files: + if not isinstance(entry, dict) or not isinstance(entry.get(b"length"), int) or entry[b"length"] < 0: + return False + path = entry.get(b"path") + if not isinstance(path, list) or not path: + return False + if not all(isinstance(part, bytes) and part not in (b"", b".", b"..") and b"/" not in part for part in path): + return False + return True + + +def metadata_source(data): + root, info = decode_metadata(data) + details = root[b"info"] + topics = [] + if b"pieces" in details: + topics.append("xt=urn:btih:" + hashlib.sha1(info).hexdigest()) + if details.get(b"meta version") == 2: + topics.append("xt=urn:btmh:1220" + hashlib.sha256(info).hexdigest()) + topics.append("dn=" + quote(details[b"name"].decode("utf-8", errors="replace"))) + trackers = [] + if isinstance(root.get(b"announce"), bytes): + trackers.append(root[b"announce"]) + for tier in root.get(b"announce-list", []): + if isinstance(tier, list): + trackers.extend(value for value in tier if isinstance(value, bytes)) + for tracker in dict.fromkeys(trackers): + topics.append("tr=" + quote(tracker.decode("utf-8", errors="replace"), safe="")) + return TorrentSource("magnet:?" + "&".join(topics), data) + + +def resolve_torrent(value, timeout=30, max_hops=6, allow_local=True): + if isinstance(value, TorrentSource): + return value + value = str(value).strip() + if value.lower().startswith("magnet:"): + return TorrentSource(validate_magnet(value)) + if allow_local and not urlsplit(value).scheme: + path = Path(value).expanduser() + if not path.is_file() or path.suffix.lower() != ".torrent": + raise ValueError("Expected an existing .torrent file") + with path.open("rb") as stream: + return metadata_source(stream.read(MAX_METADATA + 1)) + deadline = time.monotonic() + timeout + seen = set() + for _ in range(max_hops): + if value in seen: + raise ValueError("Torrent link contains a redirect loop") + seen.add(value) + if urlsplit(value).scheme.lower() not in ("http", "https"): + raise ValueError("Only HTTP(S), magnet URIs and local .torrent files are supported") + remaining = deadline - time.monotonic() + if remaining <= 0: + raise TimeoutError("Torrent link resolution exceeded its deadline") + response = get_shared_session().get(value, timeout=min(10, remaining), stream=True, allow_redirects=False) + try: + response.raise_for_status() + if 300 <= response.status_code < 400: + location = response.headers.get("Location") + if not location: + raise ValueError("Redirect has no Location") + value = urljoin(value, location) + if value.lower().startswith("magnet:"): + return TorrentSource(validate_magnet(value)) + continue + chunks = [] + total = 0 + for chunk in response.iter_content(65536): + if time.monotonic() >= deadline: + raise TimeoutError("Torrent link resolution exceeded its deadline") + total += len(chunk) + if total > MAX_METADATA: + raise ValueError("Torrent response exceeds 8 MiB") + chunks.append(chunk) + data = b"".join(chunks) + if data.startswith(b"d"): + try: + return metadata_source(data) + except ValueError: + pass # Plain text or HTML can also begin with "d". + # Bytes let BeautifulSoup sniff the charset; a server's label may be invalid. + soup = BeautifulSoup(data, "html.parser") + links = [urljoin(value, anchor.get("href", "")) for anchor in soup.find_all("a", href=True)] + magnets = [link for link in links if link.lower().startswith("magnet:")] + if magnets: + return TorrentSource(validate_magnet(magnets[0])) + torrents = [link for link in links if urlsplit(link).path.lower().endswith(".torrent")] + if not torrents: + raise ValueError("Detail page contains no magnet or .torrent link") + value = torrents[0] + finally: + response.close() + raise ValueError("Torrent resolution exceeded its redirect/detail-page limit") + + +def info_hash(magnet): + for topic in parse_qs(urlsplit(magnet).query).get("xt", []): + if topic.lower().startswith("urn:btih:"): + value = topic.rsplit(":", 1)[1] + if len(value) == 32: + return base64.b32decode(value.upper()).hex() + return value.lower() + if topic.lower().startswith("urn:btmh:1220"): + return topic.rsplit(":", 1)[1][4:].lower() + raise ValueError("No supported torrent hash") diff --git a/src/helm/core/watch.py b/src/helm/core/watch.py new file mode 100644 index 0000000..387592b --- /dev/null +++ b/src/helm/core/watch.py @@ -0,0 +1,117 @@ +"""Stable-file ingestion for the durable download queue.""" + +import signal +import threading +import time +import uuid +from pathlib import Path +from urllib.parse import urlsplit + +from helm.core.jobs import JobStore, process_one, queue_loop +from helm.core.logger import get_logger +from helm.core.secret_manager import redact_text +from helm.core.torrent_links import MAX_METADATA + +logger = get_logger(__name__) + + +def scan_directory(directory, store, observed, lite=False, settle=1, now=None): + directory = Path(directory).resolve() + now = time.monotonic() if now is None else now + current = {} + for path in sorted(directory.iterdir()): + if path.is_symlink() or not path.is_file() or path.suffix.lower() not in (".torrent", ".magnet", ".txt"): + continue + try: + stat = path.stat() + except OSError: + continue # Removed between listing and stat. + signature = (stat.st_size, stat.st_mtime_ns) + previous = observed.get(str(path)) + since = previous[1] if previous and previous[0] == signature else now + current[str(path)] = (signature, since) + if now - since < settle: + continue + try: + if stat.st_size > MAX_METADATA: + raise ValueError("Watch input exceeds 8 MiB") + if path.suffix.lower() == ".torrent": + sources = [str(path)] + else: + sources = [ + line.strip() + for line in path.read_text(encoding="utf-8").splitlines() + if line.strip() and not line.lstrip().startswith("#") + ] + if not sources: + raise ValueError("Watch file contains no links") + if any(urlsplit(source).scheme.lower() not in ("magnet", "http", "https") for source in sources): + raise ValueError("Watch files accept only magnet or HTTP(S) links") + identifiers = [job["id"] for job in store.enqueue_many(sources, lite)] + target = directory / ".processed" + if target.is_symlink(): + raise ValueError("Processed directory must not be a symlink") + target.mkdir(exist_ok=True) + path.replace(target / (path.stem + "-" + uuid.uuid4().hex[:8] + path.suffix)) + logger.info("Queued %s download(s) from %s", len(identifiers), path.name) + current.pop(str(path), None) + except Exception as error: + target = directory / ".failed" + if target.is_symlink(): + logger.error("Failed directory must not be a symlink") + continue + target.mkdir(exist_ok=True) + destination = target / (path.stem + "-" + uuid.uuid4().hex[:8] + path.suffix) + if path.exists(): + path.replace(destination) + destination.with_suffix(destination.suffix + ".error.txt").write_text(redact_text(error) + "\n") + logger.warning("Watch input %s failed: %s", path.name, error) + current.pop(str(path), None) + return current + + +def safe_scan(directory, store, observed, lite, settle): + """Keep a long-running watcher alive through a transient filesystem failure.""" + try: + return scan_directory(directory, store, observed, lite, settle=settle) + except OSError: + logger.exception("Cannot scan watch directory %s", directory) + return observed + + +def run_watch(directory, lite=False, interval=1, once=False, enqueue_only=False, stop=None): + if interval <= 0: + raise ValueError("Watch interval must be positive") + directory = Path(directory).expanduser().resolve() + directory.mkdir(parents=True, exist_ok=True) + store = JobStore() + stop = stop or threading.Event() + previous_signals = {} + if threading.current_thread() is threading.main_thread(): + for signum in (signal.SIGTERM, signal.SIGINT): + previous_signals[signum] = signal.signal(signum, lambda *_: stop.set()) + worker = None + if not enqueue_only and not once: + worker = threading.Thread(target=queue_loop, args=(store, stop), name="helm-download-queue") + worker.start() + observed = {} + try: + if once: + observed = scan_directory(directory, store, observed, lite, settle=interval) + stop.wait(interval) + if not stop.is_set(): + scan_directory(directory, store, observed, lite, settle=interval) + if not enqueue_only: + while not stop.is_set() and process_one(store, stop): + pass + return 0 + while not stop.is_set(): + observed = safe_scan(directory, store, observed, lite, interval) + stop.wait(interval) + finally: + stop.set() + if worker: + worker.join() + for signum, handler in previous_signals.items(): + signal.signal(signum, handler) + return 0 diff --git a/src/helm/plugins/bitsearch.py b/src/helm/plugins/bitsearch.py index 0331f3e..2617382 100644 --- a/src/helm/plugins/bitsearch.py +++ b/src/helm/plugins/bitsearch.py @@ -4,8 +4,8 @@ import urllib.parse from bs4 import BeautifulSoup -from helpers import retrieve_url -from novaprinter import prettyPrinter +from helpers import retrieve_url, validate_html +from novaprinter import prettyPrinter, report_error class bitsearch(object): @@ -16,17 +16,20 @@ class bitsearch(object): def search(self, what, cat="all"): query = urllib.parse.quote(what) html = retrieve_url(self.url + f"/search?q={query}") + validate_html(html, ("bg-white",)) soup = BeautifulSoup(html, "html.parser") for item in soup.select("div.bg-white.rounded-lg.shadow-sm"): try: title_elem = item.select_one("h3 a") if not title_elem: + report_error(ValueError("Result row has no title")) continue res = {"name": title_elem.text.strip()} magnet_a = item.select_one('a[href^="magnet:"]') if not magnet_a: + report_error(ValueError("Result row has no magnet")) continue res["link"] = magnet_a["href"] res["desc_link"] = self.url + title_elem["href"] @@ -45,5 +48,6 @@ def search(self, what, cat="all"): res["engine_url"] = self.url prettyPrinter(res) - except Exception: + except Exception as error: + report_error(error) continue diff --git a/src/helm/plugins/bittorrented.py b/src/helm/plugins/bittorrented.py index 8b94f98..b9da8a2 100644 --- a/src/helm/plugins/bittorrented.py +++ b/src/helm/plugins/bittorrented.py @@ -9,7 +9,7 @@ import re import requests -from novaprinter import prettyPrinter +from novaprinter import prettyPrinter, report_error from helm.core.http import get_shared_session from helm.core.logger import get_logger @@ -27,6 +27,7 @@ def map_results(results): for r in results: info_hash = (r.get("torrent_infohash") or "").lower() if not INFO_HASH.match(info_hash): + report_error(ValueError("Invalid info hash in API result")) continue name = r.get("torrent_name") or info_hash out.append( @@ -73,6 +74,7 @@ def search(self, what, cat="all"): payload = r.json() except Exception as e: logger.debug(f"Event: BitTorrented API connection failed: {e}") + report_error(e) return results = (payload or {}).get("results") or [] diff --git a/src/helm/plugins/eztv.py b/src/helm/plugins/eztv.py index 144ee55..0a23b2b 100644 --- a/src/helm/plugins/eztv.py +++ b/src/helm/plugins/eztv.py @@ -7,7 +7,7 @@ # are filtered client-side from the most recent 100 episodes. import requests -from novaprinter import prettyPrinter +from novaprinter import prettyPrinter, report_error from helm.core.http import get_shared_session from helm.core.logger import get_logger @@ -33,6 +33,7 @@ def search(self, what, cat="all"): payload = r.json() except Exception as e: logger.debug(f"Event: EZTV API connection failed: {e}") + report_error(e) return for torrent in payload.get("torrents") or []: @@ -52,7 +53,8 @@ def search(self, what, cat="all"): try: size = int(torrent.get("size_bytes") or 0) - except (TypeError, ValueError): + except (TypeError, ValueError) as error: + report_error(error) size = 0 prettyPrinter( diff --git a/src/helm/plugins/helpers.py b/src/helm/plugins/helpers.py index 539b342..d32a314 100644 --- a/src/helm/plugins/helpers.py +++ b/src/helm/plugins/helpers.py @@ -13,6 +13,7 @@ def retrieve_url(url, request_data=None): r = session.post(url, data=request_data, headers=headers, timeout=15) else: r = session.get(url, headers=headers, timeout=15) + r.raise_for_status() return r.text @@ -21,6 +22,7 @@ def download_file(url, filename=None): Downloads a file to a specific location. Used by qBittorrent search plugins. """ r = get_shared_session().get(url, timeout=15) + r.raise_for_status() if filename: with open(filename, "wb") as f: f.write(r.content) @@ -35,3 +37,13 @@ def htmlentitydecode(s): import html return html.unescape(s) + + +def validate_html(html, markers): + lower = html.lower() + if any(text in lower for text in ("just a moment", "cf-chl-", "captcha")): + raise ValueError("Source returned a challenge page") + if not any(marker.lower() in lower for marker in markers) and not any( + marker in lower for marker in ("no results", "nothing found", "0 results", "no torrents") + ): + raise ValueError("Unrecognized search result page") diff --git a/src/helm/plugins/limetorrents.py b/src/helm/plugins/limetorrents.py index 3cfaa07..cf89701 100644 --- a/src/helm/plugins/limetorrents.py +++ b/src/helm/plugins/limetorrents.py @@ -8,7 +8,7 @@ from typing import Callable, Dict, List, Mapping, Match, Tuple, Union from urllib.parse import quote -from helpers import retrieve_url +from helpers import retrieve_url, validate_html from novaprinter import prettyPrinter @@ -131,6 +131,7 @@ def search(self, query: str, cat: str = "all") -> None: for page in range(1, 5): page_url = f"{self.url}/search/{category}/{query}/seeds/{page}/" html = retrieve_url(page_url) + validate_html(html, ("table2",)) parser = self.MyHtmlParser(self.url) parser.feed(html) parser.close() diff --git a/src/helm/plugins/novaprinter.py b/src/helm/plugins/novaprinter.py index 8412970..8d6642c 100644 --- a/src/helm/plugins/novaprinter.py +++ b/src/helm/plugins/novaprinter.py @@ -1,7 +1,7 @@ import threading from typing import List -from helm.core.rss_fetcher import TorrentItem +from helm.core.rss_fetcher import TorrentItem, source_status class _ThreadLocalResults(threading.local): @@ -10,6 +10,7 @@ class _ThreadLocalResults(threading.local): def __init__(self) -> None: super().__init__() self.items: List[TorrentItem] = [] + self.errors: List[str] = [] _local_results = _ThreadLocalResults() @@ -20,6 +21,15 @@ def get_results() -> List[TorrentItem]: return _local_results.items +def get_errors(): + return _local_results.errors + + +def report_error(error): + """Record a swallowed plugin failure for the loader's source outcome.""" + _local_results.errors.append(source_status(error)) + + def prettyPrinter(result_dict): """ Called by qBittorrent search plugins to yield a parsed torrent result. @@ -57,5 +67,5 @@ def prettyPrinter(result_dict): leechers=leechers, ) _local_results.items.append(item) - except Exception: - pass + except Exception as error: + report_error(error) diff --git a/src/helm/plugins/piratebay.py b/src/helm/plugins/piratebay.py index 2d92ff6..a2dbaf9 100644 --- a/src/helm/plugins/piratebay.py +++ b/src/helm/plugins/piratebay.py @@ -124,9 +124,9 @@ def getBrowserUserAgent() -> str: request = urllib.request.Request(url, None, {"User-Agent": getBrowserUserAgent()}) try: - response: http.client.HTTPResponse = urllib.request.urlopen(request) # pylint: disable=consider-using-with + response: http.client.HTTPResponse = urllib.request.urlopen(request, timeout=15) # pylint: disable=consider-using-with except urllib.error.HTTPError: - return "" + raise data = response.read() diff --git a/src/helm/plugins/subsplease.py b/src/helm/plugins/subsplease.py index d4255ef..8f951d4 100644 --- a/src/helm/plugins/subsplease.py +++ b/src/helm/plugins/subsplease.py @@ -3,11 +3,11 @@ # SubsPlease exposes a small JSON API that returns recent/new anime with magnet # links embedded. It carries no swarm data, so seeders/leechers are reported as -# 0 (the CLI keeps unknown-seed items per the min-seeds filter fix in 0.9.0). +# -1 (unknown counts must survive the min-seeds filter). import re -from novaprinter import prettyPrinter +from novaprinter import prettyPrinter, report_error from helm.core.http import get_shared_session from helm.core.logger import get_logger @@ -49,9 +49,11 @@ def search(self, what, cat="all"): payload = r.json() except Exception as e: logger.debug(f"Event: SubsPlease API connection failed: {e}") + report_error(e) return if not isinstance(payload, dict): + report_error(ValueError("Expected API object")) return for entry in payload.values(): @@ -81,6 +83,7 @@ def search(self, what, cat="all"): parsed = parse_magnet(magnet) if not parsed: + report_error(ValueError("Invalid magnet in API result")) continue info_hash, size = parsed @@ -93,8 +96,8 @@ def search(self, what, cat="all"): "name": name, "link": magnet, "size": f"{size} B", - "seeds": "0", - "leech": "0", + "seeds": "-1", + "leech": "-1", "engine_url": self.url, "desc_link": entry.get("page") or self.url, "pub_date": 0, diff --git a/src/helm/plugins/torlock.py b/src/helm/plugins/torlock.py index 75e0553..f318dc9 100644 --- a/src/helm/plugins/torlock.py +++ b/src/helm/plugins/torlock.py @@ -6,7 +6,7 @@ from html.parser import HTMLParser from typing import Any, Dict, List, Tuple, Union -from helpers import download_file, retrieve_url +from helpers import download_file, retrieve_url, validate_html from novaprinter import prettyPrinter @@ -106,6 +106,7 @@ def search(self, query: str, cat: str = "all") -> None: parser = self.MyHtmlParser(self.url) page_url = f"{self.url}/{category}/torrents/{query}.html?sort=seeds&page={page}" html = retrieve_url(page_url) + validate_html(html, (" None: for currPage in range(0, 5): url = f"{self.url}/browse?t={what}&p={currPage}" html = retrieve_url(url) + validate_html(html, ("similarfiles",)) parser = self.MyHTMLParser(self.url) parser.feed(html) parser.close() diff --git a/src/helm/plugins/x1337.py b/src/helm/plugins/x1337.py index 3bb6c78..180c099 100644 --- a/src/helm/plugins/x1337.py +++ b/src/helm/plugins/x1337.py @@ -10,8 +10,8 @@ import urllib.parse from concurrent.futures import ThreadPoolExecutor, as_completed -from helpers import retrieve_url -from novaprinter import prettyPrinter +from helpers import retrieve_url, validate_html +from novaprinter import prettyPrinter, report_error from helm.core.logger import get_logger @@ -87,12 +87,15 @@ def search(self, what, cat="all"): if not query: return + categories = CATEGORIES if cat == "all" else [{"movies": "Movies", "tv": "TV"}[cat]] + failure = None base = None list_html = None for i in range(len(HOSTS)): host = HOSTS[(_working_host + i) % len(HOSTS)] try: - html = retrieve_url(f"https://{host}{_category_path(query, CATEGORIES[0])}") + html = retrieve_url(f"https://{host}{_category_path(query, categories[0])}") + validate_html(html, ("table-list",)) rows = parse_rows(html) if not rows: continue # empty or a Cloudflare wall page @@ -100,20 +103,24 @@ def search(self, what, cat="all"): list_html = html _set_working_host(host) break - except Exception: + except Exception as error: + failure = error continue if not base: + if failure is not None: + report_error(failure) return rows = parse_rows(list_html) # The "all" category handed to the plugin can be either; search the # other category too so movies and TV overlap is recovered. - for category in CATEGORIES[1:]: + for category in categories[1:]: try: html = retrieve_url(f"{base}{_category_path(query, category)}") rows.extend(parse_rows(html)) - except Exception: + except Exception as error: + report_error(error) continue seen = set() @@ -136,7 +143,8 @@ def search(self, what, cat="all"): path = futures[future] try: magnets[path] = extract_magnet(future.result()) - except Exception: + except Exception as error: + report_error(error) magnets[path] = None for row in unique[:MAX_DETAILS]: diff --git a/src/helm/plugins/yts.py b/src/helm/plugins/yts.py index 2856c97..1e6078c 100644 --- a/src/helm/plugins/yts.py +++ b/src/helm/plugins/yts.py @@ -5,7 +5,7 @@ # same API and returns 200 without Cloudflare as of 2026-08. import requests -from novaprinter import prettyPrinter +from novaprinter import prettyPrinter, report_error from helm.core.http import get_shared_session from helm.core.logger import get_logger @@ -40,9 +40,11 @@ def search(self, what, cat="all"): payload = r.json() except Exception as e: logger.debug(f"Event: YTS API connection failed: {e}") + report_error(e) return if payload.get("status") != "ok": + report_error(ValueError("API rejected query")) logger.debug(f"Event: YTS API returned status {payload.get('status')!r}") return @@ -75,7 +77,8 @@ def search(self, what, cat="all"): break else: size_bytes = int(size_str.replace("B", "").strip()) - except (ValueError, TypeError): + except (ValueError, TypeError) as error: + report_error(error) size_bytes = 0 seeders = torrent.get("seeds", 0) or 0 diff --git a/src/helm/ui/tui.py b/src/helm/ui/tui.py index 52a92b3..3988280 100644 --- a/src/helm/ui/tui.py +++ b/src/helm/ui/tui.py @@ -87,7 +87,9 @@ def animate(): t = threading.Thread(target=animate) t.start() - res = [] + from helm.core.rss_fetcher import SearchResults + + res = SearchResults() used_lite = lite_mode try: import concurrent.futures @@ -95,12 +97,12 @@ def animate(): def fetch_jackett(): from helm.core.rss_fetcher import search_indexers - return search_indexers(query, content_type) + return search_indexers(query, content_type, fallback_lite=False) def fetch_lite(): from helm.core.lite_fetcher import search_lite - return search_lite(query) + return search_lite(query, content_type) if not lite_mode: jackett_future = None @@ -113,17 +115,18 @@ def fetch_lite(): try: res.extend(jackett_future.result()) except Exception as e: - sys.stdout.write("\r" + " " * 30 + "\r") - sys.stdout.write( - f"\n\033[33m[!] Indexer Manager not available ({e}). Auto-falling back to LITE MODE...\033[0m\n" + print( + f"Indexer manager unavailable ({type(e).__name__}); using Lite results.", + file=sys.stderr, ) - sys.stdout.flush() used_lite = True try: res.extend(lite_future.result()) - except Exception: - pass + except Exception as error: + from helm.core.rss_fetcher import SourceOutcome, source_status + + res.outcomes.append(SourceOutcome("Lite", source_status(error))) else: res.extend(fetch_lite()) @@ -132,6 +135,9 @@ def fetch_lite(): if t is not None: t.join() + if res.outcomes: + summary = "; ".join(f"{o.source}: {o.status} ({o.count})" for o in res.outcomes) + print(f"Sources: {summary}", file=sys.stderr) return res, used_lite diff --git a/tests/conftest.py b/tests/conftest.py index e8e5d13..fe55ab2 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -3,7 +3,7 @@ # Isolate the whole session from the real XDG config/state dirs so tests never # touch ~/.config/helm or ~/.local/state/helm. Set before test modules are -# imported (logger.py computes its LOG_DIR at import time). +# imported. Logging is now configured explicitly after CLI path overrides. _TMP_BASE = tempfile.mkdtemp(prefix="helm-tests-") os.environ["HELM_CONFIG_DIR"] = os.path.join(_TMP_BASE, "config") os.environ["HELM_STATE_DIR"] = os.path.join(_TMP_BASE, "state") @@ -16,3 +16,19 @@ def pytest_runtest_setup(item): import helm.core.secret_manager as sm sm._invalidate_cache() + import sys + + printer = sys.modules.get("novaprinter") + if printer is not None: + printer.get_results().clear() + printer.get_errors().clear() + + +def pytest_runtest_teardown(item): + import logging + + root = logging.getLogger() + for handler in list(root.handlers): + if getattr(handler, "_helm_handler", False): + root.removeHandler(handler) + handler.close() diff --git a/tests/test_benchmark.py b/tests/test_benchmark.py new file mode 100644 index 0000000..de4de0f --- /dev/null +++ b/tests/test_benchmark.py @@ -0,0 +1,197 @@ +import json +import sys +from pathlib import Path +from types import SimpleNamespace +from unittest.mock import Mock + +import pytest + +from helm.core import benchmark + + +def fake_proc(root, pid, parent, name, pss): + path = root / str(pid) + path.mkdir(parents=True) + (path / "stat").write_text(f"{pid} ({name}) S {parent} 0 0 0") + (path / "comm").write_text(name + "\n") + if pss is not None: + (path / "smaps_rollup").write_text(f"Rss: 1000 kB\nPss: {pss} kB\n") + + +def test_pss_units_and_invalid_samples(): + assert benchmark.parse_pss("Pss: 12 kB\n") == 12 * 1024 + with pytest.raises(ValueError): + benchmark.parse_pss("Rss: 12 kB\n") + with pytest.raises(ValueError): + benchmark.parse_pss("Pss: 12 MB\n") + + +def test_memory_accounting_uses_disjoint_process_sets(tmp_path): + fake_proc(tmp_path, 1, 0, "workload", 10) + fake_proc(tmp_path, 2, 1, "worker", 20) + fake_proc(tmp_path, 3, 0, "dockerd", 30) + fake_proc(tmp_path, 4, 3, "helper", 40) + fake_proc(tmp_path, 5, 3, "container", 50) + fake_proc(tmp_path, 6, 5, "service", 60) + sample = benchmark.memory_sample(1, [5], True, tmp_path) + assert sample["workload_pss_bytes"] == 30 * 1024 + assert sample["attached_stack_pss_bytes"] == 110 * 1024 + assert sample["engine_pss_bytes"] == 70 * 1024 + assert sample["accounted_pss_bytes"] == 210 * 1024 + assert sample["complete"] is True + + +def test_missing_memory_is_flagged_instead_of_assumed_complete(tmp_path): + fake_proc(tmp_path, 1, 0, "workload", None) + sample = benchmark.memory_sample(1, proc_root=tmp_path) + assert sample["missing_pids"] == [1] + assert sample["complete"] is False + + +def test_summary_excludes_incomplete_samples(): + def sample(value, complete): + return { + "phase": "idle", + "complete": complete, + **{ + key: value + for key in ("workload_pss_bytes", "attached_stack_pss_bytes", "engine_pss_bytes", "accounted_pss_bytes") + }, + } + + summary = benchmark.summarize([sample(10, True), sample(30, True), sample(999, False)]) + assert summary["idle"]["accounted_pss_bytes"] == {"median": 20, "peak": 30} + assert summary["idle"]["incomplete_samples"] == 1 + assert benchmark.summarize([sample(999, False)])["idle"]["accounted_pss_bytes"]["median"] is None + + +def test_container_metadata_drops_secrets_and_records_limits(monkeypatch): + raw = [ + { + "Id": "abc", + "Name": "helm-test", + "State": {"Pid": 123}, + "Image": "sha256:image", + "Config": {"Image": "example/image", "Env": ["PASSWORD=private"]}, + "HostConfig": {"Memory": 1000, "NanoCpus": 500000000}, + } + ] + + def run(command, **kwargs): + if "inspect" in command: + output = json.dumps(raw) + elif "version" in command: + output = "test-version" + else: + assert "label=com.docker.compose.project=helm" in command + output = "abc\n" + return SimpleNamespace(stdout=output) + + monkeypatch.setattr(benchmark.subprocess, "run", run) + metadata = benchmark.container_metadata("docker", "helm") + assert "private" not in json.dumps(metadata) + assert metadata["containers"][0]["memory_limit_bytes"] == 1000 + assert metadata["containers"][0]["image_id"] == "sha256:image" + + +def test_local_download_validates_generated_payload_and_pauses(monkeypatch, tmp_path): + seed, client = Mock(), Mock() + handle = Mock() + handle.status.return_value = SimpleNamespace(is_seeding=True) + + def add(params): + source = tmp_path / "seed" / "payload.bin" + (Path(params.save_path) / "payload.bin").write_bytes(source.read_bytes()) + return handle + + client.add_torrent.side_effect = add + sessions = iter([seed, client]) + create = Mock() + create.generate.return_value = {} + module = SimpleNamespace( + file_storage=lambda: object(), + add_files=lambda *args: None, + create_torrent=lambda *args: create, + set_piece_hashes=lambda *args: None, + torrent_info=lambda value: value, + session=lambda settings: next(sessions), + add_torrent_params=lambda: SimpleNamespace(flags=0), + torrent_flags=SimpleNamespace(seed_mode=1, paused=2, auto_managed=4), + version="fixture", + ) + monkeypatch.setitem(sys.modules, "libtorrent", module) + monkeypatch.setattr(benchmark.time, "sleep", lambda seconds: None) + result = benchmark.local_download(tmp_path, 4096, 1) + assert result["payload_bytes"] == 4096 + assert len(result["sha256"]) == 64 + seed.pause.assert_called_once() + client.pause.assert_called_once() + + +def test_cli_writes_raw_samples_and_reproducible_metadata(monkeypatch, tmp_path): + trial = {"samples": [], "events": [], "summary": {}} + monkeypatch.setattr(benchmark, "run_trial", lambda *args: trial) + output = tmp_path / "samples.json" + assert benchmark.main(["--output", str(output), "--repeats", "2"]) == 0 + data = json.loads(output.read_text()) + assert data["schema_version"] == 1 + assert len(data["trials"]) == 2 + assert data["attachment"] is None + assert "PSS" in data["metric"] + assert data["environment"]["python"] + + +@pytest.mark.parametrize( + "arguments", [["--repeats", "0"], ["--interval", "0"], ["--payload-mib", "0"], ["--timeout", "0"]] +) +def test_invalid_benchmark_arguments(tmp_path, arguments): + with pytest.raises(SystemExit) as error: + benchmark.main(["--output", str(tmp_path / "unused.json"), *arguments]) + assert error.value.code == 2 + assert not (tmp_path / "unused.json").exists() + + +@pytest.mark.parametrize("filename", ["local-loopback.json", "local-loopback-workers2.json"]) +def test_published_raw_samples_have_valid_phases_and_checksums(filename): + path = Path(__file__).resolve().parents[1] / "docs" / "benchmarks" / filename + data = json.loads(path.read_text()) + assert data["mode"] == "local_fixture_search_and_loopback_bittorrent" + for trial in data["trials"]: + assert {"idle", "search", "download", "teardown", "exited"} <= {sample["phase"] for sample in trial["samples"]} + assert trial["summary"] == benchmark.summarize(trial["samples"]) + downloads = [event for event in trial["events"] if "sha256" in event] + assert len(downloads) == 1 + assert downloads[0]["payload_bytes"] == data["payload_bytes"] + assert len(downloads[0]["sha256"]) == 64 + searches = [event for event in trial["events"] if "result_count" in event] + assert searches[0]["result_count"] == data["fixture_plugins"] * data["fixture_results_per_plugin"] + + +def test_benchmark_deadline_stops_worker(monkeypatch): + from helm.core import search_runner + + process = Mock() + process.poll.return_value = None + process.pid = 12345 + monkeypatch.setattr(benchmark.subprocess, "Popen", lambda *a, **kw: process) + clock = iter([0, 100]) + monkeypatch.setattr(benchmark.time, "monotonic", lambda: next(clock)) + stop = Mock() + monkeypatch.setattr(search_runner, "stop_worker", stop) + with pytest.raises(TimeoutError): + benchmark.run_trial(0.05, 1024, 1) + stop.assert_called_once_with(process) + + +def test_sampler_tracks_real_worker_protocol_and_exit(monkeypatch): + real_popen = benchmark.subprocess.Popen + code = "import json,time\nfor phase in ('idle','search','download','teardown'):\n print(json.dumps({'phase': phase}),flush=True)\n time.sleep(0.08)\n" + + def fixture_process(command, **kwargs): + return real_popen([sys.executable, "-c", code], **kwargs) + + monkeypatch.setattr(benchmark.subprocess, "Popen", fixture_process) + trial = benchmark.run_trial(0.01, 1024, 1) + assert {"idle", "search", "download", "teardown", "exited"} <= {s["phase"] for s in trial["samples"]} + assert trial["samples"][-1]["workload_pss_bytes"] == 0 + assert trial["summary"] == benchmark.summarize(trial["samples"]) diff --git a/tests/test_cli.py b/tests/test_cli.py index 0c6b7e0..0436e50 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -46,7 +46,7 @@ def test_search_json_output_is_machine_readable(monkeypatch, capsys): "animated_search", lambda query, content_type, lite_mode=False, show_spinner=True: (_make_items(), True), ) - monkeypatch.setattr(sys, "argv", ["helm", "search", "--json", "ubuntu"]) + monkeypatch.setattr(sys, "argv", ["helm-torrent", "search", "--json", "ubuntu"]) with pytest.raises(SystemExit) as exc_info: helm.cli.main() @@ -72,7 +72,7 @@ def test_search_with_no_results_exits_one(monkeypatch, capsys): "animated_search", lambda query, content_type, lite_mode=False, show_spinner=True: ([], False), ) - monkeypatch.setattr(sys, "argv", ["helm", "search", "--json", "definitely-not-found"]) + monkeypatch.setattr(sys, "argv", ["helm-torrent", "search", "--json", "definitely-not-found"]) with pytest.raises(SystemExit) as exc_info: helm.cli.main() @@ -95,7 +95,7 @@ def fake_search(query, content_type, lite_mode=False, show_spinner=True): return (_make_items(), lite_mode) monkeypatch.setattr(helm.cli, "animated_search", fake_search) - monkeypatch.setattr(sys, "argv", ["helm", "search", "--json", "ubuntu"]) + monkeypatch.setattr(sys, "argv", ["helm-torrent", "search", "--json", "ubuntu"]) with pytest.raises(SystemExit) as exc_info: helm.cli.main() @@ -107,3 +107,351 @@ def fake_search(query, content_type, lite_mode=False, show_spinner=True): assert len(data) == 2 assert captured["lite_mode"] is True assert "No configuration found" not in out + + +@pytest.mark.parametrize("query", ["", " "]) +def test_search_rejects_blank_query(monkeypatch, capsys, query): + monkeypatch.setattr(sys, "argv", ["helm-torrent", "search", "--lite", query]) + with pytest.raises(SystemExit) as exc_info: + helm.cli.main() + assert exc_info.value.code == 2 + assert "search query must not be empty" in capsys.readouterr().err + + +@pytest.mark.parametrize("has_raw_results", [False, True]) +def test_empty_search_explains_sources_or_filters(monkeypatch, capsys, has_raw_results): + items = _make_items() if has_raw_results else [] + monkeypatch.setattr(helm.cli, "animated_search", lambda *a, **kw: (items, True)) + monkeypatch.setattr(helm.cli, "load_config", lambda: {"min_seeds": 1000}) + monkeypatch.setattr(sys, "argv", ["helm-torrent", "search", "--lite", "ubuntu"]) + with pytest.raises(SystemExit) as exc_info: + helm.cli.main() + assert exc_info.value.code == 1 + err = capsys.readouterr().err + if has_raw_results: + assert "removed by filters" in err + assert "minimum seeders: 1000" in err + else: + assert "unreachable or have no matches" in err + assert "helm-torrent logs" in err + + +def test_lite_downloader_without_libtorrent_shows_magnet(monkeypatch, capsys): + from helm.core.lite_downloader import download_magnet + + monkeypatch.setitem(sys.modules, "libtorrent", None) + magnet = "magnet:?xt=urn:btih:cafe" + assert download_magnet(magnet) is False + output = capsys.readouterr().out + assert magnet in output + assert "helm-torrent[download]" in output + + +@pytest.mark.parametrize("outcome", ["complete", "metadata_timeout", "interrupt"]) +def test_lite_downloader_without_legacy_dht_router_api(monkeypatch, tmp_path, capsys, outcome): + from types import SimpleNamespace + from unittest.mock import Mock + + from helm.core import lite_downloader + + # Match bindings that expose session settings but no add_dht_router method. + session = Mock(spec=["add_torrent", "pause"]) + status = SimpleNamespace(has_metadata=outcome == "complete", state=5) + session.add_torrent.return_value.status.return_value = status + params = SimpleNamespace(save_path=None) + lt = SimpleNamespace( + session=Mock(return_value=session), + parse_magnet_uri=Mock(return_value=params), + torrent_status=SimpleNamespace(seeding=5), + ) + monkeypatch.setitem(sys.modules, "libtorrent", lt) + + def sleep(seconds): + if outcome == "interrupt": + raise KeyboardInterrupt + + monkeypatch.setattr(lite_downloader.time, "sleep", sleep) + magnet = "magnet:?xt=urn:btih:" + "a" * 40 + destination = str(tmp_path / "downloads") + + assert lite_downloader.download_magnet(magnet, destination) is (outcome == "complete") + settings = lt.session.call_args[0][0] + assert settings["enable_dht"] is True + assert "router.bittorrent.com:6881" in settings["dht_bootstrap_nodes"].split(",") + lt.parse_magnet_uri.assert_called_once_with(magnet) + session.add_torrent.assert_called_once_with(params) + assert params.save_path == destination + assert (tmp_path / "downloads").is_dir() + output = capsys.readouterr().out + if outcome == "complete": + assert "Download complete!" in output + else: + session.pause.assert_called_once_with() + if outcome == "metadata_timeout": + assert magnet in output + else: + assert "interrupted by user" in output + + +def test_bug_report_omits_unredactable_config(monkeypatch, tmp_path, capsys): + import zipfile + + from helm.core import config_manager, secret_manager + + config_file = tmp_path / "config.json" + config_file.write_text('{"JACKETT_API_KEY": "must-stay-private"}') + monkeypatch.setattr(config_manager, "get_config_file", lambda: str(config_file)) + monkeypatch.setattr(config_manager, "get_log_dir", lambda: str(tmp_path / "logs")) + monkeypatch.setattr(helm.cli.os.path, "expanduser", lambda path: str(tmp_path)) + + def failed_redaction(config): + raise ValueError("Cannot redact") + + monkeypatch.setattr(secret_manager, "redact_config", failed_redaction) + monkeypatch.setattr(sys, "argv", ["helm-torrent", "bug-report"]) + with pytest.raises(SystemExit) as exc_info: + helm.cli.main() + assert exc_info.value.code == 0 + with zipfile.ZipFile(tmp_path / "helm-bug-report.zip") as archive: + assert "config.json" not in archive.namelist() + assert "omitting it" in capsys.readouterr().err + + +@pytest.mark.parametrize("arguments", [["--type", "unknown"], ["--litte"], ["--typo", "music"]]) +def test_search_rejects_invalid_options_before_setup(monkeypatch, capsys, arguments): + from unittest.mock import Mock + + setup = Mock(side_effect=AssertionError("Validation must precede setup")) + monkeypatch.setattr(helm.cli, "load_config", setup) + monkeypatch.setattr(sys, "argv", ["helm-torrent", "search", "ubuntu"] + arguments) + with pytest.raises(SystemExit) as error: + helm.cli.main() + assert error.value.code == 2 + assert "error:" in capsys.readouterr().err + setup.assert_not_called() + + +def test_cli_normalizes_content_type(monkeypatch): + captured = [] + monkeypatch.setattr( + helm.cli, "animated_search", lambda query, category, **kw: captured.append(category) or ([], True) + ) + monkeypatch.setattr(sys, "argv", ["helm-torrent", "search", "ubuntu", "--lite", "--json", "--type", "MUSIC"]) + with pytest.raises(SystemExit) as error: + helm.cli.main() + assert error.value.code == 1 + assert captured == ["music"] + + +@pytest.mark.parametrize("explicit_lite", [True, False]) +def test_lite_oneshot_never_starts_or_stops_containers(monkeypatch, explicit_lite): + from unittest.mock import Mock + + from helm.core import oneshot + + start = Mock() + stop = Mock() + monkeypatch.setattr(oneshot, "spin_up_oneshot", start) + monkeypatch.setattr(oneshot, "teardown_oneshot", stop) + monkeypatch.setattr(helm.cli, "load_config", lambda: {"LITE_MODE_ONLY": True}) + monkeypatch.setattr(helm.cli, "animated_search", lambda *a, **kw: (_make_items(), True)) + arguments = ["helm-torrent", "search", "ubuntu", "--oneshot", "--json"] + monkeypatch.setattr(sys, "argv", arguments + (["--lite"] if explicit_lite else [])) + with pytest.raises(SystemExit) as error: + helm.cli.main() + assert error.value.code == 0 + start.assert_not_called() + stop.assert_not_called() + + +@pytest.mark.parametrize( + "outcome", + [ + "success", + "json", + "empty", + "send_failure", + "send_exception", + "search_exception", + "interrupt", + "startup_failure", + "wait_failure", + ], +) +def test_oneshot_cleans_up_once_on_every_exit(monkeypatch, outcome): + from helm.core import oneshot + + events = [] + monkeypatch.setenv("JACKETT_API_KEY", "testkey") + monkeypatch.setattr(helm.cli, "ensure_config", lambda: None) + monkeypatch.setattr(helm.cli, "load_config", lambda: {"min_seeds": 3}) + + def start(): + events.append("start") + if outcome == "startup_failure": + raise RuntimeError("partial startup failed") + + def search(*args, **kwargs): + if outcome == "search_exception": + raise RuntimeError("search failed") + if outcome == "interrupt": + raise KeyboardInterrupt + return ([] if outcome == "empty" else _make_items(), False) + + def send(*args, **kwargs): + events.append("send") + if outcome == "send_exception": + raise RuntimeError("download failed") + return outcome != "send_failure" + + def wait(): + events.append("wait") + if outcome == "wait_failure": + raise RuntimeError("wait failed") + + monkeypatch.setattr(oneshot, "spin_up_oneshot", start) + monkeypatch.setattr(oneshot, "teardown_oneshot", lambda: events.append("stop")) + monkeypatch.setattr(helm.cli, "animated_search", search) + monkeypatch.setattr(helm.cli, "_send_magnet", send) + monkeypatch.setattr(helm.cli, "wait_for_download", wait) + monkeypatch.setattr( + sys, + "argv", + ["helm-torrent", "search", "ubuntu", "--oneshot", "--json" if outcome in ("json", "empty") else "--auto"], + ) + with pytest.raises((SystemExit, RuntimeError)) as error: + helm.cli.main() + assert events[0] == "start" + assert events[-1] == "stop" + assert events.count("stop") == 1 + if outcome in ("empty", "send_failure"): + assert isinstance(error.value, SystemExit) and error.value.code == 1 + elif outcome in ("success", "json", "interrupt"): + assert isinstance(error.value, SystemExit) and error.value.code == 0 + else: + assert isinstance(error.value, RuntimeError) + if outcome == "success": + assert events == ["start", "send", "wait", "stop"] + + +def test_download_uses_cli_directory_override(monkeypatch, tmp_path): + from types import SimpleNamespace + from unittest.mock import Mock + + session = Mock(spec=["add_torrent", "pause"]) + session.add_torrent.return_value.status.return_value = SimpleNamespace(has_metadata=True, state=5) + params = SimpleNamespace(save_path=None) + monkeypatch.setitem( + sys.modules, + "libtorrent", + SimpleNamespace( + session=lambda settings: session, + parse_magnet_uri=lambda magnet: params, + torrent_status=SimpleNamespace(seeding=5), + ), + ) + destination = tmp_path / "custom downloads" + monkeypatch.setattr(helm.cli, "animated_search", lambda *a, **kw: (_make_items(), True)) + monkeypatch.setattr( + sys, "argv", ["helm-torrent", "search", "ubuntu", "--lite", "--auto", "--dl-dir", str(destination)] + ) + with pytest.raises(SystemExit) as error: + helm.cli.main() + assert error.value.code == 0 + assert params.save_path == str(destination) + assert destination.is_dir() + session.pause.assert_called_once_with() + + +def test_real_search_fallback_keeps_json_stdout_clean(monkeypatch, capsys): + from helm.core import lite_fetcher, rss_fetcher + + items = _make_items() + results = rss_fetcher.SearchResults(items, [rss_fetcher.SourceOutcome("Nyaa", "timeout")]) + + def unavailable(*args, **kwargs): + raise RuntimeError("indexer unavailable with private-token") + + monkeypatch.setenv("JACKETT_API_KEY", "testkey") + monkeypatch.setattr(helm.cli, "load_config", lambda: {"min_seeds": 3}) + monkeypatch.setattr(helm.cli, "ensure_config", lambda: None) + monkeypatch.setattr(rss_fetcher, "search_indexers", unavailable) + monkeypatch.setattr(lite_fetcher, "search_lite", lambda query, content_type: results) + monkeypatch.setattr(sys, "argv", ["helm-torrent", "search", "ubuntu", "--json"]) + with pytest.raises(SystemExit) as error: + helm.cli.main() + assert error.value.code == 0 + out, err = capsys.readouterr() + assert len(json.loads(out)) == 2 + assert "Nyaa: timeout (0)" in err + assert "Indexer manager unavailable" in err + assert "private-token" not in out + err + + +def test_indexer_exit_cleans_up_once(monkeypatch): + from types import SimpleNamespace + + from helm.core import indexer_manager, oneshot + + events = [] + monkeypatch.setenv("JACKETT_API_KEY", "testkey") + monkeypatch.setattr(helm.cli, "ensure_config", lambda: None) + monkeypatch.setattr(helm.cli, "load_config", lambda: {}) + monkeypatch.setattr(oneshot, "spin_up_oneshot", lambda: events.append("start")) + monkeypatch.setattr(oneshot, "teardown_oneshot", lambda: events.append("stop")) + monkeypatch.setattr(indexer_manager, "JackettManager", lambda: SimpleNamespace(get_all_indexers=lambda: [])) + + def exit_indexers(*args): + raise KeyboardInterrupt + + def end_input(*args): + raise EOFError + + monkeypatch.setattr(helm.cli, "interactive_indexer_selector", exit_indexers) + monkeypatch.setattr("builtins.input", end_input) + monkeypatch.setattr(sys, "argv", ["helm-torrent", "indexers", "--oneshot"]) + with pytest.raises(SystemExit) as error: + helm.cli.main() + assert error.value.code == 0 + assert events == ["start", "stop"] + + +def test_bug_report_streams_and_redacts_historical_logs(monkeypatch, tmp_path): + import zipfile + + from helm.core import config_manager + + config = tmp_path / "config.json" + config.write_text('{"nested": {"password": "nested-private"}}') + logs = tmp_path / "logs" + logs.mkdir() + (logs / "helm.log").write_text( + "old request https://alice:pass@example.test/?apikey=historical-key\nAuthorization: Bearer historical-auth\n" + ) + monkeypatch.setattr(config_manager, "get_config_file", lambda: str(config)) + monkeypatch.setattr(config_manager, "get_log_dir", lambda: str(logs)) + monkeypatch.setattr(helm.cli.os.path, "expanduser", lambda path: str(tmp_path)) + monkeypatch.setattr(sys, "argv", ["helm-torrent", "bug-report"]) + with pytest.raises(SystemExit) as error: + helm.cli.main() + assert error.value.code == 0 + with zipfile.ZipFile(tmp_path / "helm-bug-report.zip") as archive: + contents = archive.read("helm.log").decode() + archive.read("config.json").decode() + assert all( + secret not in contents for secret in ("historical-key", "historical-auth", "alice:pass", "nested-private") + ) + + +def test_cli_worker_limit_overrides_environment(monkeypatch): + import os + + seen = [] + monkeypatch.setenv("HELM_LITE_WORKERS", "6") + monkeypatch.setattr( + helm.cli, "animated_search", lambda *a, **kw: seen.append(os.environ["HELM_LITE_WORKERS"]) or ([], True) + ) + monkeypatch.setattr(sys, "argv", ["helm-torrent", "search", "generated", "--lite", "--json", "--lite-workers", "2"]) + with pytest.raises(SystemExit) as error: + helm.cli.main() + assert error.value.code == 1 + assert seen == ["2"] diff --git a/tests/test_device_profile.py b/tests/test_device_profile.py new file mode 100644 index 0000000..e9eaf8b --- /dev/null +++ b/tests/test_device_profile.py @@ -0,0 +1,124 @@ +import json +from types import SimpleNamespace + +import pytest + +import helm.core.device_profile as device +from helm.core.benchmark import binding_version +from helm.core.device_profile import battery_adb, battery_sysfs, cleanup_probe, energy_delta + +DISCHARGING = {"status": 3, "Charge counter": 2000000, "voltage": 4000, "USB powered": False} + + +@pytest.mark.parametrize( + "binding,expected", + [ + (SimpleNamespace(__version__="2.0.11", version="old"), "2.0.11"), + (SimpleNamespace(version="2.0.9"), "2.0.9"), + (SimpleNamespace(), "unknown"), + ], +) +def test_binding_version(binding, expected): + assert binding_version(binding) == expected + + +def test_battery_sysfs_reads_first_battery(tmp_path): + (tmp_path / "usb").mkdir() + (tmp_path / "usb" / "type").write_text("USB\n") + battery = tmp_path / "battery" + battery.mkdir() + (battery / "type").write_text("Battery\n") + (battery / "voltage_now").write_text("4000000\n") + (battery / "status").write_text("Discharging\n") + assert battery_sysfs(tmp_path) == {"available": True, "voltage_now": 4000000, "status": "Discharging"} + + +def test_battery_sysfs_without_sensors(tmp_path): + assert battery_sysfs(tmp_path)["available"] is False + unreadable = tmp_path / "battery" + unreadable.mkdir() + (unreadable / "type").write_text("Battery") + (unreadable / "current_now").write_text("not a number") + assert battery_sysfs(tmp_path)["available"] is False + + +def test_battery_adb_parses_dumpsys(): + text = """Current Battery Service state: + AC powered: false + USB powered: true + Wireless powered: false + status: 2 + level: 80 + voltage: 4100 + temperature: 300 + Charge counter: 3000000 + technology: Li-ion + status: 9 +""" + assert battery_adb(text) == { + "AC powered": False, + "USB powered": True, + "Wireless powered": False, + "status": 2, + "level": 80, + "voltage": 4100, + "temperature": 300, + "Charge counter": 3000000, + } + + +def test_energy_is_calculated_only_while_verified_discharging(): + after = {**DISCHARGING, "Charge counter": 1999000, "voltage": 3900} + result = energy_delta(DISCHARGING, after) + assert result["consumption_wh"] == pytest.approx(0.00395) + assert "not application-attributed" in result["scope"] + + +@pytest.mark.parametrize( + "before,after,reason", + [ + ({**DISCHARGING, "USB powered": True}, DISCHARGING, "charging"), + (DISCHARGING, {**DISCHARGING, "status": 5}, "charging"), + ({**DISCHARGING, "status": 4}, DISCHARGING, "not verified"), + (DISCHARGING, {**DISCHARGING, "Charge counter": 2000001}, "increased"), + ({"status": 3}, {"status": 3}, "unavailable"), + ], +) +def test_unmeasurable_energy_is_never_reported_as_zero(before, after, reason): + result = energy_delta(before, after) + assert result["consumption_wh"] is None + assert reason in result["reason"] + + +def test_cleanup_probe_kills_hung_source_and_keeps_results(): + result = cleanup_probe() + assert result == { + "passed": True, + "outcomes": {"stalled": "timeout", "healthy": "success"}, + "retained_results": 1, + "stalled_process_running_after_return": False, + } + + +def test_main_writes_report_and_restores_environment(tmp_path, monkeypatch, capsys): + monkeypatch.setattr(device, "run_trial", lambda *a, **kw: {"search_workers": kw["search_workers"]}) + monkeypatch.setattr(device, "cleanup_probe", lambda: {"passed": True}) + monkeypatch.setenv("HELM_STATE_DIR", "/kept") + output = tmp_path / "out" / "profile.json" + assert device.main(["--output", str(output), "--repeats", "2", "--workers", "2", "6"]) == 0 + report = json.loads(output.read_text()) + assert [(p["workers"], len(p["trials"])) for p in report["profiles"]] == [(2, 2), (6, 2)] + assert report["energy"]["consumption_wh"] is None + assert device.os.environ["HELM_STATE_DIR"] == "/kept" + + +def test_failed_cleanup_probe_fails_the_run(tmp_path, monkeypatch): + monkeypatch.setattr(device, "run_trial", lambda *a, **kw: {}) + monkeypatch.setattr(device, "cleanup_probe", lambda: {"passed": False}) + assert device.main(["--output", str(tmp_path / "p.json"), "--repeats", "1", "--workers", "1"]) == 1 + + +@pytest.mark.parametrize("arguments", [["--repeats", "0"], ["--workers", "13"]]) +def test_invalid_arguments(tmp_path, arguments): + with pytest.raises(SystemExit): + device.main(["--output", str(tmp_path / "p.json"), *arguments]) diff --git a/tests/test_headless_cli.py b/tests/test_headless_cli.py new file mode 100644 index 0000000..13e528a --- /dev/null +++ b/tests/test_headless_cli.py @@ -0,0 +1,162 @@ +"""The installed entry point, run as real subprocesses with disposable state.""" + +import json +import os +import socket +import stat +import subprocess +import sys +import time +from pathlib import Path + +import pytest +import requests + +SRC = str(Path(__file__).resolve().parents[1] / "src") +MAGNET = "magnet:?xt=urn:btih:" + "a" * 40 +TOKEN = "t" * 32 + + +@pytest.fixture +def environment(tmp_path): + env = { + **os.environ, + "PYTHONPATH": SRC, + "HELM_CONFIG_DIR": str(tmp_path / "config"), + "HELM_STATE_DIR": str(tmp_path / "state"), + "HELM_DL_DIR": str(tmp_path / "downloads"), + "HELM_SERVER_TOKEN": TOKEN, + } + for key in ("QB_WEBUI", "QB_PASSWORD"): + env.pop(key, None) + return env + + +def helm(env, *arguments, timeout=30, stdin=subprocess.DEVNULL): + return subprocess.run( + [sys.executable, "-m", "helm.cli", *arguments], + env=env, + stdin=stdin, + capture_output=True, + text=True, + timeout=timeout, + ) + + +def free_port(): + with socket.socket() as probe: + probe.bind(("127.0.0.1", 0)) + return probe.getsockname()[1] + + +def wait_for_health(port, timeout=20): + deadline = time.monotonic() + timeout + while True: + try: + return requests.get( + f"http://127.0.0.1:{port}/health", headers={"Authorization": "Bearer " + TOKEN}, timeout=1 + ) + except requests.ConnectionError: + assert time.monotonic() < deadline + time.sleep(0.05) + + +def test_heavy_modules_stay_out_of_light_commands(environment): + code = ( + "import sys, helm.cli\n" + "print(sorted(m for m in ('requests', 'bs4', 'helm.ui.tui', 'helm.core.config_wizard') if m in sys.modules))" + ) + result = subprocess.run([sys.executable, "-c", code], env=environment, capture_output=True, text=True, check=True) + assert result.stdout.strip() == "[]" + + +def test_daemon_status_without_records(environment): + result = helm(environment, "daemon", "status") + assert result.returncode == 0 + assert json.loads(result.stdout) == [] + + +def test_daemon_stop_needs_id(environment): + assert helm(environment, "daemon", "stop").returncode == 2 + + +def test_session_rejects_headless_command(environment): + result = helm(environment, "--session", "a", "serve") + assert result.returncode == 2 and "headless" in result.stderr + + +def test_background_search_needs_noninteractive_mode(environment): + assert helm(environment, "search", "ubuntu", "--daemon").returncode == 2 + + +def test_invalid_port(environment): + assert helm(environment, "serve", "--port", "70000", "--lite").returncode == 2 + + +def test_download_rejects_invalid_source_without_prompting(environment): + result = helm(environment, "download", "magnet:?xt=urn:btih:12345") + assert result.returncode == 1 + assert "info hash" in result.stderr + + +def test_download_failure_reports_job_status(environment, tmp_path): + # No libtorrent session can complete this: the worker exits without success. + environment["PYTHONPATH"] = str(tmp_path / "no-libtorrent") + os.pathsep + SRC + stub = tmp_path / "no-libtorrent" + stub.mkdir() + (stub / "libtorrent.py").write_text("raise ImportError('stub')\n") + result = helm(environment, "download", MAGNET, "--lite") + assert result.returncode == 1 + report = json.loads(result.stdout) + assert report["status"] == "failed" + assert "did not complete" in report["error"] + + +def test_watch_once_enqueue_only_uses_state_dir(environment, tmp_path): + inbox = tmp_path / "inbox" + inbox.mkdir() + (inbox / "a.magnet").write_text(MAGNET) + result = helm(environment, "watch", str(inbox), "--once", "--enqueue-only", "--interval", "0.1", "--lite") + assert result.returncode == 0, result.stderr + assert not (inbox / "a.magnet").exists() + assert len(list((inbox / ".processed").iterdir())) == 1 + database = tmp_path / "state" / "jobs.sqlite3" + assert stat.S_IMODE(database.stat().st_mode) == 0o600 + + +def test_serve_daemon_lifecycle_and_job_submission(environment, tmp_path): + port = free_port() + started = helm(environment, "--daemon", "serve", "--port", str(port), "--lite") + assert started.returncode == 0, started.stderr + records = json.loads(helm(environment, "daemon", "status").stdout) + assert len(records) == 1 and records[0]["running"] is True + try: + assert wait_for_health(port).json()["read_only"] is False + response = requests.post( + f"http://127.0.0.1:{port}/jobs", + headers={"Authorization": "Bearer " + TOKEN}, + json={"source": MAGNET}, + timeout=5, + ) + assert response.status_code == 202 + finally: + stopped = helm(environment, "daemon", "stop", records[0]["id"]) + assert json.loads(stopped.stdout) == {"stopped": True} + assert json.loads(helm(environment, "daemon", "status").stdout)[0]["running"] is False + log = Path(records[0]["log"]).read_text() + assert TOKEN not in log + + +def test_files_server_is_read_only(environment): + port = free_port() + process = subprocess.Popen( + [sys.executable, "-m", "helm.cli", "files", "--port", str(port)], + env=environment, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + ) + try: + assert wait_for_health(port).json()["read_only"] is True + finally: + process.terminate() + assert process.wait(10) == 0 diff --git a/tests/test_jobs.py b/tests/test_jobs.py new file mode 100644 index 0000000..4b3c82e --- /dev/null +++ b/tests/test_jobs.py @@ -0,0 +1,452 @@ +"""Queue behaviour against a real database and real worker subprocesses.""" + +import os +import stat +import subprocess +import sys +import threading +import time +from pathlib import Path + +import pytest +import responses + +import helm.core.jobs as jobs +import helm.core.qbittorrent_client as client +from helm.core.config_manager import get_dl_dir +from helm.core.jobs import ( + JobStore, + cancel_job, + execute_job, + host_path, + process_one, + public_job, + queue_loop, + reconcile_qbittorrent, +) + +MAGNET = "magnet:?xt=urn:btih:" + "a" * 40 +OTHER = "magnet:?xt=urn:btih:" + "b" * 40 +TORRENT = b"d4:infod6:lengthi5e4:name4:file12:piece lengthi16384e6:pieces20:" + b"p" * 20 + b"ee" +BASE = "http://localhost:8080" +DEAD_PID = 2**22 + 1 + + +@pytest.fixture +def store(tmp_path): + return JobStore(tmp_path / "state" / "jobs.sqlite3") + + +@pytest.fixture +def qbittorrent(monkeypatch): + monkeypatch.setenv("QB_WEBUI", BASE) + monkeypatch.setenv("QB_PASSWORD", "testpass") + monkeypatch.setattr(client, "_session", None) + monkeypatch.setattr(client, "_session_key", None) + + +def set_row(store, identifier, **values): + columns = ",".join(key + "=?" for key in values) + with store.connect() as connection: + connection.execute(f"UPDATE jobs SET {columns} WHERE id=?", (*values.values(), identifier)) + + +def test_store_is_private_and_uses_wal(store): + assert stat.S_IMODE(store.path.stat().st_mode) == 0o600 + with store.connect() as connection: + assert connection.execute("PRAGMA journal_mode").fetchone()[0] == "wal" + plan = connection.execute( + "EXPLAIN QUERY PLAN SELECT * FROM jobs WHERE status='pending' ORDER BY created LIMIT 1" + ).fetchone() + assert "jobs_status_created" in plan["detail"] + + +def test_enqueue_deduplicates_active_jobs(store): + first = store.enqueue(MAGNET) + assert store.enqueue(MAGNET)["id"] == first["id"] + assert store.enqueue(MAGNET, lite=True)["id"] != first["id"] + + +@pytest.mark.parametrize("status", ["failed", "cancelled"]) +def test_terminal_failure_can_be_resubmitted(store, status): + job = store.enqueue(MAGNET) + store.update(job["id"], status, error="broken") + again = store.enqueue(MAGNET) + assert again["id"] == job["id"] + assert (again["status"], again["error"]) == ("pending", None) + + +def test_succeeded_job_is_not_repeated(store): + job = store.enqueue(MAGNET) + store.update(job["id"], "succeeded") + assert store.enqueue(MAGNET)["status"] == "succeeded" + + +def test_cancelled_job_with_live_worker_is_not_requeued(store): + job = store.enqueue(MAGNET) + assert store.claim()["id"] == job["id"] + store.cancel(job["id"]) + assert store.enqueue(MAGNET)["status"] == "cancelled" + store.release(job["id"]) + assert store.enqueue(MAGNET)["status"] == "pending" + + +def test_cancelled_job_with_dead_owner_can_be_resubmitted(store): + job = store.enqueue(MAGNET) + store.claim() + store.cancel(job["id"]) + set_row(store, job["id"], owner_pid=DEAD_PID, owner_start="1") + assert store.enqueue(MAGNET)["status"] == "pending" + + +def test_enqueue_many_is_all_or_nothing(store): + with pytest.raises(ValueError): + store.enqueue_many([MAGNET, "magnet:?xt=urn:btih:12345"]) + assert store.list() == [] + assert len(store.enqueue_many([MAGNET, OTHER])) == 2 + + +@pytest.mark.parametrize("source", ["ftp://x/y", "http://", "/no/such/file.torrent", "plain text"]) +def test_invalid_sources_are_rejected(store, source): + with pytest.raises(ValueError): + store.enqueue(source) + + +def test_local_torrent_is_spooled_privately(store, tmp_path): + original = tmp_path / "a.torrent" + original.write_bytes(TORRENT) + job = store.enqueue(str(original)) + original.unlink() + spooled = Path(job["source"]) + assert spooled.read_bytes() == TORRENT + assert stat.S_IMODE(spooled.stat().st_mode) == 0o600 + assert not list(spooled.parent.glob("*.tmp")) + + +def test_claim_is_oldest_first_and_exclusive(store): + first = store.enqueue(MAGNET) + second = store.enqueue(OTHER) + set_row(store, second["id"], created=first["created"] + 1) + assert store.claim()["id"] == first["id"] + assert store.claim()["id"] == second["id"] + assert store.claim() is None + + +def test_concurrent_claims_never_share_a_job(store): + for index in range(20): + store.enqueue("magnet:?xt=urn:btih:" + f"{index:040x}") + claimed = [] + + def worker(): + while True: + job = store.claim() + if job is None: + return + claimed.append(job["id"]) + + threads = [threading.Thread(target=worker) for _ in range(6)] + for thread in threads: + thread.start() + for thread in threads: + thread.join() + assert len(claimed) == 20 == len(set(claimed)) + + +def test_claim_recovers_jobs_of_dead_owners_only(store): + job = store.enqueue(MAGNET) + store.claim() + assert store.claim() is None + set_row(store, job["id"], owner_pid=DEAD_PID, owner_start="1") + assert store.claim()["id"] == job["id"] + + +def test_cancel(store): + job = store.enqueue(MAGNET) + assert store.cancel(job["id"]) is True + assert store.cancel(job["id"]) is False + with pytest.raises(KeyError): + store.cancel("missing") + + +def test_late_worker_result_does_not_override_cancellation(store): + job = store.enqueue(MAGNET) + store.cancel(job["id"]) + store.update(job["id"], "succeeded") + assert store.get(job["id"])["status"] == "cancelled" + + +def test_register_files_stays_inside_download_root(store, tmp_path): + root = Path(get_dl_dir()) + root.mkdir(parents=True, exist_ok=True) + inside = root / "inside.bin" + inside.write_bytes(b"123") + outside = tmp_path / "outside.bin" + outside.write_bytes(b"x") + job = store.enqueue(MAGNET) + store.register_files(job["id"], [inside, outside, root / "missing"]) + assert [item["path"] for item in store.files()] == ["inside.bin"] + assert store.file_entry("inside.bin")["size"] == 3 + assert store.file_entry("outside.bin") is None + + +def test_public_job_redacts_and_hides_internals(store, monkeypatch): + monkeypatch.setenv("JACKETT_API_KEY", "supersecretvalue1234") + job = store.enqueue("http://example.test/a?apikey=supersecretvalue1234") + view = public_job(job) + assert "owner_pid" not in view and "fingerprint" not in view + assert "supersecretvalue1234" not in view["source"] + + +def test_execute_job_outcomes(store, monkeypatch): + import helm.core.lite_downloader as downloader + + job = store.enqueue(MAGNET, lite=True) + assert execute_job(store, job["id"]) == 1 # Not claimed. + store.claim() + monkeypatch.setattr(downloader, "download_magnet", lambda source, on_complete: False) + assert execute_job(store, job["id"]) == 1 + assert store.get(job["id"])["status"] == "failed" + + store.release(job["id"]) + store.enqueue(MAGNET, lite=True) + store.claim() + monkeypatch.setattr(downloader, "download_magnet", lambda source, on_complete: on_complete([]) or True) + assert execute_job(store, job["id"]) == 0 + assert store.get(job["id"])["status"] == "succeeded" + + +@responses.activate +def test_execute_job_submits_with_shared_and_job_tags(store, qbittorrent): + responses.add(responses.GET, BASE + "/api/v2/app/version", status=200) + responses.add(responses.POST, BASE + "/api/v2/torrents/add", status=200) + job = store.enqueue(MAGNET) + store.claim() + assert execute_job(store, job["id"]) == 0 + assert store.get(job["id"])["status"] == "submitted" + assert ("tags=helm%2Chelm-job-" + job["id"]) in responses.calls[-1].request.body + + +def write_worker(tmp_path, body): + """Install a fake helm.core.jobs worker module found through PYTHONPATH.""" + package = tmp_path / "fake" / "helm" / "core" + package.mkdir(parents=True) + (package.parent / "__init__.py").write_text("") + (package / "__init__.py").write_text("") + (package / "jobs.py").write_text(body) + return str(tmp_path / "fake") + + +def patch_environment(monkeypatch, path): + monkeypatch.setattr(jobs, "child_environment", lambda: {**os.environ, "PYTHONPATH": path}) + + +def test_worker_that_writes_nothing_is_marked_failed(store, tmp_path, monkeypatch): + patch_environment(monkeypatch, write_worker(tmp_path, "raise SystemExit(0)\n")) + job = store.enqueue(MAGNET) + assert process_one(store) is True + final = store.get(job["id"]) + assert final["status"] == "failed" and "job log" in final["error"] + assert final["owner_pid"] is None + + +def test_process_one_with_empty_queue(store): + assert process_one(store) is False + + +def test_stop_requeues_running_job_and_kills_worker(store, tmp_path, monkeypatch): + marker = tmp_path / "pid" + body = f"import os,time\nopen({str(marker)!r},'w').write(str(os.getpid()))\ntime.sleep(60)\n" + patch_environment(monkeypatch, write_worker(tmp_path, body)) + job = store.enqueue(MAGNET) + stop = threading.Event() + thread = threading.Thread(target=process_one, args=(store, stop)) + thread.start() + deadline = time.monotonic() + 10 + while not (marker.exists() and marker.read_text()) and time.monotonic() < deadline: + time.sleep(0.02) + pid = int(marker.read_text()) + stop.set() + thread.join(10) + assert not thread.is_alive() + final = store.get(job["id"]) + assert (final["status"], final["owner_pid"]) == ("pending", None) + with pytest.raises(ProcessLookupError): + os.kill(pid, 0) + + +def test_cancellation_stops_worker(store, tmp_path, monkeypatch): + marker = tmp_path / "pid" + body = f"import os,time\nopen({str(marker)!r},'w').write(str(os.getpid()))\ntime.sleep(60)\n" + patch_environment(monkeypatch, write_worker(tmp_path, body)) + job = store.enqueue(MAGNET) + thread = threading.Thread(target=process_one, args=(store, None, 0.05)) + thread.start() + deadline = time.monotonic() + 10 + while not (marker.exists() and marker.read_text()) and time.monotonic() < deadline: + time.sleep(0.02) + pid = int(marker.read_text()) + store.cancel(job["id"]) + thread.join(10) + assert not thread.is_alive() + assert store.get(job["id"])["status"] == "cancelled" + with pytest.raises(ProcessLookupError): + os.kill(pid, 0) + + +def test_spawn_failure_fails_the_job(store, monkeypatch): + def refuse(*args, **kwargs): + raise OSError("cannot fork") + + monkeypatch.setattr(jobs.subprocess, "Popen", refuse) + job = store.enqueue(MAGNET) + assert process_one(store) is True + assert store.get(job["id"])["status"] == "failed" + assert store.get(job["id"])["owner_pid"] is None + + +def test_queue_loop_survives_unexpected_errors(store, monkeypatch): + calls = [] + stop = threading.Event() + + def explode(*args): + calls.append(1) + if len(calls) == 3: + stop.set() + return False + raise RuntimeError("bad job") + + monkeypatch.setattr(jobs, "process_one", explode) + monkeypatch.setattr(jobs, "min", lambda *a: 0.001, raising=False) + queue_loop(store, stop) + assert len(calls) == 3 + + +def test_queue_loop_survives_reconcile_errors(store, monkeypatch): + stop = threading.Event() + seen = [] + + def broken(_): + seen.append(1) + stop.set() + raise RuntimeError("qBittorrent offline") + + monkeypatch.setattr(jobs, "process_one", lambda *a: False) + monkeypatch.setattr(jobs, "reconcile_qbittorrent", broken) + queue_loop(store, stop) + assert seen == [1] + + +def test_host_path_maps_container_mount(monkeypatch): + monkeypatch.delenv("QB_DOWNLOADS_ROOT", raising=False) + assert host_path("/downloads/sub", "a/b.iso") == Path(get_dl_dir()) / "sub/a/b.iso" + assert host_path("/downloads/", "b.iso") == Path(get_dl_dir()) / "b.iso" + assert host_path("/srv/native", "b.iso") == Path("/srv/native/b.iso") + monkeypatch.setenv("QB_DOWNLOADS_ROOT", "/data") + assert host_path("/data", "b.iso") == Path(get_dl_dir()) / "b.iso" + + +@responses.activate +def test_reconcile_uses_one_list_call_and_records_host_paths(store, qbittorrent): + root = Path(get_dl_dir()) + root.mkdir(parents=True, exist_ok=True) + (root / "done.iso").write_bytes(b"12345") + done = store.enqueue(MAGNET) + active = store.enqueue(OTHER) + store.update(done["id"], "submitted") + store.update(active["id"], "submitted") + responses.add(responses.GET, BASE + "/api/v2/app/version", status=200) + responses.add( + responses.GET, + BASE + "/api/v2/torrents/info", + json=[ + {"hash": "h1", "progress": 1, "save_path": "/downloads", "tags": "helm, helm-job-" + done["id"]}, + {"hash": "h2", "progress": 0.5, "save_path": "/downloads", "tags": "helm, helm-job-" + active["id"]}, + ], + ) + responses.add( + responses.GET, + BASE + "/api/v2/torrents/files", + json=[{"name": "done.iso", "progress": 1}, {"name": "partial.bin", "progress": 0.2}], + ) + reconcile_qbittorrent(store) + assert store.get(done["id"])["status"] == "succeeded" + assert store.get(active["id"])["status"] == "submitted" + assert [item["path"] for item in store.files()] == ["done.iso"] + assert sum(call.request.url.split("?")[0].endswith("/info") for call in responses.calls) == 1 + assert "tag=helm" in next(call.request.url for call in responses.calls if "/info" in call.request.url) + + +@responses.activate +def test_reconcile_skips_network_without_submitted_jobs(store, qbittorrent): + store.enqueue(MAGNET) + reconcile_qbittorrent(store) + assert len(responses.calls) == 0 + + +@responses.activate +def test_reconcile_fails_jobs_removed_from_qbittorrent_after_grace(store, qbittorrent): + recent = store.enqueue(MAGNET) + removed = store.enqueue(OTHER) + store.update(recent["id"], "submitted") + store.update(removed["id"], "submitted") + set_row(store, removed["id"], updated=time.time() - jobs.MISSING_GRACE - 1) + responses.add(responses.GET, BASE + "/api/v2/app/version", status=200) + responses.add(responses.GET, BASE + "/api/v2/torrents/info", json=[]) + reconcile_qbittorrent(store) + assert store.get(recent["id"])["status"] == "submitted" + assert store.get(removed["id"])["status"] == "failed" + + +@responses.activate +def test_cancelling_submitted_job_removes_torrent(store, qbittorrent): + job = store.enqueue(MAGNET) + store.update(job["id"], "submitted") + responses.add(responses.GET, BASE + "/api/v2/app/version", status=200) + responses.add(responses.GET, BASE + "/api/v2/torrents/info", json=[{"hash": "h1"}]) + responses.add(responses.POST, BASE + "/api/v2/torrents/delete", status=200) + assert cancel_job(store, job["id"]) is True + assert "hashes=h1" in responses.calls[-1].request.body + + +def test_cancelling_lite_job_needs_no_qbittorrent(store): + job = store.enqueue(MAGNET, lite=True) + assert cancel_job(store, job["id"]) is True + with pytest.raises(KeyError): + cancel_job(store, "missing") + + +@responses.activate +def test_cancel_succeeds_when_qbittorrent_is_offline(store, qbittorrent): + job = store.enqueue(MAGNET) + store.update(job["id"], "submitted") + assert cancel_job(store, job["id"]) is True + assert store.get(job["id"])["status"] == "cancelled" + + +def test_orphaned_worker_exits_when_its_parent_dies(tmp_path): + src = str(Path(jobs.__file__).resolve().parents[2]) + marker = tmp_path / "pid" + child = ( + "import os,threading,time\n" + "from helm.core.jobs import exit_with_parent\n" + "threading.Thread(target=exit_with_parent,args=(os.getppid(),0.05),daemon=True).start()\n" + f"open({str(marker)!r},'w').write(str(os.getpid()))\n" + "time.sleep(30)\n" + ) + parent = f"import subprocess,sys\nsubprocess.Popen([sys.executable,'-c',{child!r}])\nimport time\ntime.sleep(30)\n" + process = subprocess.Popen([sys.executable, "-c", parent], env={**os.environ, "PYTHONPATH": src}) + deadline = time.monotonic() + 15 + while not (marker.exists() and marker.read_text()) and time.monotonic() < deadline: + time.sleep(0.02) + pid = int(marker.read_text()) + process.kill() + process.wait() + deadline = time.monotonic() + 5 + while time.monotonic() < deadline: + try: + os.kill(pid, 0) + except ProcessLookupError: + return + time.sleep(0.02) + os.kill(pid, 9) + pytest.fail("Orphaned worker kept running") diff --git a/tests/test_lite_fetcher.py b/tests/test_lite_fetcher.py index e19f5aa..26f5194 100644 --- a/tests/test_lite_fetcher.py +++ b/tests/test_lite_fetcher.py @@ -1,9 +1,29 @@ import asyncio +import pytest import responses from helm.core.lite_fetcher import search_all_plugins, search_lite + +@pytest.fixture(autouse=True) +def inline_sources_in_process(monkeypatch): + # Parsing/HTTP unit tests execute synchronously; subprocess behavior has its + # own integration tests with real workers and disposable fixture plugins. + from helm.core import lite_plugin_loader, search_runner + from helm.core.rss_fetcher import SearchResults + + monkeypatch.setattr(lite_plugin_loader, "plugin_jobs", lambda directories: []) + + def run(jobs, query, content_type="video", **kwargs): + result = SearchResults() + for job in jobs: + result.extend(search_runner.execute_job(job, query, content_type)) + return result + + monkeypatch.setattr(search_runner, "run_searches", run) + + NYAA_RSS = """ @@ -84,8 +104,101 @@ def test_search_all_plugins_delegates_to_search_lite(monkeypatch): from helm.core.rss_fetcher import TorrentItem item = TorrentItem("Ubuntu 24.04 ISO", "magnet:?xt=urn:btih:cafe", 42, 7, 999) - monkeypatch.setattr("helm.core.lite_fetcher.search_lite", lambda query: [item]) + monkeypatch.setattr("helm.core.lite_fetcher.search_lite", lambda query, content_type: [item]) result = asyncio.run(search_all_plugins("ubuntu", "video")) assert result == [item] + + +def test_search_lite_rejects_empty_queries_without_network(monkeypatch): + def unexpected_search(query, content_type): + raise AssertionError("Blank queries must not reach sources") + + monkeypatch.setattr("helm.core.lite_fetcher._collect_all", unexpected_search) + assert search_lite(" \t\n") == [] + + +def test_search_lite_trims_query(monkeypatch): + queries = [] + monkeypatch.setattr("helm.core.lite_fetcher._collect_all", lambda query, content_type: queries.append(query) or []) + assert search_lite(" ubuntu ") == [] + assert queries == ["ubuntu"] + + +@responses.activate +def test_nyaa_timeout_preserves_other_source_results(monkeypatch): + import requests + + monkeypatch.setattr("helm.core.lite_plugin_loader.run_plugins", lambda query, dirs: []) + responses.add(responses.GET, "https://apibay.org/q.php", json=[APITBAY_ITEM]) + responses.add(responses.GET, "https://torrents-csv.com/service/search", json={"torrents": [CSV_ITEM]}) + responses.add(responses.GET, "https://nyaa.si/", body=requests.exceptions.ConnectTimeout("Nyaa timed out")) + + assert {item.indexer for item in search_lite("ubuntu")} == {"Apibay", "Torrents-csv"} + + +def test_search_uses_one_budget_for_inline_and_plugin_jobs(monkeypatch): + from helm.core import lite_plugin_loader, search_runner + + jobs_seen = [] + plugin = search_runner.SearchJob("Fixture", "plugin", "fixture.py") + monkeypatch.setattr(lite_plugin_loader, "plugin_jobs", lambda directories: [plugin]) + + def run(jobs, query, content_type, timeout): + jobs_seen.extend(jobs) + assert query == "ubuntu" + assert content_type == "music" + assert timeout == lite_plugin_loader.PLUGIN_SEARCH_TIMEOUT + return [] + + monkeypatch.setattr(search_runner, "run_searches", run) + assert search_lite("ubuntu", "music") == [] + assert [job.kind for job in jobs_seen] == ["inline", "inline", "inline", "plugin"] + + +@responses.activate +def test_search_outcomes_distinguish_source_failures(monkeypatch): + import requests + + monkeypatch.setattr("helm.core.lite_plugin_loader.run_plugins", lambda query, dirs: []) + responses.add(responses.GET, "https://apibay.org/q.php", json=[]) + responses.add(responses.GET, "https://torrents-csv.com/service/search", status=503) + responses.add(responses.GET, "https://nyaa.si/", body=requests.exceptions.ConnectTimeout("private URL")) + results = search_lite("ubuntu") + assert results == [] + assert {o.source: o.status for o in results.outcomes} == { + "Apibay": "empty", + "Torrents-csv": "http_error", + "Nyaa": "timeout", + } + + +@responses.activate +def test_parse_failure_keeps_successful_sources_and_counts(monkeypatch): + monkeypatch.setattr("helm.core.lite_plugin_loader.run_plugins", lambda query, dirs: []) + responses.add(responses.GET, "https://apibay.org/q.php", json=[APITBAY_ITEM]) + responses.add(responses.GET, "https://torrents-csv.com/service/search", body="not-json") + responses.add(responses.GET, "https://nyaa.si/", body="broken XML") + results = search_lite("ubuntu") + assert len(results) == 1 + assert {o.source: (o.status, o.count) for o in results.outcomes} == { + "Apibay": ("success", 1), + "Torrents-csv": ("parse_error", 0), + "Nyaa": ("parse_error", 0), + } + + +def test_search_outcomes_do_not_leak_between_calls(monkeypatch): + from helm.core import lite_fetcher + from helm.core.rss_fetcher import SearchResults, SourceOutcome + + monkeypatch.setattr( + lite_fetcher, "_fetch_apibay", lambda query: SearchResults([], [SourceOutcome("Apibay", query)]) + ) + for name in ("_fetch_torrents_csv", "_fetch_nyaa"): + monkeypatch.setattr(lite_fetcher, name, lambda query: []) + first = search_lite("first") + second = search_lite("second") + assert first.outcomes[0].status == "first" + assert second.outcomes[0].status == "second" diff --git a/tests/test_lite_plugin_loader.py b/tests/test_lite_plugin_loader.py index 368af10..19bbce5 100644 --- a/tests/test_lite_plugin_loader.py +++ b/tests/test_lite_plugin_loader.py @@ -109,3 +109,40 @@ def test_run_plugins_does_not_leak_between_runs(plugin_dir): second = run_plugins("ubuntu", [plugin_dir]) assert len(first) == 1 assert len(second) == 1 + + +def test_reused_worker_keeps_previous_plugin_results(): + from concurrent.futures import ThreadPoolExecutor + + from helm.core.lite_plugin_loader import _execute_plugin + + class Plugin: + def search(self, query): + novaprinter.prettyPrinter({"name": query, "link": "magnet:?xt=urn:btih:1111"}) + + with ThreadPoolExecutor(max_workers=1) as executor: + first = executor.submit(_execute_plugin, Plugin(), "first").result() + second = executor.submit(_execute_plugin, Plugin(), "second").result() + assert [item.title for item in first] == ["first"] + assert [item.title for item in second] == ["second"] + + +def test_plugin_error_retains_partial_results_and_outcome(): + from concurrent.futures import ThreadPoolExecutor + + import requests + + from helm.core.lite_plugin_loader import _execute_plugin + + class Plugin: + name = "Partial" + + def search(self, query): + novaprinter.prettyPrinter({"name": query, "link": "magnet:?xt=urn:btih:1111"}) + raise requests.exceptions.ConnectTimeout("private URL") + + with ThreadPoolExecutor(max_workers=1) as executor: + result = executor.submit(_execute_plugin, Plugin(), "ubuntu").result() + assert len(result) == 1 + assert result[0].indexer == "Partial" + assert [(o.source, o.status, o.count) for o in result.outcomes] == [("Partial", "timeout", 1)] diff --git a/tests/test_logger.py b/tests/test_logger.py index 08cfc7b..4d92cde 100644 --- a/tests/test_logger.py +++ b/tests/test_logger.py @@ -47,3 +47,81 @@ def test_file_only_records_skipped_by_console_but_kept_by_file(capsys): captured = stream.getvalue() assert "visible warning" in captured assert "hidden warning" in captured + + +def test_importing_logging_does_not_create_files(tmp_path): + import subprocess + + environment = os.environ.copy() + root = os.path.abspath(os.path.join(os.path.dirname(__file__), "../src")) + environment.update( + PYTHONPATH=root, HELM_CONFIG_DIR=str(tmp_path / "config"), HELM_STATE_DIR=str(tmp_path / "state") + ) + result = subprocess.run( + [sys.executable, "-c", "import helm.cli; import helm.core.lite_fetcher"], + env=environment, + capture_output=True, + text=True, + ) + assert result.returncode == 0, result.stderr + assert not (tmp_path / "state").exists() + assert not (tmp_path / "config").exists() + + +def test_logging_reconfigures_after_path_override(monkeypatch, tmp_path): + from helm.core.logger import configure_logging, get_logger + + first, second = tmp_path / "first", tmp_path / "second" + monkeypatch.setenv("HELM_STATE_DIR", str(first)) + configure_logging() + get_logger("helm.test.paths").info("first-message") + monkeypatch.setenv("HELM_STATE_DIR", str(second)) + configure_logging() + get_logger("helm.test.paths").info("second-message") + assert "first-message" in (first / "helm.log").read_text() + assert "second-message" not in (first / "helm.log").read_text() + assert "second-message" in (second / "helm.log").read_text() + + +def test_formatters_redact_exception_and_structured_extras(monkeypatch): + from helm.core.logger import ConsoleFormatter, JSONFormatter, PlainTextFormatter + + monkeypatch.setenv("JACKETT_API_KEY", "private-key-123") + try: + raise ValueError("https://user:pass@example.test/search?apikey=unknown-token&x=1 private-key-123") + except ValueError: + record = logging.LogRecord( + "helm.test", logging.ERROR, __file__, 1, "request failed private-key-123", (), sys.exc_info() + ) + record.details = {"password": "extra-password", "url": "https://example.test/?token=other-secret"} + for formatter in (ConsoleFormatter(), JSONFormatter(), PlainTextFormatter()): + formatted = formatter.format(record) + assert "private-key-123" not in formatted + assert "unknown-token" not in formatted + assert "user:pass" not in formatted + assert "other-secret" not in formatted + assert "extra-password" not in formatted + import json + + assert json.loads(JSONFormatter().format(record))["details"]["password"] == "***REDACTED***" + + +def test_tail_reads_only_bounded_suffix_and_redacts(tmp_path, monkeypatch): + from helm.core.logger import tail_log + + path = tmp_path / "large.log" + path.write_text("old line\n" * 200000 + "apikey=old-unknown-secret\nlast line\n") + monkeypatch.setenv("JACKETT_API_KEY", "known-secret") + result = tail_log(path, lines=2, max_bytes=256) + assert "old-unknown-secret" not in result + assert result.endswith("last line\n") + assert len(result.splitlines()) == 2 + assert tail_log(path, lines=0) == "" + + +def test_tail_handles_a_single_oversized_record(tmp_path): + from helm.core.logger import tail_log + + path = tmp_path / "huge.log" + path.write_text("x" * 10000) + assert len(tail_log(path, max_bytes=64).encode()) <= 65 diff --git a/tests/test_qbittorrent_client.py b/tests/test_qbittorrent_client.py index 71de832..92b8365 100644 --- a/tests/test_qbittorrent_client.py +++ b/tests/test_qbittorrent_client.py @@ -1,30 +1,105 @@ +from urllib.parse import parse_qs + +import pytest import responses -from helm.core.qbittorrent_client import add_magnet, login_qbittorrent +import helm.core.qbittorrent_client as client +from helm.core.qbittorrent_client import add_magnet, delete_tagged, login_qbittorrent, qb_request +BASE = "http://localhost:8080" +MAGNET = "magnet:?xt=urn:btih:" + "a" * 40 -@responses.activate -def test_login_qbittorrent_bypassed(monkeypatch): + +@pytest.fixture(autouse=True) +def qbittorrent(monkeypatch): + monkeypatch.setenv("QB_WEBUI", BASE) monkeypatch.setenv("QB_PASSWORD", "testpass") - responses.add(responses.GET, "http://localhost:8080/api/v2/app/version", status=200) + monkeypatch.setattr(client, "_session", None) + monkeypatch.setattr(client, "_session_key", None) + + +@responses.activate +def test_login_qbittorrent_bypassed(): + responses.add(responses.GET, BASE + "/api/v2/app/version", status=200) + assert login_qbittorrent() is not None + assert [call.request.method for call in responses.calls] == ["GET"] + - # reset global _session - import helm.core.qbittorrent_client +@responses.activate +def test_add_magnet_submits_urls_and_tags(): + responses.add(responses.GET, BASE + "/api/v2/app/version", status=200) + responses.add(responses.POST, BASE + "/api/v2/torrents/add", status=200, body="Ok.") - helm.core.qbittorrent_client._session = None + add_magnet(MAGNET, save_path="/downloads/x", tag="helm,helm-job-1") - session = login_qbittorrent() - assert session is not None + body = parse_qs(responses.calls[-1].request.body) + assert body == {"urls": [MAGNET], "savepath": ["/downloads/x"], "tags": ["helm,helm-job-1"]} @responses.activate -def test_add_magnet(monkeypatch): - monkeypatch.setenv("QB_PASSWORD", "testpass") - responses.add(responses.GET, "http://localhost:8080/api/v2/app/version", status=200) - responses.add(responses.POST, "http://localhost:8080/api/v2/torrents/add", status=200) +def test_add_magnet_rejects_short_hash_before_any_request(): + with pytest.raises(ValueError, match="info hash"): + add_magnet("magnet:?xt=urn:btih:12345") + assert len(responses.calls) == 0 - import helm.core.qbittorrent_client - helm.core.qbittorrent_client._session = None +@responses.activate +def test_add_reports_qbittorrent_rejection(): + responses.add(responses.GET, BASE + "/api/v2/app/version", status=200) + responses.add(responses.POST, BASE + "/api/v2/torrents/add", status=200, body="Fails.") + with pytest.raises(RuntimeError, match="rejected"): + add_magnet(MAGNET) + + +@responses.activate +def test_expired_session_logs_in_again_and_retries_once(): + responses.add(responses.GET, BASE + "/api/v2/app/version", status=200) + responses.add(responses.GET, BASE + "/api/v2/torrents/info", status=403) + responses.add(responses.GET, BASE + "/api/v2/torrents/info", status=200, json=[{"hash": "abc"}]) + + assert qb_request("GET", "/api/v2/torrents/info").json() == [{"hash": "abc"}] + paths = [call.request.url.rsplit("/", 1)[1] for call in responses.calls] + assert paths == ["version", "info", "version", "info"] + + +@responses.activate +def test_persistent_403_is_raised(): + responses.add(responses.GET, BASE + "/api/v2/app/version", status=200) + responses.add(responses.GET, BASE + "/api/v2/torrents/info", status=403) + with pytest.raises(Exception, match="403"): + qb_request("GET", "/api/v2/torrents/info") + + +@responses.activate +def test_session_cache_follows_changed_url(monkeypatch): + other = "http://localhost:9090" + responses.add(responses.GET, BASE + "/api/v2/app/version", status=200) + responses.add(responses.GET, other + "/api/v2/app/version", status=200) + + first = login_qbittorrent() + assert login_qbittorrent() is first + monkeypatch.setenv("QB_WEBUI", other) + assert login_qbittorrent() is not first + + +@responses.activate +def test_login_failure_is_reported_and_not_cached(): + responses.add(responses.GET, BASE + "/api/v2/app/version", status=403) + responses.add(responses.POST, BASE + "/api/v2/auth/login", status=401, body="nope") + with pytest.raises(ConnectionError, match="401"): + login_qbittorrent() + assert client._session is None + + +@responses.activate +def test_delete_tagged_keeps_files_and_skips_empty_tags(): + responses.add(responses.GET, BASE + "/api/v2/app/version", status=200) + responses.add(responses.GET, BASE + "/api/v2/torrents/info", json=[{"hash": "a"}, {"hash": "b"}]) + responses.add(responses.POST, BASE + "/api/v2/torrents/delete", status=200) + delete_tagged("helm-job-1") + assert parse_qs(responses.calls[-1].request.body) == {"hashes": ["a|b"], "deleteFiles": ["false"]} - add_magnet("magnet:?xt=urn:btih:12345") + responses.replace(responses.GET, BASE + "/api/v2/torrents/info", json=[]) + count = len(responses.calls) + delete_tagged("helm-job-2") + assert len(responses.calls) == count + 1 diff --git a/tests/test_rss_fetcher.py b/tests/test_rss_fetcher.py index f781779..8161bb4 100644 --- a/tests/test_rss_fetcher.py +++ b/tests/test_rss_fetcher.py @@ -74,7 +74,7 @@ def test_search_indexers_falls_back_to_lite_when_manager_returns_nothing(monkeyp monkeypatch.setattr(rf, "search_jackett", lambda *a, **k: []) lite = TorrentItem("Ubuntu 24.04 Lite", "magnet:?xt=urn:btih:cafe", 5) - monkeypatch.setattr(lite_fetcher, "search_lite", lambda query: [lite]) + monkeypatch.setattr(lite_fetcher, "search_lite", lambda query, content_type: [lite]) # Must NOT raise ImportError despite the async search_all_plugins wrapper. items = rf.search_indexers("ubuntu", "video") @@ -91,7 +91,7 @@ def test_search_indexers_falls_back_to_lite_with_prowlarr_manager(monkeypatch): monkeypatch.setattr(rf, "search_jackett", lambda *a, **k: []) lite = TorrentItem("Ubuntu 24.04 Lite", "magnet:?xt=urn:btih:cafe", 5) - monkeypatch.setattr(lite_fetcher, "search_lite", lambda query: [lite]) + monkeypatch.setattr(lite_fetcher, "search_lite", lambda query, content_type: [lite]) ret = rf.search_indexers("ubuntu", "video") diff --git a/tests/test_runtime.py b/tests/test_runtime.py new file mode 100644 index 0000000..d2cab30 --- /dev/null +++ b/tests/test_runtime.py @@ -0,0 +1,235 @@ +"""Daemons and tmux sessions, using real processes and a private tmux socket.""" + +import json +import os +import shutil +import stat +import subprocess +import sys +import time +import uuid +from pathlib import Path +from types import SimpleNamespace + +import pytest + +import helm.core.runtime as runtime +from helm.core.config_manager import get_state_dir +from helm.core.runtime import ( + child_arguments, + child_environment, + daemon_records, + private_json, + process_alive, + process_start, + session_name, + start_daemon, + stop_daemon, +) + +SRC = str(Path(runtime.__file__).resolve().parents[2]) + + +def test_child_environment_never_adds_working_directory(monkeypatch): + monkeypatch.delenv("PYTHONPATH", raising=False) + assert child_environment()["PYTHONPATH"] == SRC + assert child_environment({"PYTHONPATH": ""})["PYTHONPATH"] == SRC + assert child_environment({"PYTHONPATH": "/x"})["PYTHONPATH"] == SRC + os.pathsep + "/x" + + +def test_process_identity(): + assert process_start(os.getpid()) + assert process_alive(os.getpid()) is True + assert process_alive(os.getpid(), process_start(os.getpid())) is True + assert process_alive(os.getpid(), "different-start-time") is False + assert process_alive(None) is False + assert process_alive("bad") is False + assert process_start(2**22 + 1) is None + + +def test_reaped_and_zombie_processes_are_not_alive(): + process = subprocess.Popen([sys.executable, "-c", "pass"]) + deadline = time.monotonic() + 5 + while process_start(process.pid) is not None and time.monotonic() < deadline: + time.sleep(0.01) + assert process_alive(process.pid) is False # Zombie: exited, not yet reaped. + process.wait() + assert process_alive(process.pid) is False + + +def test_private_json_is_atomic_and_private(tmp_path): + path = tmp_path / "sub" / "record.json" + private_json(path, {"a": 1}) + assert json.loads(path.read_text()) == {"a": 1} + assert stat.S_IMODE(path.stat().st_mode) == 0o600 + assert [item.name for item in path.parent.iterdir()] == ["record.json"] + + +@pytest.mark.parametrize( + "arguments,expected", + [ + (["watch", "d", "--daemon"], ["watch", "d"]), + (["--session", "a", "ui"], ["ui"]), + (["--session=a", "ui", "--lite"], ["ui", "--lite"]), + ], +) +def test_child_arguments(arguments, expected): + assert child_arguments(arguments) == expected + + +@pytest.mark.parametrize("value", ["", "a b", "a;b", "x" * 41, "../x"]) +def test_session_names_are_validated(value): + with pytest.raises(ValueError): + session_name(value) + + +def fake_cli(tmp_path, monkeypatch, body): + package = tmp_path / "fake" / "helm" + package.mkdir(parents=True) + (package / "__init__.py").write_text("") + (package / "cli.py").write_text(body) + monkeypatch.setattr(runtime, "child_environment", lambda: {**os.environ, "PYTHONPATH": str(tmp_path / "fake")}) + + +def wait_for(condition, timeout=10): + deadline = time.monotonic() + timeout + while not condition(): + assert time.monotonic() < deadline + time.sleep(0.02) + + +def test_daemon_lifecycle_with_graceful_stop(tmp_path, monkeypatch): + marker = tmp_path / "stopped" + fake_cli( + tmp_path, + monkeypatch, + "import signal,sys,time\n" + f"signal.signal(signal.SIGTERM, lambda *a: (open({str(marker)!r},'w').close(), sys.exit(0)))\n" + "print('started', flush=True)\n" + "time.sleep(60)\n", + ) + identifier = start_daemon(["--daemon", "serve", "--port", "0"]) + record = next(item for item in daemon_records() if item["id"] == identifier) + assert record["running"] is True + assert record["command"] == "serve --port 0" + log = Path(record["log"]) + assert stat.S_IMODE(log.stat().st_mode) == 0o600 + wait_for(lambda: "started" in log.read_text()) + assert stop_daemon(identifier) is True + wait_for(marker.exists) + wait_for(lambda: not process_alive(record["pid"], record["identity"])) + assert stop_daemon(identifier) is False + assert next(item for item in daemon_records() if item["id"] == identifier)["running"] is False + + +def test_forced_stop_kills_whole_process_group(tmp_path, monkeypatch): + child_pid = tmp_path / "child" + fake_cli( + tmp_path, + monkeypatch, + "import signal,subprocess,sys,time\n" + "signal.signal(signal.SIGTERM, signal.SIG_IGN)\n" + "p = subprocess.Popen([sys.executable, '-c', 'import signal,time; signal.signal(signal.SIGTERM, signal.SIG_IGN); time.sleep(60)'])\n" + f"open({str(child_pid)!r},'w').write(str(p.pid))\n" + "time.sleep(60)\n", + ) + identifier = start_daemon(["serve"]) + wait_for(lambda: child_pid.exists() and child_pid.read_text()) + assert stop_daemon(identifier, timeout=0.2) is True + + def gone(): + return process_start(int(child_pid.read_text())) is None + + wait_for(gone) + + +def test_immediate_daemon_failure_is_reported(tmp_path, monkeypatch): + fake_cli(tmp_path, monkeypatch, "raise SystemExit(3)\n") + # Give the child time to exit inside the normally brief failure window. + clock = SimpleNamespace(time=time.time, sleep=lambda _: time.sleep(2)) + monkeypatch.setattr(runtime, "time", clock) + with pytest.raises(RuntimeError, match="failed"): + start_daemon(["serve"]) + + +def test_stop_validates_identifier(): + with pytest.raises(ValueError): + stop_daemon("../../etc/passwd") + with pytest.raises(OSError): + stop_daemon("0" * 12) + + +def test_process_without_identity_is_not_signalled(monkeypatch): + directory = Path(get_state_dir()) / "daemons" + identifier = "a" * 12 + private_json(directory / (identifier + ".json"), {"id": identifier, "pid": os.getpid(), "identity": None}) + try: + with pytest.raises(RuntimeError, match="identity"): + stop_daemon(identifier) + finally: + (directory / (identifier + ".json")).unlink() + + +def test_corrupt_records_are_skipped(): + directory = Path(get_state_dir()) / "daemons" + directory.mkdir(parents=True, exist_ok=True) + (directory / "corrupt.json").write_text("{") + try: + assert all(record.get("id") != "corrupt" for record in daemon_records()) + finally: + (directory / "corrupt.json").unlink() + + +def test_missing_tmux_gives_install_hint(monkeypatch): + monkeypatch.setattr(runtime.shutil, "which", lambda _: None) + with pytest.raises(RuntimeError, match="Install tmux"): + runtime.tmux_command("list-sessions") + + +@pytest.fixture +def tmux_socket(monkeypatch): + if shutil.which("tmux") is None: + pytest.skip("tmux is not installed") + name = "helm-test-" + uuid.uuid4().hex + monkeypatch.setenv("HELM_TMUX_SOCKET", name) + yield name + subprocess.run(["tmux", "-L", name, "kill-server"], capture_output=True) + + +def test_tmux_session_forwards_paths_to_existing_server(tmux_socket, tmp_path, monkeypatch): + fake_cli( + tmp_path, + monkeypatch, + "import json,os,sys,time\n" + f"open({str(tmp_path / 'seen')!r},'w').write(json.dumps([sys.argv[1:], os.environ['HELM_STATE_DIR'], os.environ.get('HELM_SERVER_TOKEN')]))\n" + "time.sleep(60)\n", + ) + monkeypatch.setenv("HELM_SERVER_TOKEN", "must-not-be-forwarded") + # A server started first has an older environment that must not win. + subprocess.run( + ["tmux", "-L", tmux_socket, "new-session", "-d", "-s", "other", "sleep", "60"], + env={**{k: v for k, v in os.environ.items() if k != "HELM_SERVER_TOKEN"}, "HELM_STATE_DIR": "/stale"}, + check=True, + ) + monkeypatch.setenv("HELM_STATE_DIR", str(tmp_path / "state")) + assert runtime.start_session("main", ["--session", "main", "--lite"]) == "helm-torrent-main" + seen = tmp_path / "seen" + wait_for(lambda: seen.exists() and seen.read_text()) + arguments, state, token = json.loads(seen.read_text()) + assert arguments == ["--lite", "ui"] + assert state == str(tmp_path / "state") + assert token is None + with pytest.raises(ValueError, match="already exists"): + runtime.start_session("main", []) + + +def test_attach_requires_existing_session_and_execs_tmux(tmux_socket, monkeypatch): + with pytest.raises(ValueError, match="No running"): + runtime.attach_session("missing") + subprocess.run( + ["tmux", "-L", tmux_socket, "new-session", "-d", "-s", "helm-torrent-main", "sleep", "60"], check=True + ) + calls = [] + monkeypatch.setattr(runtime.os, "execvp", lambda file, arguments: calls.append(arguments)) + runtime.attach_session("main") + assert calls == [["tmux", "-L", tmux_socket, "attach-session", "-t", "=helm-torrent-main"]] diff --git a/tests/test_scraper_fixtures.py b/tests/test_scraper_fixtures.py new file mode 100644 index 0000000..8e25327 --- /dev/null +++ b/tests/test_scraper_fixtures.py @@ -0,0 +1,161 @@ +"""Offline response fixtures for every bundled HTML scraper and plugin errors.""" + +import sys +from pathlib import Path + +import pytest +import requests +import responses + +from helm.core.lite_plugin_loader import _execute_plugin, load_plugin, plugin_categories + +PLUGIN_DIR = Path(__file__).resolve().parents[1] / "src" / "helm" / "plugins" +sys.path.insert(0, str(PLUGIN_DIR)) + +HTML_FIXTURES = { + "bitsearch": """""", + "limetorrents": """ +
Generated fixture2 days1.5 GB123
""", + "torlock": """""", + "torrentproject": """
Generated fixture +verified1232026-01-01 00:00:001.5 GB
""", +} + + +@pytest.mark.parametrize("name", sorted(HTML_FIXTURES)) +@responses.activate +def test_html_scraper_fixture_roundtrip(name): + plugin = load_plugin(str(PLUGIN_DIR / (name + ".py"))) + responses.add(responses.GET, __import__("re").compile("https://.*"), body=HTML_FIXTURES[name]) + result = _execute_plugin(plugin, "generated", "all") + assert len(result) == 1 + assert result[0].title == "Generated fixture" + assert result[0].seeders == 12 + assert result[0].leechers == 3 + assert result[0].size == int(1.5 * 1024**3) + assert result.outcomes[0].status == "success" + + +@pytest.mark.parametrize("name", sorted(HTML_FIXTURES)) +@responses.activate +def test_html_scraper_distinguishes_blocked_or_changed_page(name): + plugin = load_plugin(str(PLUGIN_DIR / (name + ".py"))) + responses.add(responses.GET, __import__("re").compile("https://.*"), body="Just a moment...") + result = _execute_plugin(plugin, "generated", "all") + assert result == [] + assert result.outcomes[0].status == "parse_error" + + +@pytest.mark.parametrize( + "name", + ["bitsearch", "limetorrents", "torlock", "torrentproject", "eztv", "subsplease", "yts", "bittorrented", "x1337"], +) +@pytest.mark.parametrize( + "failure,status", [(requests.exceptions.ConnectTimeout("unreachable"), "timeout"), (None, "http_error")] +) +@responses.activate +def test_bundled_plugins_report_swallowed_http_failures(name, failure, status): + plugin = load_plugin(str(PLUGIN_DIR / (name + ".py"))) + responses.add(responses.GET, __import__("re").compile("https://.*"), body=failure or "forbidden", status=403) + result = _execute_plugin(plugin, "generated", "all") + assert result == [] + assert result.outcomes[0].status == status + + +@pytest.mark.parametrize("name", ["eztv", "subsplease", "yts", "bittorrented"]) +@responses.activate +def test_api_plugins_report_invalid_json(name): + plugin = load_plugin(str(PLUGIN_DIR / (name + ".py"))) + responses.add(responses.GET, __import__("re").compile("https://.*"), body="broken JSON") + result = _execute_plugin(plugin, "generated", "all") + assert result == [] + assert result.outcomes[0].status == "parse_error" + + +@responses.activate +def test_piratebay_fixture_and_http_error(monkeypatch): + import io + + plugin = load_plugin(str(PLUGIN_DIR / "piratebay.py")) + payload = b'[{"id":"1","added":"1700000000","name":"Generated fixture","info_hash":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","seeders":"12","leechers":"3","size":"123"}]' + + class Response(io.BytesIO): + def getheader(self, name, default): + return "application/json; charset=utf-8" + + monkeypatch.setattr("urllib.request.urlopen", lambda request, timeout: Response(payload)) + result = _execute_plugin(plugin, "generated", "music") + assert len(result) == 1 and result[0].seeders == 12 + import urllib.error + + def fail(request, timeout): + raise urllib.error.HTTPError(request.full_url, 403, "forbidden", {}, None) + + monkeypatch.setattr("urllib.request.urlopen", fail) + result = _execute_plugin(plugin, "generated", "music") + assert result == [] and result.outcomes[0].status == "http_error" + + +@pytest.mark.parametrize( + "content,expected", + [ + ("video", ["movies", "tv", "anime"]), + ("music", ["music"]), + ("video,music", ["movies", "tv", "anime", "music"]), + ("books", ["all"]), + ], +) +def test_category_mapping_for_supported_plugin(content, expected): + plugin = load_plugin(str(PLUGIN_DIR / "limetorrents.py")) + assert plugin_categories(plugin, content) == expected + + +def test_loader_passes_category_keys_and_avoids_duplicate_all(): + calls = [] + + class Plugin: + supported_categories = {"all": "0", "music": "100", "movies": "200", "tv": "500"} + + def search(self, query, cat="all"): + calls.append(cat) + + _execute_plugin(Plugin(), "generated", "video,music") + assert calls == ["movies", "tv", "music"] + calls.clear() + _execute_plugin(Plugin(), "generated", "books,music") + assert calls == ["all"] + + +@responses.activate +def test_unknown_subsplease_seeders_survive_filter(): + from helm.core.torrent_filter import filter_items + + plugin = load_plugin(str(PLUGIN_DIR / "subsplease.py")) + responses.add( + responses.GET, + "https://subsplease.org/api/", + json={ + "show": {"show": "Generated", "downloads": [{"res": "1080", "magnet": "magnet:?xt=urn:btih:" + "a" * 40}]} + }, + ) + result = _execute_plugin(plugin, "generated") + assert result[0].seeders == -1 + assert filter_items(result, {"video": []}, [], min_seeds=3) == result + + +def test_http_sessions_are_reused_per_thread_but_not_shared(): + import threading + + from helm.core.http import get_shared_session + + main = get_shared_session() + assert main is get_shared_session() + others = [] + thread = threading.Thread(target=lambda: others.append(get_shared_session())) + thread.start() + thread.join() + assert others[0] is not main diff --git a/tests/test_search_runner.py b/tests/test_search_runner.py new file mode 100644 index 0000000..c50d646 --- /dev/null +++ b/tests/test_search_runner.py @@ -0,0 +1,205 @@ +import json +import os +import subprocess +import sys +import time +from pathlib import Path + +import pytest + +from helm.core.search_runner import SearchJob, run_searches + + +def make_plugin(tmp_path, name, body): + path = tmp_path / (name + ".py") + path.write_text( + "from novaprinter import prettyPrinter\nclass " + + name + + ":\n name = '" + + name + + "'\n def search(self, query, cat='all'):\n" + + "\n".join(" " + line for line in body.splitlines()) + + "\n" + ) + return SearchJob(name, "plugin", str(path)) + + +def test_worker_roundtrip_and_category_propagation(tmp_path): + job = make_plugin( + tmp_path, "fixture", "prettyPrinter({'name': query, 'link': 'magnet:?xt=urn:btih:' + 'a'*40, 'seeds': 12})" + ) + result = run_searches([job], "generated", timeout=5) + assert len(result) == 1 + assert result[0].title == "generated" + assert [(o.source, o.status, o.count) for o in result.outcomes] == [("fixture", "success", 1)] + + +def test_stalled_worker_cannot_delay_process_exit(tmp_path): + stalled = make_plugin(tmp_path, "stalled", "import time\nwhile True: time.sleep(1)") + healthy = make_plugin( + tmp_path, "healthy", "prettyPrinter({'name': 'healthy', 'link': 'magnet:?xt=urn:btih:' + 'b'*40})" + ) + environment = os.environ.copy() + environment["PYTHONPATH"] = str(Path(__file__).resolve().parents[1] / "src") + code = """import json +from helm.core.search_runner import SearchJob, run_searches +jobs = [SearchJob(**job) for job in json.loads(__import__('sys').argv[1])] +result = run_searches(jobs, 'generated', timeout=1) +print(json.dumps({'titles': [i.title for i in result], 'outcomes': [(o.source, o.status) for o in result.outcomes]})) +""" + from dataclasses import asdict + + started = time.monotonic() + process = subprocess.run( + [sys.executable, "-c", code, json.dumps([asdict(stalled), asdict(healthy)])], + env=environment, + capture_output=True, + text=True, + timeout=4, + ) + assert process.returncode == 0, process.stderr + assert time.monotonic() - started < 4 + data = json.loads(process.stdout) + assert data["titles"] == ["healthy"] + assert ["stalled", "timeout"] in data["outcomes"] + + +def test_plugin_import_is_isolated_and_bounded(tmp_path): + path = tmp_path / "bad.py" + path.write_text("import time\nwhile True: time.sleep(1)\n") + started = time.monotonic() + result = run_searches([SearchJob("bad", "plugin", str(path))], "generated", timeout=0.3) + assert result == [] + assert result.outcomes[0].status == "timeout" + assert time.monotonic() - started < 2 + + +def test_worker_exception_and_noise_are_contained(tmp_path): + job = make_plugin( + tmp_path, "noisy", "import sys\nprint('noise')\nsys.stdout.write('more noise')\nraise ValueError('bad parse')" + ) + result = run_searches([job], "generated", timeout=5) + assert result == [] + assert result.outcomes[0].status == "parse_error" + + +def test_queued_jobs_share_the_deadline(tmp_path): + job = make_plugin(tmp_path, "stalled", "import time\ntime.sleep(20)") + result = run_searches([job, job, job], "generated", timeout=0.3, max_workers=1) + assert [outcome.status for outcome in result.outcomes] == ["timeout", "budget_exhausted", "budget_exhausted"] + + +@pytest.mark.parametrize("timeout,workers", [(0, 1), (1, 0)]) +def test_invalid_worker_limits(timeout, workers): + with pytest.raises(ValueError): + run_searches([], "generated", timeout=timeout, max_workers=workers) + + +def test_keyboard_interrupt_reaps_workers(monkeypatch, tmp_path): + import concurrent.futures + + import helm.core.search_runner as runner + + job = make_plugin(tmp_path, "stalled", "import time\ntime.sleep(20)") + original = concurrent.futures.Future.result + interrupted = False + + def interrupt_once(self, *args, **kwargs): + nonlocal interrupted + if not interrupted: + interrupted = True + time.sleep(0.15) + raise KeyboardInterrupt + return original(self, *args, **kwargs) + + monkeypatch.setattr(concurrent.futures.Future, "result", interrupt_once) + started = time.monotonic() + with pytest.raises(KeyboardInterrupt): + runner.run_searches([job], "generated", timeout=20) + assert time.monotonic() - started < 3 + + +@pytest.mark.skipif(os.name != "posix", reason="POSIX process group cleanup") +def test_worker_descendants_are_stopped_even_after_leader_exits(tmp_path): + pid_file = tmp_path / "child.pid" + job = make_plugin( + tmp_path, + "spawner", + "import subprocess, sys\nfrom pathlib import Path\nchild = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(60)'], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)\nPath(query).write_text(str(child.pid))", + ) + result = run_searches([job], str(pid_file), timeout=5) + assert result.outcomes[0].status == "empty" + child = int(pid_file.read_text()) + deadline = time.monotonic() + 1 + while time.monotonic() < deadline: + try: + stat = Path(f"/proc/{child}/stat").read_text() + except FileNotFoundError: + return + if stat.rsplit(")", 1)[1].split()[0] == "Z": + return # terminated; waiting for the OS init process to reap it + time.sleep(0.01) + pytest.fail("Worker descendant is still running") + + +def test_category_keys_reach_real_worker(tmp_path): + path = tmp_path / "categorized.py" + path.write_text( + "from novaprinter import prettyPrinter\nclass categorized:\n name = 'categorized'\n supported_categories = {'all': '0', 'movies': '1', 'tv': '2', 'music': '3'}\n def search(self, query, cat='all'):\n prettyPrinter({'name': cat, 'link': 'magnet:?xt=urn:btih:' + 'a'*40})\n" + ) + result = run_searches([SearchJob("categorized", "plugin", str(path))], "generated", "video", timeout=5) + assert [item.title for item in result] == ["movies", "tv"] + assert result.outcomes[0].count == 2 + + +def test_windows_cleanup_uses_tree_termination(monkeypatch): + from types import SimpleNamespace + from unittest.mock import Mock + + import helm.core.search_runner as runner + + process = Mock() + process.pid = 123 + process.poll.return_value = None + monkeypatch.setattr(runner, "os", SimpleNamespace(name="nt")) + terminate = Mock() + monkeypatch.setattr(runner.subprocess, "run", terminate) + runner.stop_worker(process) + assert terminate.call_args[0][0] == ["taskkill", "/PID", "123", "/T", "/F"] + process.kill.assert_called_once_with() + process.communicate.assert_called_once_with(timeout=1) + + +def test_invalid_job_kind_reports_failure(tmp_path): + result = run_searches([SearchJob("unknown", "unsupported", "none")], "generated", timeout=5) + assert result == [] + assert result.outcomes[0].status == "parse_error" + + +def test_worker_limit_environment_and_explicit_override(monkeypatch): + from helm.core.search_runner import worker_count + + monkeypatch.setenv("HELM_LITE_WORKERS", "2") + assert worker_count() == 2 + assert worker_count(6) == 6 + monkeypatch.setenv("HELM_LITE_WORKERS", "invalid") + with pytest.raises(ValueError): + worker_count() + with pytest.raises(ValueError): + worker_count(13) + + +def test_worker_errors_reach_parent_log_with_secrets_redacted(monkeypatch, tmp_path): + from helm.core.logger import configure_logging + + logs = tmp_path / "logs" + monkeypatch.setenv("HELM_STATE_DIR", str(logs)) + monkeypatch.setenv("QB_PASSWORD", "known-worker-private") + configure_logging() + job = make_plugin(tmp_path, "failure", "raise ValueError('known-worker-private url?apikey=unknown-worker-private')") + result = run_searches([job], "generated", timeout=5) + assert result.outcomes[0].status == "parse_error" + contents = (logs / "helm.log").read_text() + assert "ValueError" in contents + assert "known-worker-private" not in contents + assert "unknown-worker-private" not in contents diff --git a/tests/test_secret_manager.py b/tests/test_secret_manager.py index 9edfb9b..c33a9cd 100644 --- a/tests/test_secret_manager.py +++ b/tests/test_secret_manager.py @@ -94,3 +94,35 @@ def test_sanitize_link_strips_apikey(): def test_sanitize_link_leaves_magnets_alone(): magnet = "magnet:?xt=urn:btih:abcd" assert sanitize_link(magnet) == magnet + + +def test_secrets_cache_follows_config_override(monkeypatch, tmp_path): + from helm.core import secret_manager + + first, second = tmp_path / "first", tmp_path / "second" + first.mkdir() + second.mkdir() + (first / "secrets.env").write_text("JACKETT_PASSWORD=first-private\n") + (second / "secrets.env").write_text("JACKETT_PASSWORD=second-private\n") + monkeypatch.delenv("JACKETT_PASSWORD", raising=False) + monkeypatch.setenv("HELM_CONFIG_DIR", str(first)) + assert secret_manager.get_secret("JACKETT_PASSWORD") == "first-private" + monkeypatch.setenv("HELM_CONFIG_DIR", str(second)) + assert secret_manager.get_secret("JACKETT_PASSWORD") == "second-private" + + +def test_redaction_handles_nested_config_and_encoded_secrets(monkeypatch): + from helm.core.secret_manager import redact_config, redact_text + + monkeypatch.setenv("QB_PASSWORD", "p@ss word") + original = { + "nested": {"password": "unknown", "url": "https://alice:other@example.test/?apikey=abc123"}, + "values": ["p%40ss%20word", "p%40ss+word"], + } + result = redact_config(original) + assert result["nested"]["password"] == "***REDACTED***" + assert "abc123" not in str(result) + assert "alice:other" not in str(result) + assert all(value == "***REDACTED***" for value in result["values"]) + assert original["nested"]["password"] == "unknown" + assert "header-secret" not in redact_text("Authorization: Bearer header-secret") diff --git a/tests/test_server.py b/tests/test_server.py new file mode 100644 index 0000000..9c9a33c --- /dev/null +++ b/tests/test_server.py @@ -0,0 +1,367 @@ +"""The HTTP API, spoken to over a real socket.""" + +import http.client +import json +import socket +import threading +import time +from pathlib import Path + +import pytest +import requests + +import helm.core.server as server_module +from helm.core.config_manager import get_dl_dir +from helm.core.jobs import JobStore +from helm.core.secret_manager import get_secret +from helm.core.server import byte_range, is_loopback, make_server, run_server + +TOKEN = "t" * 32 +AUTH = {"Authorization": "Bearer " + TOKEN} +MAGNET = "magnet:?xt=urn:btih:" + "a" * 40 + + +@pytest.fixture +def downloads(tmp_path, monkeypatch): + root = tmp_path / "downloads" + root.mkdir() + monkeypatch.setenv("HELM_DL_DIR", str(root)) + return root + + +def launch(tmp_path, read_only=False): + store = JobStore(tmp_path / "state" / "jobs.sqlite3") + server, _ = make_server("127.0.0.1", 0, store=store, token=TOKEN, lite=True, read_only=read_only) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + return server, thread, store + + +@pytest.fixture +def api(tmp_path, downloads): + server, thread, store = launch(tmp_path) + yield f"http://127.0.0.1:{server.server_port}", store + server.shutdown() + server.server_close() + thread.join() + + +@pytest.fixture +def read_only_api(tmp_path, downloads): + server, thread, store = launch(tmp_path, read_only=True) + yield f"http://127.0.0.1:{server.server_port}", store + server.shutdown() + server.server_close() + thread.join() + + +def add_file(store, name="movie.bin", content=b"0123456789"): + path = Path(get_dl_dir()) / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(content) + job = store.enqueue("magnet:?xt=urn:btih:" + "f" * 40, lite=True) + store.register_files(job["id"], [path]) + return path + + +@pytest.mark.parametrize( + "header,size,expected", + [ + (None, 10, (0, 9, False)), + (None, 0, (0, 0, False)), + ("bytes=0-", 10, (0, 9, True)), + ("bytes=2-4", 10, (2, 4, True)), + ("bytes=8-100", 10, (8, 9, True)), + ("bytes=-3", 10, (7, 9, True)), + ("bytes=-30", 10, (0, 9, True)), + ], +) +def test_byte_range(header, size, expected): + assert byte_range(header, size) == expected + + +@pytest.mark.parametrize( + "header,size", [("bytes=10-", 10), ("bytes=5-2", 10), ("bytes=-0", 10), ("x", 10), ("bytes=0-", 0), ("bytes=-", 10)] +) +def test_invalid_byte_range(header, size): + with pytest.raises(ValueError): + byte_range(header, size) + + +@pytest.mark.parametrize( + "host,expected", + [("127.0.0.1", True), ("::1", True), ("localhost", True), ("0.0.0.0", False), ("example.test", False)], +) +def test_is_loopback(host, expected): + assert is_loopback(host) is expected + + +@pytest.mark.parametrize("path", ["/health", "/jobs", "/files", "/files/x", "/anything"]) +@pytest.mark.parametrize("headers", [{}, {"Authorization": "Bearer wrong"}, {"Authorization": "Basic " + TOKEN}]) +def test_every_route_requires_the_token(api, path, headers): + assert requests.get(api[0] + path, headers=headers).status_code == 401 + + +def test_health_and_unknown_route(api): + assert requests.get(api[0] + "/health", headers=AUTH).json() == {"status": "ok", "read_only": False} + assert requests.get(api[0] + "/nope", headers=AUTH).status_code == 404 + + +def test_submit_list_get_and_cancel_job(api): + base, store = api + created = requests.post(base + "/jobs", headers=AUTH, json={"source": MAGNET}) + assert created.status_code == 202 + identifier = created.json()["id"] + assert store.get(identifier)["lite"] == 1 + assert [job["id"] for job in requests.get(base + "/jobs", headers=AUTH).json()] == [identifier] + assert requests.get(f"{base}/jobs/{identifier}", headers=AUTH).json()["status"] == "pending" + assert requests.get(base + "/jobs/" + "0" * 32, headers=AUTH).status_code == 404 + assert requests.delete(f"{base}/jobs/{identifier}", headers=AUTH).json() == {"cancelled": True} + assert requests.delete(f"{base}/jobs/{identifier}", headers=AUTH).status_code == 409 + assert requests.delete(base + "/jobs/" + "0" * 32, headers=AUTH).status_code == 404 + assert requests.delete(base + "/jobs/not-an-id", headers=AUTH).status_code == 404 + + +@pytest.mark.parametrize( + "body", + [ + b"not json", + b"[]", + b"{}", + b'{"source": 1}', + b'{"source": "/etc/passwd"}', + b'{"source": "a.torrent"}', + b'{"source": "http://"}', + b'{"source": "magnet:?xt=urn:btih:12345"}', + b"\xff\xfe", + b"[" * 60000, + ], +) +def test_invalid_submissions_are_rejected(api, body): + base, store = api + response = requests.post(base + "/jobs", headers={**AUTH, "Content-Type": "application/json"}, data=body) + assert response.status_code == 400 + assert store.list() == [] + + +def test_body_limits_and_content_type(api): + base, _ = api + json_type = {**AUTH, "Content-Type": "application/json"} + assert requests.post(base + "/jobs", headers=json_type, data=b"x" * 65537).status_code == 413 + assert requests.post(base + "/jobs", headers=json_type, data=b"").status_code == 413 + response = requests.post(base + "/jobs", headers={**AUTH, "Content-Type": "text/plain"}, data=b"{}") + assert response.status_code == 400 + assert requests.post(base + "/other", headers=json_type, data=b"{}").status_code == 404 + + +def test_rejected_body_cannot_become_a_second_request(api): + """An unread body on a kept-alive connection would otherwise parse as a request.""" + base, _ = api + host, port = base.rsplit("//", 1)[1].split(":") + smuggled = f"GET /health HTTP/1.1\r\nHost: x\r\nAuthorization: Bearer {TOKEN}\r\n\r\n".encode() + head = ( + f"POST /jobs HTTP/1.1\r\nHost: x\r\nAuthorization: Bearer {TOKEN}\r\n" + f"Content-Type: text/plain\r\nContent-Length: {len(smuggled)}\r\n\r\n" + ).encode() + with socket.create_connection((host, int(port)), timeout=5) as connection: + connection.sendall(head + smuggled) + received = b"" + while True: + chunk = connection.recv(65536) + if not chunk: + break + received += chunk + assert received.count(b"HTTP/1.") == 1 + assert b" 400 " in received + + +def test_read_only_server_refuses_changes(read_only_api): + base, store = read_only_api + assert requests.post(base + "/jobs", headers=AUTH, json={"source": MAGNET}).status_code == 403 + job = store.enqueue(MAGNET) + assert requests.delete(f"{base}/jobs/{job['id']}", headers=AUTH).status_code == 403 + assert store.get(job["id"])["status"] == "pending" + assert requests.get(base + "/health", headers=AUTH).json()["read_only"] is True + + +def test_stream_full_file_and_catalog(api): + base, store = api + add_file(store, "sub dir/movie.bin") + assert [item["path"] for item in requests.get(base + "/files", headers=AUTH).json()] == ["sub dir/movie.bin"] + response = requests.get(base + "/files/sub%20dir/movie.bin", headers=AUTH) + assert response.status_code == 200 and response.content == b"0123456789" + assert response.headers["Accept-Ranges"] == "bytes" + + +def test_large_file_arrives_intact(api): + base, store = api + content = bytes(range(256)) * 40000 + add_file(store, "large.bin", content) + assert requests.get(base + "/files/large.bin", headers=AUTH).content == content + middle = requests.get(base + "/files/large.bin", headers={**AUTH, "Range": "bytes=5000000-5999999"}) + assert middle.content == content[5000000:6000000] + + +@pytest.mark.parametrize( + "header,body,content_range", + [("bytes=2-4", b"234", "bytes 2-4/10"), ("bytes=-2", b"89", "bytes 8-9/10"), ("bytes=8-", b"89", "bytes 8-9/10")], +) +def test_range_requests(api, header, body, content_range): + base, store = api + add_file(store) + response = requests.get(base + "/files/movie.bin", headers={**AUTH, "Range": header}) + assert response.status_code == 206 + assert response.content == body + assert response.headers["Content-Range"] == content_range + + +def test_unsatisfiable_range(api): + base, store = api + add_file(store) + response = requests.get(base + "/files/movie.bin", headers={**AUTH, "Range": "bytes=50-"}) + assert response.status_code == 416 + assert response.headers["Content-Range"] == "bytes */10" + + +def test_keep_alive_survives_range_requests(api): + base, store = api + add_file(store) + host, port = base.rsplit("//", 1)[1].split(":") + connection = http.client.HTTPConnection(host, int(port), timeout=5) + for _ in range(3): + connection.request("GET", "/files/movie.bin", headers={**AUTH, "Range": "bytes=0-1"}) + assert connection.getresponse().read() == b"01" + connection.close() + + +def test_head_has_headers_and_no_body(api): + base, store = api + add_file(store) + response = requests.head(base + "/files/movie.bin", headers=AUTH) + assert response.status_code == 200 + assert response.headers["Content-Length"] == "10" + assert response.content == b"" + + +def test_empty_file(api): + base, store = api + add_file(store, "empty.bin", b"") + response = requests.get(base + "/files/empty.bin", headers=AUTH) + assert response.status_code == 200 and response.content == b"" + + +def test_only_cataloged_files_are_served(api): + base, _ = api + (Path(get_dl_dir()) / "partial.bin").write_bytes(b"secret") + assert requests.get(base + "/files/partial.bin", headers=AUTH).status_code == 404 + + +@pytest.mark.parametrize("path", ["../outside", "..%2Foutside", "%2e%2e/outside", "a/../../outside"]) +def test_traversal_is_refused(api, path, tmp_path): + base, _ = api + (tmp_path / "outside").write_bytes(b"secret") + prepared = requests.Request("GET", base + "/files/x", headers=AUTH).prepare() + prepared.url = base + "/files/" + path + assert requests.Session().send(prepared).status_code == 404 + + +def test_cataloged_file_replaced_by_symlink_is_refused(api, tmp_path): + base, store = api + path = add_file(store) + outside = tmp_path / "outside" + outside.write_bytes(b"secret") + path.unlink() + path.symlink_to(outside) + assert requests.get(base + "/files/movie.bin", headers=AUTH).status_code == 404 + + +def test_cataloged_file_behind_symlinked_directory_is_refused(api, tmp_path): + base, store = api + add_file(store, "sub/movie.bin") + root = Path(get_dl_dir()) + (root / "sub" / "movie.bin").unlink() + (root / "sub").rmdir() + outside = tmp_path / "elsewhere" + outside.mkdir() + (outside / "movie.bin").write_bytes(b"secret") + (root / "sub").symlink_to(outside) + assert requests.get(base + "/files/sub/movie.bin", headers=AUTH).status_code == 404 + + +def test_deleted_file_is_not_found(api): + base, store = api + add_file(store).unlink() + assert requests.get(base + "/files/movie.bin", headers=AUTH).status_code == 404 + + +def test_stalled_client_releases_its_thread(tmp_path, downloads, monkeypatch): + monkeypatch.setattr(server_module, "REQUEST_TIMEOUT", 0.2) + server, thread, _ = launch(tmp_path) + try: + with socket.create_connection(("127.0.0.1", server.server_port), timeout=5) as connection: + connection.sendall(b"POST /jobs HTTP/1.1\r\nHost: x\r\n") + connection.settimeout(5) + started = time.monotonic() + assert connection.recv(1024) == b"" + assert time.monotonic() - started < 4 + finally: + server.shutdown() + server.server_close() + thread.join() + + +def test_short_token_is_rejected(tmp_path): + with pytest.raises(ValueError, match="16"): + make_server("127.0.0.1", 0, store=JobStore(tmp_path / "j.sqlite3"), token="short") + + +def test_token_is_generated_once(tmp_path): + store = JobStore(tmp_path / "j.sqlite3") + server, _ = make_server("127.0.0.1", 0, store=store) + server.server_close() + token = get_secret("HELM_SERVER_TOKEN") + assert token and len(token) >= 16 + server, _ = make_server("127.0.0.1", 0, store=store) + server.server_close() + assert get_secret("HELM_SERVER_TOKEN") == token + + +@pytest.mark.parametrize("read_only", [False, True]) +def test_run_server_serves_then_shuts_down(tmp_path, monkeypatch, capsys, read_only): + store = JobStore(tmp_path / "j.sqlite3") + monkeypatch.setattr(server_module, "JobStore", lambda: store) + monkeypatch.setenv("HELM_SERVER_TOKEN", TOKEN) + monkeypatch.setattr(server_module, "queue_loop", lambda store, stop: stop.wait()) + with socket.socket() as probe: + probe.bind(("127.0.0.1", 0)) + port = probe.getsockname()[1] + stop = threading.Event() + thread = threading.Thread( + target=run_server, args=("127.0.0.1", port), kwargs={"read_only": read_only, "stop": stop} + ) + thread.start() + try: + deadline = time.monotonic() + 5 + while True: + try: + response = requests.get(f"http://127.0.0.1:{port}/health", headers=AUTH, timeout=1) + break + except requests.ConnectionError: + assert time.monotonic() < deadline + time.sleep(0.02) + assert json.loads(response.text)["read_only"] is read_only + finally: + stop.set() + thread.join(5) + assert not thread.is_alive() + assert TOKEN not in capsys.readouterr().out + + +def test_public_binding_warns_about_plain_http(tmp_path, monkeypatch, capsys): + store = JobStore(tmp_path / "j.sqlite3") + monkeypatch.setattr(server_module, "JobStore", lambda: store) + monkeypatch.setenv("HELM_SERVER_TOKEN", TOKEN) + stop = threading.Event() + stop.set() + run_server("0.0.0.0", 0, read_only=True, stop=stop) + assert "plain HTTP" in capsys.readouterr().err diff --git a/tests/test_service_boundaries.py b/tests/test_service_boundaries.py new file mode 100644 index 0000000..a1ba492 --- /dev/null +++ b/tests/test_service_boundaries.py @@ -0,0 +1,142 @@ +"""Setup, wizard and one-shot behaviour against a fake engine binary and real HTTP.""" + +import builtins +import stat +import threading +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path +from types import SimpleNamespace + +import pytest + +import helm.core.config_wizard as wizard +import helm.core.oneshot as oneshot +from helm.core.config_manager import get_state_dir, load_config, save_config +from helm.core.secret_manager import get_secret + + +def install_engine(tmp_path, monkeypatch, status): + """A fake docker CLI that records its arguments and reports one container state.""" + log = tmp_path / "engine.log" + binary = tmp_path / "docker" + binary.write_text( + "#!/bin/sh\n" + f'echo "$*" >> {log}\n' + 'case "$1 $2" in\n' + f" inspect*) echo {status} ;;\n" + ' compose*) case "$*" in *" ps -q "*) echo cid ;; esac ;;\n' + "esac\n" + ) + binary.chmod(binary.stat().st_mode | stat.S_IXUSR) + monkeypatch.setattr(oneshot, "DOCKER_CMD", str(binary)) + monkeypatch.setattr(oneshot.time, "sleep", lambda _: None) + return log + + +class Service(BaseHTTPRequestHandler): + def log_message(self, *args): + pass + + def do_GET(self): + self.send_response(200) + self.send_header("Content-Length", "5") + self.end_headers() + self.wfile.write(b"ready") + + do_POST = do_GET + + +@pytest.fixture +def service(): + server = ThreadingHTTPServer(("127.0.0.1", 0), Service) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + yield f"http://127.0.0.1:{server.server_port}" + server.shutdown() + server.server_close() + thread.join() + + +def test_teardown_stops_only_named_stack_services(tmp_path, monkeypatch): + log = install_engine(tmp_path, monkeypatch, "running") + monkeypatch.setenv("COMPOSE_PROJECT_NAME", "helm-test") + oneshot.teardown_oneshot() + lines = sorted(log.read_text().splitlines()) + assert lines == sorted("stop helm-test-" + service for service in oneshot.CONTAINER_SERVICES) + + +def test_startup_brings_up_stack_before_inspecting_it(tmp_path, monkeypatch, service): + log = install_engine(tmp_path, monkeypatch, "running") + monkeypatch.setenv("JACKETT_URL", service) + monkeypatch.setenv("FLARESOLVERR_URL", service) + oneshot.spin_up_oneshot() + lines = log.read_text().splitlines() + assert lines[0].startswith("compose") and " up -d " in lines[0] + for name in ("jackett", "prowlarr", "qbittorrent", "flaresolverr"): + assert name in lines[0] + assert sum(line.startswith("inspect") for line in lines) == 4 + + +def test_startup_uses_generated_compose_file(tmp_path, monkeypatch, service): + log = install_engine(tmp_path, monkeypatch, "running") + monkeypatch.setenv("JACKETT_URL", service) + monkeypatch.setenv("FLARESOLVERR_URL", service) + state = Path(get_state_dir()) + state.mkdir(parents=True, exist_ok=True) + compose = state / "docker-compose.yml" + compose.write_text("services: {}\n") + try: + oneshot.spin_up_oneshot() + assert f"-f {compose}" in log.read_text().splitlines()[0] + finally: + compose.unlink() + + +def test_crashed_container_stops_the_stack_and_exits(tmp_path, monkeypatch): + log = install_engine(tmp_path, monkeypatch, "exited") + with pytest.raises(SystemExit) as error: + oneshot.spin_up_oneshot() + assert error.value.code == 1 + stopped = [line for line in log.read_text().splitlines() if line.startswith("stop ")] + assert len(stopped) == len(oneshot.CONTAINER_SERVICES) + + +def answers(monkeypatch, values): + remaining = iter(values) + monkeypatch.setattr(builtins, "input", lambda prompt="": next(remaining)) + + +def test_wizard_lite_choice_is_saved(monkeypatch): + answers(monkeypatch, ["n"]) + wizard.run_wizard() + assert load_config()["LITE_MODE_ONLY"] is True + save_config({"LITE_MODE_ONLY": False}) + + +def test_wizard_without_a_terminal_exits_with_guidance(monkeypatch, capsys): + def closed(prompt=""): + raise EOFError + + monkeypatch.setattr(builtins, "input", closed) + with pytest.raises(SystemExit) as error: + wizard.run_wizard() + assert error.value.code == 1 + assert "-it" in capsys.readouterr().out + + +def test_ensure_config_runs_wizard_only_when_settings_are_missing(monkeypatch): + calls = [] + monkeypatch.setattr(wizard, "run_wizard", lambda: calls.append(1)) + for key in ("JACKETT_URL", "QB_WEBUI", "QB_USERNAME", "JACKETT_API_KEY", "QB_PASSWORD"): + monkeypatch.delenv(key, raising=False) + save_config({"LITE_MODE_ONLY": False}) + wizard.ensure_config() # Not a terminal: warn instead of blocking on a prompt. + assert calls == [] + monkeypatch.setattr(wizard.sys, "stdin", SimpleNamespace(isatty=lambda: True)) + wizard.ensure_config() + assert calls == [1] + save_config({"LITE_MODE_ONLY": True}) + wizard.ensure_config() + assert calls == [1] + save_config({"LITE_MODE_ONLY": False}) + assert get_secret("QB_PASSWORD") is None diff --git a/tests/test_stack_benchmark.py b/tests/test_stack_benchmark.py new file mode 100644 index 0000000..a545877 --- /dev/null +++ b/tests/test_stack_benchmark.py @@ -0,0 +1,232 @@ +"""Everything in the stack exercise that does not need a container engine.""" + +import hashlib +import json +import socket +import threading +import time +from http.server import ThreadingHTTPServer +from pathlib import Path + +import pytest +import requests +import responses + +import helm.core.stack_benchmark as stack_benchmark +from helm.core.stack_benchmark import ( + DEFAULT_IMAGES, + Stack, + cgroup_path, + fixture_handler, + load_images, + read_cgroup, + scrub_logs, + verify_limits, +) +from helm.core.torrent_links import metadata_source + + +def test_default_images_cover_every_service(): + assert set(DEFAULT_IMAGES) == set(stack_benchmark.PORTS) + + +def test_load_images_applies_manifest_then_overrides(tmp_path): + manifest = tmp_path / "images.json" + manifest.write_text(json.dumps({"jackett": "manifest:1", "prowlarr": "manifest:2"})) + images = load_images(manifest, ["prowlarr=override:3"]) + assert images["jackett"] == "manifest:1" + assert images["prowlarr"] == "override:3" + assert images["qbittorrent"] == DEFAULT_IMAGES["qbittorrent"] + + +@pytest.mark.parametrize("overrides", [["jackett"], ["jackett="], ["unknown=x"]]) +def test_invalid_image_overrides(overrides): + with pytest.raises(ValueError): + load_images(None, overrides) + + +def test_scrub_logs_removes_run_keys_and_temporary_password(): + text = ( + "The WebUI administrator username is: admin\n" + "A temporary password is provided for this session: aBc123XyZ\n" + "key abcdef0123456789 started" + ) + scrubbed = scrub_logs(text, ["abcdef0123456789"]) + assert "aBc123XyZ" not in scrubbed + assert "abcdef0123456789" not in scrubbed + assert "administrator username" in scrubbed + + +def write_cgroup(path, memory_max="268435456", cpu_max="50000 100000"): + path.mkdir(exist_ok=True) + (path / "memory.max").write_text(memory_max + "\n") + (path / "cpu.max").write_text(cpu_max + "\n") + (path / "memory.current").write_text("1024\n") + (path / "cpu.stat").write_text("usage_usec 77\nuser_usec 7\n") + return path + + +def test_verify_limits_accepts_effective_limits(tmp_path): + result = verify_limits(write_cgroup(tmp_path), 256 * 1024**2) + assert result == {"memory_max": "268435456", "cpu_max": "50000 100000", "verified": True} + + +@pytest.mark.parametrize( + "memory_max,cpu_max", + [("max", "50000 100000"), ("1", "50000 100000"), ("268435456", "max 100000"), ("268435456", "100000 100000")], +) +def test_verify_limits_detects_unenforced_limits(tmp_path, memory_max, cpu_max): + assert verify_limits(write_cgroup(tmp_path, memory_max, cpu_max), 256 * 1024**2)["verified"] is False + + +def test_read_cgroup(tmp_path): + assert read_cgroup(write_cgroup(tmp_path)) == {"memory_current_bytes": 1024, "cpu_usage_usec": 77} + + +def test_cgroup_path_of_current_process(): + assert Path("/sys/fs/cgroup") in [*cgroup_path("self").parents, cgroup_path("self")] + + +def test_peer_addresses_prefer_network_gateway_and_deduplicate(): + routes = "default via 172.28.0.1 dev eth0\n" + hosts = "172.17.0.1 host.docker.internal\n172.28.0.1 host.docker.internal\n" + assert stack_benchmark.peer_addresses(routes, hosts) == ["172.28.0.1", "172.17.0.1"] + assert stack_benchmark.peer_addresses("", "") == [] + + +def test_seeder_is_reachable_on_every_interface_at_the_reported_port(tmp_path): + pytest.importorskip("libtorrent") + session, data, checksum = stack_benchmark.seed_payload(tmp_path / "seed", 1024) + try: + address = socket.gethostbyname(socket.gethostname()) + deadline = time.monotonic() + 5 + while True: + try: + socket.create_connection(("127.0.0.1", session.listen_port()), timeout=1).close() + socket.create_connection((address, session.listen_port()), timeout=1).close() + break + except OSError: + assert time.monotonic() < deadline + time.sleep(0.05) + finally: + session.pause() + assert hashlib.sha256((tmp_path / "seed" / "generated-payload.bin").read_bytes()).hexdigest() == checksum + assert metadata_source(data).magnet + + +def test_fixture_page_escapes_query_and_links_magnet(): + server = ThreadingHTTPServer(("127.0.0.1", 0), fixture_handler({"magnet": "magnet:?a=1&b=2", "size": 5})) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + try: + response = requests.get(f"http://127.0.0.1:{server.server_port}/search", params={"q": ""}) + finally: + server.shutdown() + server.server_close() + thread.join() + assert "<b> Linux ISO" in response.text + assert "magnet:?a=1&b=2" in response.text + + +def make_stack(tmp_path, monkeypatch, fail_on=()): + calls = [] + + def fake_command(engine, *arguments, timeout=120): + calls.append(arguments) + if arguments[0] in fail_on: + raise RuntimeError("engine refused token-free") + return "" + + monkeypatch.setattr(stack_benchmark, "command", fake_command) + return Stack("docker", tmp_path, 1234), calls + + +def test_prepare_writes_isolated_configuration(tmp_path, monkeypatch): + stack, _ = make_stack(tmp_path, monkeypatch) + stack.prepare() + assert stack.project.startswith("helm-bench-") + assert json.loads((tmp_path / "jackett/Jackett/ServerConfig.json").read_text())["APIKey"] == stack.keys["jackett"] + assert "host.docker.internal:1234" in (tmp_path / "jackett/cardigann/definitions/helmbenchmark.yml").read_text() + assert stack.keys["prowlarr"] in (tmp_path / "prowlarr/config.xml").read_text() + assert "DHTEnabled=false" in (tmp_path / "qbittorrent/qBittorrent/qBittorrent.conf").read_text() + + +def test_cleanup_only_touches_owned_resources(tmp_path, monkeypatch): + stack, calls = make_stack(tmp_path, monkeypatch) + assert stack.cleanup() == [] + assert calls == [] + stack.ids = {"jackett": "id1"} + stack.network_created = True + assert stack.cleanup() == [] + assert calls == [("rm", "-f", "id1"), ("network", "rm", stack.project)] + + +def test_cleanup_reports_each_failure(tmp_path, monkeypatch): + stack, _ = make_stack(tmp_path, monkeypatch, fail_on=("rm", "network")) + stack.ids = {"jackett": "id1"} + stack.network_created = True + assert len(stack.cleanup()) == 2 + + +@responses.activate +def test_configure_indexers_gets_jackett_session_before_config(tmp_path, monkeypatch): + stack, _ = make_stack(tmp_path, monkeypatch) + stack.urls = {"jackett": "http://jackett.test", "prowlarr": "http://prowlarr.test"} + config = "http://jackett.test/api/v2.0/indexers/helmbenchmark/config" + responses.add(responses.GET, "http://jackett.test/UI/Dashboard", status=200, headers={"Set-Cookie": "Jackett=1"}) + responses.add(responses.GET, config, json=[{"id": "sitelink"}]) + responses.add(responses.POST, config, status=204) + responses.add( + responses.GET, + "http://prowlarr.test/api/v1/indexer/schema", + json=[ + {"implementation": "Other", "fields": []}, + { + "implementation": "Torznab", + "fields": [{"name": "baseUrl"}, {"name": "apiPath"}, {"name": "apiKey"}, {"name": "unrelated"}], + }, + ], + ) + responses.add(responses.POST, "http://prowlarr.test/api/v1/indexer", status=201) + + stack.configure_indexers() + + assert responses.calls[0].request.url.endswith("/UI/Dashboard") + assert responses.calls[1].request.url == config + posted = json.loads(responses.calls[-1].request.body) + values = {field["name"]: field.get("value") for field in posted["fields"]} + assert values["baseUrl"] == f"http://{stack.project}-jackett:9117" + assert values["apiKey"] == stack.keys["jackett"] + assert responses.calls[-1].request.headers["X-Api-Key"] == stack.keys["prowlarr"] + + +def test_failed_engine_run_is_reported_as_failure_and_cleaned(monkeypatch): + def refuse(engine, *arguments, timeout=120): + raise RuntimeError("engine unavailable") + + monkeypatch.setattr(stack_benchmark, "command", refuse) + report = stack_benchmark.run_engine("docker", repeats=1) + assert report["success"] is False + assert report["errors"] and report["trials"] == [] + assert report["cleanup_errors"] == [] + + +def test_main_exit_code_and_output(tmp_path, monkeypatch, capsys): + seen = {} + + def fake_run(engine, repeats, images, payload): + seen.update(engine=engine, images=images) + return {"success": False, "errors": ["x"], "cleanup_errors": []} + + monkeypatch.setattr(stack_benchmark, "run_engine", fake_run) + output = tmp_path / "out" / "stack.json" + code = stack_benchmark.main(["--engine", "podman", "--output", str(output), "--image", "jackett=x:1"]) + assert code == 1 + assert json.loads(output.read_text())["success"] is False + assert seen["images"]["jackett"] == "x:1" + + +@pytest.mark.parametrize("arguments", [["--repeats", "0"], ["--image", "bad"]]) +def test_main_rejects_invalid_arguments(tmp_path, arguments): + with pytest.raises(SystemExit): + stack_benchmark.main(["--engine", "docker", "--output", str(tmp_path / "s.json"), *arguments]) diff --git a/tests/test_torrent_links.py b/tests/test_torrent_links.py new file mode 100644 index 0000000..ee0d3b8 --- /dev/null +++ b/tests/test_torrent_links.py @@ -0,0 +1,257 @@ +"""Link resolution, exercised through a real local HTTP server.""" + +import hashlib +import threading +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +import pytest + +from helm.core import torrent_links +from helm.core.torrent_links import ( + TorrentSource, + decode_metadata, + info_hash, + metadata_source, + resolve_torrent, + valid_files, + validate_magnet, +) + +HASH = "a" * 40 +MAGNET = "magnet:?xt=urn:btih:" + HASH +INFO = b"d6:lengthi5e4:name4:file12:piece lengthi16384e6:pieces20:" + b"p" * 20 + b"e" +TORRENT = b"d8:announce14:http://t.local4:info" + INFO + b"e" + + +class Routes(BaseHTTPRequestHandler): + routes: dict = {} + + def log_message(self, *args): + pass + + def do_GET(self): + status, headers, body = self.routes[self.path] + self.send_response(status) + for key, value in headers.items(): + self.send_header(key, value) + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + +@pytest.fixture +def site(): + server = ThreadingHTTPServer(("127.0.0.1", 0), Routes) + Routes.routes = {} + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + yield "http://127.0.0.1:%d" % server.server_port + server.shutdown() + server.server_close() + thread.join() + + +@pytest.mark.parametrize( + "value", + [MAGNET, "magnet:?xt=urn:btih:" + "A" * 32, "magnet:?xt=urn:btmh:1220" + "b" * 64], +) +def test_validate_magnet_accepts_supported_hashes(value): + assert validate_magnet(value) == value + + +@pytest.mark.parametrize( + "value", + ["http://x", "magnet:?dn=x", "magnet:?xt=urn:btih:12345", "magnet:?xt=urn:btih:" + "a" * 70000], +) +def test_validate_magnet_rejects_invalid(value): + with pytest.raises(ValueError): + validate_magnet(value) + + +def test_metadata_hash_uses_exact_info_bytes(): + source = metadata_source(TORRENT) + assert hashlib.sha1(INFO).hexdigest() in source.magnet + assert "dn=file&" in source.magnet + assert "tr=http%3A%2F%2Ft.local" in source.magnet + assert source.data == TORRENT + + +def test_v2_and_hybrid_metadata_produce_their_topics(): + v2 = b"4:name1:x12:meta versioni2e12:piece lengthi16384e" + source = metadata_source(b"d4:infod" + v2 + b"ee") + assert "urn:btmh:1220" in source.magnet and "urn:btih:" not in source.magnet + hybrid = metadata_source( + b"d4:infod6:lengthi1e4:name1:x12:meta versioni2e12:piece lengthi16384e6:pieces20:" + b"p" * 20 + b"ee" + ) + assert "urn:btmh:1220" in hybrid.magnet and "urn:btih:" in hybrid.magnet + + +def test_trackers_are_deduplicated_across_announce_list(): + data = b"d8:announce3:u:113:announce-listll3:u:1el3:u:2ee4:info" + INFO + b"e" + assert metadata_source(data).magnet.count("tr=") == 2 + + +@pytest.mark.parametrize( + "data", + [ + b"", + b"x", + b"i1e", + b"d4:infoi1ee", + b"d4:infod", + TORRENT + b"junk", + b"l" * 100, + b"di01e1:xe", + b"d1:ai-0ee", + b"d01:ai1ee", + b"d1:ai1e1:ai2ee", + b"d999:xe", + b"d4:infod4:name1:x12:piece lengthi0e6:pieces20:" + b"p" * 20 + b"ee", + b"d4:infod4:name1:x12:piece lengthi1eee", + b"d4:infod6:lengthi1e4:name1:x12:piece lengthi1e6:pieces3:abcee", + b"d4:infod4:name1:x12:piece lengthi1e6:pieces20:" + b"p" * 20 + b"ee", + b"d4:infod6:lengthi-1e4:name1:x12:piece lengthi1e6:pieces20:" + b"p" * 20 + b"ee", + b"d4:infod5:filesl" + + b"d6:lengthi1e4:pathl2:..ee" + + b"e4:name1:x12:piece lengthi1e6:pieces20:" + + b"p" * 20 + + b"ee", + ], +) +def test_malformed_metadata_is_rejected(data): + with pytest.raises(ValueError): + decode_metadata(data) + + +def test_oversized_metadata_is_rejected(): + with pytest.raises(ValueError, match="8 MiB"): + decode_metadata(b"d" * (torrent_links.MAX_METADATA + 1)) + + +@pytest.mark.parametrize( + "files,expected", + [ + ([{b"length": 1, b"path": [b"a", b"b"]}], True), + ([], False), + (None, False), + (["x"], False), + ([{b"length": -1, b"path": [b"a"]}], False), + ([{b"length": 1, b"path": []}], False), + ([{b"length": 1, b"path": [b"a/b"]}], False), + ([{b"length": 1, b"path": [b""]}], False), + ], +) +def test_valid_files(files, expected): + assert valid_files(files) is expected + + +def test_info_hash_forms(): + assert info_hash(MAGNET) == HASH + assert info_hash("magnet:?xt=urn:btih:" + "A" * 32) == "00" * 20 + assert info_hash("magnet:?xt=urn:btmh:1220" + "B" * 64) == "b" * 64 + with pytest.raises(ValueError): + info_hash("magnet:?dn=x") + + +def test_resolve_passes_through_sources_and_magnets(): + source = TorrentSource(MAGNET) + assert resolve_torrent(source) is source + assert resolve_torrent(" " + MAGNET + " ").magnet == MAGNET + + +def test_resolve_local_torrent(tmp_path): + path = tmp_path / "a.torrent" + path.write_bytes(TORRENT) + assert resolve_torrent(str(path)).data == TORRENT + with pytest.raises(ValueError, match="existing"): + resolve_torrent(str(tmp_path / "missing.torrent")) + with pytest.raises(ValueError): + resolve_torrent(str(path), allow_local=False) + + +@pytest.mark.parametrize("value", ["file:///etc/passwd", "ftp://example.test/x.torrent"]) +def test_unsupported_schemes_are_rejected(value): + with pytest.raises(ValueError, match="supported"): + resolve_torrent(value) + + +def test_direct_torrent_download(site): + Routes.routes["/a.torrent"] = (200, {"Content-Type": "application/x-bittorrent"}, TORRENT) + assert resolve_torrent(site + "/a.torrent").data == TORRENT + + +def test_detail_page_prefers_magnet(site): + Routes.routes["/d"] = (200, {}, f'tm'.encode()) + assert resolve_torrent(site + "/d").magnet == MAGNET + + +def test_detail_page_follows_relative_torrent_anchor(site): + Routes.routes["/x/d"] = (200, {}, b'nt') + Routes.routes["/x/a.TORRENT?k=1"] = (200, {}, TORRENT) + assert resolve_torrent(site + "/x/d").data == TORRENT + + +def test_redirect_to_magnet_and_to_relative_location(site): + Routes.routes["/m"] = (302, {"Location": MAGNET}, b"") + assert resolve_torrent(site + "/m").magnet == MAGNET + Routes.routes["/r"] = (301, {"Location": "/a.torrent"}, b"") + Routes.routes["/a.torrent"] = (200, {}, TORRENT) + assert resolve_torrent(site + "/r").data == TORRENT + + +def test_redirect_failures(site): + Routes.routes["/a"] = (302, {"Location": "/b"}, b"") + Routes.routes["/b"] = (302, {"Location": "/a"}, b"") + with pytest.raises(ValueError, match="loop"): + resolve_torrent(site + "/a") + Routes.routes["/none"] = (302, {}, b"") + with pytest.raises(ValueError, match="Location"): + resolve_torrent(site + "/none") + Routes.routes["/file"] = (302, {"Location": "file:///etc/passwd"}, b"") + with pytest.raises(ValueError, match="supported"): + resolve_torrent(site + "/file") + + +def test_hop_limit(site): + for index in range(8): + Routes.routes[f"/{index}"] = (302, {"Location": f"/{index + 1}"}, b"") + with pytest.raises(ValueError, match="limit"): + resolve_torrent(site + "/0") + + +def test_http_error_is_raised(site): + Routes.routes["/gone"] = (404, {}, b"") + with pytest.raises(Exception, match="404"): + resolve_torrent(site + "/gone") + + +def test_page_without_links_is_rejected(site): + Routes.routes["/empty"] = (200, {}, b"nothing") + with pytest.raises(ValueError, match="no magnet"): + resolve_torrent(site + "/empty") + + +def test_invalid_declared_charset_does_not_crash(site): + Routes.routes["/d"] = ( + 200, + {"Content-Type": "text/html; charset=not-a-charset"}, + f'm'.encode(), + ) + assert resolve_torrent(site + "/d").magnet == MAGNET + + +def test_text_page_starting_with_d_still_parses_as_html(site): + Routes.routes["/d"] = (200, {}, f'download here m'.encode()) + assert resolve_torrent(site + "/d").magnet == MAGNET + + +def test_response_size_limit(site, monkeypatch): + monkeypatch.setattr(torrent_links, "MAX_METADATA", 1024) + Routes.routes["/big"] = (200, {}, b"x" * 200000) + with pytest.raises(ValueError, match="exceeds"): + resolve_torrent(site + "/big") + + +def test_exhausted_deadline(site): + with pytest.raises(TimeoutError): + resolve_torrent(site + "/any", timeout=0) diff --git a/tests/test_uninstall.py b/tests/test_uninstall.py new file mode 100644 index 0000000..e734147 --- /dev/null +++ b/tests/test_uninstall.py @@ -0,0 +1,245 @@ +"""Exercise the standalone raw-GitHub script using disposable data and engines.""" + +import os +import subprocess +import sys +from pathlib import Path + +import pytest + +SCRIPT = Path(__file__).resolve().parents[1] / "uninstall.sh" + + +def run_script(tmp_path, *arguments, stdin=False, env=None): + environment = os.environ.copy() + environment.update(env or {}) + return subprocess.run( + ["bash", "-s", "--", *arguments] if stdin else ["bash", str(SCRIPT), *arguments], + input=SCRIPT.read_text() if stdin else None, + cwd=tmp_path, + env=environment, + capture_output=True, + text=True, + ) + + +def make_config(tmp_path): + config = tmp_path / "shared config" + config.mkdir() + for name in ("config.json", "secrets.env", "repositories.yaml", "registry.json"): + (config / name).write_text("keep private") + (config / "plugins").mkdir() + return config + + +@pytest.mark.parametrize("arguments", [[], ["--config", "--dry-run"], ["--config", "--yes", "--dry-run"]]) +def test_preview_does_not_delete_config(tmp_path, arguments): + config = make_config(tmp_path) + result = run_script(tmp_path, *arguments, "--config-dir", str(config)) + assert result.returncode == (1 if not arguments else 0), result.stderr + assert (config / "config.json").exists() + assert (config / "secrets.env").exists() + + +def test_raw_stdin_script_preserves_kubernetes_and_plugins(tmp_path): + config = make_config(tmp_path) + result = run_script(tmp_path, "--config", "--config-dir", str(config), "--yes", stdin=True) + assert result.returncode == 0, result.stderr + assert not (config / "config.json").exists() + assert not (config / "secrets.env").exists() + assert (config / "repositories.yaml").exists() + assert (config / "registry.json").exists() + assert (config / "plugins").is_dir() + + +def test_state_cleanup_preserves_downloads_and_unrelated_files(tmp_path): + state = tmp_path / "state" + state.mkdir() + (state / "jackett").mkdir() + (state / "jackett" / "data").write_text("service state") + (state / "helm.log.1").write_text("log") + (state / ".env.docker").write_text("secrets") + (state / "other.txt").write_text("unrelated") + downloads = tmp_path / "downloads" + downloads.mkdir() + (downloads / "keep.iso").write_text("download") + result = run_script(tmp_path, "--state", "--state-dir", str(state), "--downloads-dir", str(downloads), "--yes") + assert result.returncode == 0, result.stderr + assert not (state / "jackett").exists() + assert not (state / "helm.log.1").exists() + assert not (state / ".env.docker").exists() + assert (state / "other.txt").exists() + assert (downloads / "keep.iso").exists() + + +@pytest.mark.parametrize("root", ["/", "."]) +def test_rejects_unsafe_root_before_removal(tmp_path, root): + result = run_script(tmp_path, "--state", "--state-dir", root, "--yes") + assert result.returncode == 1 + assert "unsafe removal path" in result.stderr + + +def test_rejects_download_overlap_before_removal(tmp_path): + state = tmp_path / "state" + downloads = state / "qbittorrent" / "downloads" + downloads.mkdir(parents=True) + (downloads / "keep.iso").write_text("download") + result = run_script(tmp_path, "--state", "--state-dir", str(state), "--downloads-dir", str(downloads), "--yes") + assert result.returncode == 1 + assert (downloads / "keep.iso").exists() + + +def test_symlink_artifact_is_unlinked_without_deleting_target(tmp_path): + state = tmp_path / "state" + state.mkdir() + target = tmp_path / "untouched" + target.mkdir() + (target / "keep.txt").write_text("keep") + (state / "jackett").symlink_to(target, target_is_directory=True) + result = run_script(tmp_path, "--state", "--state-dir", str(state), "--yes") + assert result.returncode == 0, result.stderr + assert not (state / "jackett").is_symlink() + assert (target / "keep.txt").exists() + + +def test_symlink_root_is_rejected(tmp_path): + target = tmp_path / "target" + target.mkdir() + link = tmp_path / "link" + link.symlink_to(target, target_is_directory=True) + result = run_script(tmp_path, "--state", "--state-dir", str(link), "--yes") + assert result.returncode == 1 + assert "must not be a symlink" in result.stderr + + +def fake_engine(tmp_path, engine): + tools = tmp_path / "bin" + tools.mkdir() + executable = tools / engine + executable.write_text("""#!/usr/bin/env bash +printf '%s\\n' "$*" >> "$ENGINE_LOG" +case "$1 $2" in + 'ps -aq') echo container-123 ;; + 'network ls') echo network-123 ;; + 'volume ls') echo volume-123 ;; +esac +""") + executable.chmod(0o755) + log = tmp_path / "engine.log" + return {"PATH": f"{tools}{os.pathsep}{os.environ['PATH']}", "ENGINE_LOG": str(log)}, log + + +@pytest.mark.parametrize("engine", ["docker", "podman"]) +@pytest.mark.parametrize("apply", [False, True]) +def test_removes_only_selected_project_resources(tmp_path, engine, apply): + environment, log = fake_engine(tmp_path, engine) + arguments = ["--containers", "--volumes", "--engine", engine, "--project", "helm-test"] + if apply: + arguments.append("--yes") + result = run_script(tmp_path, *arguments, env=environment) + assert result.returncode == 0, result.stderr + calls = log.read_text().splitlines() + assert calls[:3] == [ + "ps -aq --filter label=com.docker.compose.project=helm-test", + "network ls -q --filter label=com.docker.compose.project=helm-test", + "volume ls -q --filter label=com.docker.compose.project=helm-test", + ] + assert calls[3:] == ( + ["container rm -f container-123", "network rm network-123", "volume rm volume-123"] if apply else [] + ) + + +def test_volumes_are_never_selected_implicitly(tmp_path): + environment, log = fake_engine(tmp_path, "docker") + result = run_script(tmp_path, "--containers", "--engine", "docker", "--yes", env=environment) + assert result.returncode == 0, result.stderr + assert "volume" not in log.read_text() + + +def test_engine_failure_stops_before_deleting_state(tmp_path): + environment, log = fake_engine(tmp_path, "docker") + engine = tmp_path / "bin" / "docker" + engine.write_text("#!/usr/bin/env bash\nexit 1\n") + state = tmp_path / "state" + state.mkdir() + (state / ".env.docker").write_text("preserve") + result = run_script( + tmp_path, "--containers", "--engine", "docker", "--state", "--state-dir", str(state), "--yes", env=environment + ) + assert result.returncode != 0 + assert (state / ".env.docker").exists() + + +def test_package_removal_targets_only_torrent_distribution(tmp_path): + fake_python = tmp_path / "python" + log = tmp_path / "pip.log" + fake_python.write_text('#!/usr/bin/env bash\nprintf "%s\\n" "$*" > "$PIP_LOG"\n') + fake_python.chmod(0o755) + result = run_script(tmp_path, "--package", "--yes", env={"HELM_PYTHON": str(fake_python), "PIP_LOG": str(log)}) + assert result.returncode == 0, result.stderr + assert log.read_text().strip() == "-m pip uninstall -y helm-torrent" + + +@pytest.mark.parametrize( + "arguments", + [ + ["--volumes"], + ["--config-dir"], + ["--config", "--engine", "bad"], + ["--config", "--project", "../bad"], + ["--unknown"], + ], +) +def test_invalid_arguments_do_not_remove_anything(tmp_path, arguments): + result = run_script(tmp_path, *arguments) + assert result.returncode == 1 + assert "Error:" in result.stderr + + +def test_help_runs_from_raw_stdin_without_python_or_checkout(tmp_path): + result = run_script(tmp_path, "--help", stdin=True, env={"HELM_PYTHON": "/not/installed"}) + assert result.returncode == 0, result.stderr + assert "Preview by default" in result.stdout + + +def test_command_metadata_and_help_agree_on_new_name(): + import configparser + + root = SCRIPT.parent + project = (root / "pyproject.toml").read_text() + scripts = project.split("[project.scripts]\n", 1)[1].split("\n[", 1)[0] + parser = configparser.ConfigParser() + parser.read_string("[scripts]\n" + scripts) + assert dict(parser["scripts"]) == {"helm-torrent": '"helm.cli:main"'} + # The CLI help is tied to the same exported name, even under python -m. + environment = os.environ.copy() + environment["PYTHONPATH"] = str(root / "src") + result = subprocess.run( + [sys.executable, "-m", "helm.cli", "--help"], env=environment, capture_output=True, text=True + ) + assert result.returncode == 0 + assert "usage: helm-torrent" in result.stdout + + +def test_local_handout_documents_command_and_uninstall(): + handout_path = SCRIPT.parent / "personal_notes" / "handout.md" + if not handout_path.exists(): + pytest.skip("personal_notes is intentionally private and ignored") + handout = handout_path.read_text() + assert "`helm-torrent`" in handout + assert "uninstall.sh" in handout + assert "--dry-run" in handout + + +def test_local_agent_handoff_records_pending_work(): + path = SCRIPT.parent / "personal_notes" / "hadnout.md" + if not path.exists(): + pytest.skip("personal_notes is intentionally private and ignored") + contents = path.read_text() + for marker in ( + "## Last known verification state", + "3 failures, 31 passes", + "## Recommended continuation order", + "### Temporary access cleanup promise", + ): + assert marker in contents diff --git a/tests/test_watch.py b/tests/test_watch.py new file mode 100644 index 0000000..e91485c --- /dev/null +++ b/tests/test_watch.py @@ -0,0 +1,162 @@ +import errno +import threading +import time + +import pytest + +import helm.core.watch as watch +from helm.core.jobs import JobStore +from helm.core.watch import run_watch, safe_scan, scan_directory + +MAGNET = "magnet:?xt=urn:btih:" + "a" * 40 +OTHER = "magnet:?xt=urn:btih:" + "b" * 40 +TORRENT = b"d4:infod6:lengthi5e4:name4:file12:piece lengthi16384e6:pieces20:" + b"p" * 20 + b"ee" + + +@pytest.fixture +def store(tmp_path): + return JobStore(tmp_path / "state" / "jobs.sqlite3") + + +@pytest.fixture +def inbox(tmp_path): + path = tmp_path / "inbox" + path.mkdir() + return path + + +def settle_scan(inbox, store, lite=False): + return scan_directory(inbox, store, scan_directory(inbox, store, {}, lite, settle=1, now=0), lite, settle=1, now=2) + + +def test_file_is_not_ingested_until_stable(inbox, store): + path = inbox / "a.magnet" + path.write_text(MAGNET) + observed = scan_directory(inbox, store, {}, settle=1, now=0) + assert store.list() == [] and path.exists() + path.write_text(MAGNET + "\n") # Still being written. + observed = scan_directory(inbox, store, observed, settle=1, now=2) + assert store.list() == [] and path.exists() + scan_directory(inbox, store, observed, settle=1, now=4) + assert len(store.list()) == 1 and not path.exists() + + +def test_valid_text_file_moves_to_processed(inbox, store): + (inbox / "a.txt").write_text(f"# comment\n\n{MAGNET}\n {OTHER} \n") + assert settle_scan(inbox, store) == {} + assert len(store.list()) == 2 + assert len(list((inbox / ".processed").iterdir())) == 1 + + +def test_torrent_file_survives_being_moved(inbox, store): + (inbox / "a.torrent").write_bytes(TORRENT) + settle_scan(inbox, store, lite=True) + job = store.list()[0] + assert job["lite"] == 1 + assert ".processed" not in job["source"] + assert open(job["source"], "rb").read() == TORRENT + + +def test_one_bad_line_queues_nothing(inbox, store): + (inbox / "a.txt").write_text(f"{MAGNET}\nmagnet:?xt=urn:btih:12345\n") + settle_scan(inbox, store) + assert store.list() == [] + failed = list((inbox / ".failed").iterdir()) + assert len(failed) == 2 + assert any(path.name.endswith(".error.txt") for path in failed) + + +@pytest.mark.parametrize( + "name,content", + [("a.txt", b"# only a comment\n"), ("a.txt", b"ftp://x/y\n"), ("a.txt", b"\xff\xfe\x00"), ("a.torrent", b"junk")], +) +def test_invalid_inputs_are_quarantined(inbox, store, name, content): + (inbox / name).write_bytes(content) + settle_scan(inbox, store) + assert store.list() == [] + assert not (inbox / name).exists() + assert list((inbox / ".failed").iterdir()) + + +def test_oversized_input_is_quarantined(inbox, store, monkeypatch): + monkeypatch.setattr(watch, "MAX_METADATA", 4) + (inbox / "a.txt").write_text(MAGNET) + settle_scan(inbox, store) + assert store.list() == [] + + +def test_unrelated_files_and_symlinks_are_ignored(inbox, store, tmp_path): + (inbox / "notes.md").write_text(MAGNET) + target = tmp_path / "target.magnet" + target.write_text(MAGNET) + (inbox / "link.magnet").symlink_to(target) + (inbox / "dir.txt").mkdir() + assert settle_scan(inbox, store) == {} + assert store.list() == [] + assert (inbox / "notes.md").exists() and target.exists() + + +def test_symlinked_processed_directory_is_refused(inbox, store, tmp_path): + outside = tmp_path / "outside" + outside.mkdir() + (inbox / ".processed").symlink_to(outside) + (inbox / "a.magnet").write_text(MAGNET) + settle_scan(inbox, store) + assert list(outside.iterdir()) == [] + + +def test_file_vanishing_during_scan_is_skipped(inbox, store, monkeypatch): + real = watch.Path.stat + + def vanishing(self, *args, **kwargs): + if self.name == "gone.magnet": + raise FileNotFoundError(errno.ENOENT, "vanished", str(self)) + return real(self, *args, **kwargs) + + (inbox / "gone.magnet").write_text(MAGNET) + monkeypatch.setattr(watch.Path, "stat", vanishing) + assert scan_directory(inbox, store, {}, settle=0, now=0) == {} + + +def test_safe_scan_keeps_state_when_directory_is_unavailable(tmp_path, store): + observed = {"x": 1} + assert safe_scan(tmp_path / "missing", store, observed, False, 1) is observed + + +def test_run_watch_once_enqueue_only(tmp_path, inbox, monkeypatch): + store = JobStore(tmp_path / "state" / "jobs.sqlite3") + monkeypatch.setattr(watch, "JobStore", lambda: store) + (inbox / "a.magnet").write_text(MAGNET) + assert run_watch(inbox, lite=True, interval=0.05, once=True, enqueue_only=True) == 0 + assert [job["status"] for job in store.list()] == ["pending"] + + +def test_run_watch_once_processes_queue(tmp_path, inbox, monkeypatch): + store = JobStore(tmp_path / "state" / "jobs.sqlite3") + monkeypatch.setattr(watch, "JobStore", lambda: store) + processed = iter([True, False]) + monkeypatch.setattr(watch, "process_one", lambda *a: next(processed)) + assert run_watch(inbox, interval=0.01, once=True) == 0 + assert next(processed, "done") == "done" + + +def test_run_watch_loop_stops_and_joins_worker(tmp_path, inbox, monkeypatch): + store = JobStore(tmp_path / "state" / "jobs.sqlite3") + monkeypatch.setattr(watch, "JobStore", lambda: store) + monkeypatch.setattr(watch, "queue_loop", lambda store, stop: stop.wait()) + stop = threading.Event() + (inbox / "a.magnet").write_text(MAGNET) + thread = threading.Thread(target=run_watch, args=(inbox,), kwargs={"interval": 0.02, "stop": stop}) + thread.start() + deadline = time.monotonic() + 5 + while not store.list() and time.monotonic() < deadline: + time.sleep(0.01) + stop.set() + thread.join(5) + assert not thread.is_alive() + assert len(store.list()) == 1 + + +def test_interval_must_be_positive(inbox): + with pytest.raises(ValueError): + run_watch(inbox, interval=0) diff --git a/uninstall.sh b/uninstall.sh new file mode 100755 index 0000000..fc2dca5 --- /dev/null +++ b/uninstall.sh @@ -0,0 +1,179 @@ +#!/usr/bin/env bash +# Standalone: bash <(curl -fsSL https://raw.githubusercontent.com/Piratebird/helm/main/uninstall.sh) --help +set -euo pipefail + +usage() { + cat <<'HELP' +Usage: uninstall.sh [OPTIONS] +Preview by default. Select components and pass --yes to remove them. + --containers Remove this Compose project's containers and networks + --volumes Also delete labeled named volumes and ALL their contents + --config Remove config.json and secrets.env; preserve other files + --state Remove known service data, generated Compose files and logs + --package Uninstall helm-torrent using HELM_PYTHON (default: python3) + --engine docker|podman Container engine (otherwise detected) + --project NAME Compose project (default: COMPOSE_PROJECT_NAME or helm) + --config-dir PATH Override Helm torrent configuration directory + --state-dir PATH Override Helm torrent service data directory + --downloads-dir PATH Protect a custom host download directory from deletion + --yes Apply the removal plan + --dry-run Always preview, even with --yes + --help Show this help +Host downloads, user plugins, source files, images and system services are preserved. +Disable any helm-app.service separately before removing a managed stack. +Kubernetes Helm is never invoked or uninstalled. +HELP +} + +die() { echo "Error: $*" >&2; exit 1; } +need_value() { [[ $# -ge 2 && -n "$2" && "$2" != --* ]] || die "$1 requires a value"; } + +case "$(uname -s)" in + Darwin*) + config_dir="${HELM_CONFIG_DIR:-$HOME/Library/Application Support/helm}" + state_dir="${HELM_STATE_DIR:-$HOME/Library/Application Support/helm/state}" + ;; + MINGW*|CYGWIN*|MSYS*) + config_dir="${HELM_CONFIG_DIR:-${APPDATA:-$HOME/AppData/Roaming}/helm}" + state_dir="${HELM_STATE_DIR:-${LOCALAPPDATA:-$HOME/AppData/Local}/helm}" + ;; + *) + config_dir="${HELM_CONFIG_DIR:-${XDG_CONFIG_HOME:-$HOME/.config}/helm}" + state_dir="${HELM_STATE_DIR:-${XDG_STATE_HOME:-$HOME/.local/state}/helm}" + ;; +esac +downloads_dir="${HELM_DL_DIR:-$HOME/Downloads/helm}" +engine="" +project="${COMPOSE_PROJECT_NAME:-helm}" +remove_containers=false +remove_volumes=false +remove_config=false +remove_state=false +remove_package=false +apply=false +dry_run=false +while [[ $# -gt 0 ]]; do + case "$1" in + --containers) remove_containers=true; shift ;; + --volumes) remove_volumes=true; shift ;; + --config) remove_config=true; shift ;; + --state) remove_state=true; shift ;; + --package) remove_package=true; shift ;; + --yes) apply=true; shift ;; + --dry-run) dry_run=true; shift ;; + --engine) need_value "$@"; engine="$2"; shift 2 ;; + --project) need_value "$@"; project="$2"; shift 2 ;; + --config-dir) need_value "$@"; config_dir="$2"; shift 2 ;; + --state-dir) need_value "$@"; state_dir="$2"; shift 2 ;; + --downloads-dir) need_value "$@"; downloads_dir="$2"; shift 2 ;; + --help|-h) usage; exit 0 ;; + *) die "Unknown option: $1" ;; + esac +done +$remove_containers || $remove_config || $remove_state || $remove_package || die "Select at least one component; see --help" +! $remove_volumes || $remove_containers || die "--volumes requires --containers" +[[ "$project" =~ ^[a-z0-9][a-z0-9_-]*$ ]] || die "Invalid Compose project name" +[[ -z "$engine" || "$engine" == docker || "$engine" == podman ]] || die "--engine must be docker or podman" + +# Resolve existing symlinks in parents, including for a missing final directory. +canonical_path() { + local path="$1" parent leaf + [[ "$path" == /* ]] || path="$PWD/$path" + if [[ -d "$path" ]]; then + (cd -- "$path" && pwd -P) + else + parent="$(dirname -- "$path")" + leaf="$(basename -- "$path")" + [[ "$parent" != "$path" ]] || die "Cannot resolve path: $path" + parent="$(canonical_path "$parent")" + case "$leaf" in + .) echo "$parent" ;; + ..) dirname -- "$parent" ;; + *) echo "${parent%/}/$leaf" ;; + esac + fi +} + +protected_home="$(canonical_path "$HOME")" +protected_cwd="$(pwd -P)" +protected_downloads="$(canonical_path "$downloads_dir")" +check_path() { + local path="$1" resolved protected + resolved="$(canonical_path "$path")" + [[ "$resolved" != / ]] || die "Refusing unsafe removal path: $path" + for protected in "$protected_home" "$protected_cwd" "$protected_downloads"; do + [[ "$protected" != "$resolved" && "$protected" != "$resolved/"* ]] || die "Refusing unsafe removal path: $path" + done +} + +paths=() +if $remove_config; then + [[ ! -L "$config_dir" ]] || die "Configuration directory must not be a symlink" + config_dir="$(canonical_path "$config_dir")" + check_path "$config_dir" + paths+=("$config_dir/config.json" "$config_dir/secrets.env") +fi +if $remove_state; then + [[ ! -L "$state_dir" ]] || die "State directory must not be a symlink" + state_dir="$(canonical_path "$state_dir")" + check_path "$state_dir" + for name in docker-compose.yml .env.docker jackett prowlarr qbittorrent flaresolverr gluetun logs; do + paths+=("$state_dir/$name") + done + for path in "$state_dir"/helm.log*; do + [[ ! -e "$path" && ! -L "$path" ]] || paths+=("$path") + done +fi +# Check every directory before performing ANY mutations. Artifact symlinks are +# unlinked rather than followed; unrelated files in the roots are left alone. +for path in "${paths[@]}"; do + [[ -L "$path" ]] || check_path "$path" +done + +container_ids=() +network_ids=() +volume_ids=() +if $remove_containers; then + if [[ -z "$engine" ]]; then + if command -v docker >/dev/null 2>&1; then engine=docker + elif command -v podman >/dev/null 2>&1; then engine=podman + else die "No Docker/Podman found; omit --containers or install an engine" + fi + fi + label="label=com.docker.compose.project=$project" + output="$("$engine" ps -aq --filter "$label")" + while IFS= read -r id; do [[ -z "$id" ]] || container_ids+=("$id"); done <<< "$output" + output="$("$engine" network ls -q --filter "$label")" + while IFS= read -r id; do [[ -z "$id" ]] || network_ids+=("$id"); done <<< "$output" + if $remove_volumes; then + output="$("$engine" volume ls -q --filter "$label")" + while IFS= read -r id; do [[ -z "$id" ]] || volume_ids+=("$id"); done <<< "$output" + fi +fi +if $remove_package; then + python_cmd="${HELM_PYTHON:-python3}" + command -v "$python_cmd" >/dev/null 2>&1 || die "Python not found: $python_cmd" +fi + +run() { + printf ' Run:' + printf ' %q' "$@" + printf '\n' + if $apply && ! $dry_run; then "$@"; fi +} +echo "Removal plan (host download directory is preserved):" +if $remove_volumes; then echo " Selected named volumes and all their contents will be deleted."; fi +if [[ ${#container_ids[@]} -gt 0 ]]; then run "$engine" container rm -f "${container_ids[@]}"; fi +if [[ ${#network_ids[@]} -gt 0 ]]; then run "$engine" network rm "${network_ids[@]}"; fi +if [[ ${#volume_ids[@]} -gt 0 ]]; then run "$engine" volume rm "${volume_ids[@]}"; fi +for path in "${paths[@]}"; do + if [[ -L "$path" || -f "$path" ]]; then run rm -f -- "$path" + elif [[ -d "$path" ]]; then run rm -rf -- "$path" + fi +done +if $remove_package; then run "$python_cmd" -m pip uninstall -y helm-torrent; fi +if $apply && ! $dry_run; then + echo "Selected components removed. Downloads, user plugins, images and system services were not selected." +else + echo "Preview only. Pass --yes without --dry-run to apply." +fi From 99c1a7210ddbf1e8492692b50eae35d31d8a6bce Mon Sep 17 00:00:00 2001 From: Piratebird <141295458+Piratebird@users.noreply.github.com> Date: Sun, 1 Nov 2026 22:59:37 +0200 Subject: [PATCH 02/18] :shipit: feat(config): layered settings with TOML and JSONC support - Add settings core with validation, value origins, and a shared JSON Schema - Resolve environment, config file, runtime state, then defaults - Migrate non-default config.json values to config.toml once, keeping the original - Report invalid config clearly and never reset the user's file - Move every config caller to settings and use one set of service defaults - Handle config errors in the console entry point - Add tomli below Python 3.11 and update uninstall, setup, and docs --- .env.example | 2 +- CHANGELOG.md | 3 + README.md | 26 +- pyproject.toml | 3 +- requirements.txt | 1 + setup.sh | 3 + src/helm/cli.py | 62 ++-- src/helm/core/config_manager.py | 55 +--- src/helm/core/config_wizard.py | 68 +++-- src/helm/core/indexer_manager.py | 6 +- src/helm/core/jobs.py | 4 +- src/helm/core/qbittorrent_client.py | 5 +- src/helm/core/rss_fetcher.py | 16 +- src/helm/core/settings.py | 412 ++++++++++++++++++++++++++ tests/test_cli.py | 13 +- tests/test_config_manager.py | 34 +-- tests/test_rss_fetcher.py | 12 +- tests/test_service_boundaries.py | 13 +- tests/test_settings.py | 436 ++++++++++++++++++++++++++++ uninstall.sh | 6 +- 20 files changed, 992 insertions(+), 188 deletions(-) create mode 100644 src/helm/core/settings.py create mode 100644 tests/test_settings.py diff --git a/.env.example b/.env.example index 2859b18..bed9591 100644 --- a/.env.example +++ b/.env.example @@ -12,7 +12,7 @@ JACKETT_PASSWORD= # qBittorrent QB_PASSWORD=mypassword -# --- Non-secret settings stay in config.json, not here --- +# --- Non-secret settings stay in config.toml, not here --- # JACKETT_URL=http://localhost:9117 # QB_WEBUI=http://localhost:8080 # QB_USERNAME=admin \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 63fa85d..7ebfcb7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,8 @@ All notable changes to this project will be documented in this file. ## [Unreleased] ### Changed +- Use one set of service defaults: Jackett `19117`, Prowlarr `19696`, qBittorrent `18080`. Set `[services]` for a native Jackett on `9117`. +- Report invalid config files clearly instead of resetting them. Runtime choices are stored in `settings.json` in the state directory, below the user's file. - Start faster by deferring heavy imports, and split the CLI entry point into separate handlers. - Use SQLite WAL, indexed lookups, one-second cancellation polling and `sendfile` in the queue and file server. - Install the `helm-torrent` command instead of `helm` to avoid Kubernetes Helm's executable. Python imports, configuration paths, and container names remain compatible. Source setup generates `helm-torrent.sh`. @@ -10,6 +12,7 @@ All notable changes to this project will be documented in this file. - Respect the configured download directory and reject unknown flags, blank queries, and invalid content types. ### Added +- Layered settings from `config.toml` or `config.jsonc`, with validation and a shared JSON Schema. Existing `config.json` values migrate once, and the original file stays in place. If both new files exist, `config.toml` is used. - Durable job queue with process-isolated workers, crash recovery, cancellation and a completed-file catalog. - `helm-torrent download`, `watch`, `serve`, `files`, `attach` and `daemon`, plus `--daemon` and `--session`. - Authenticated HTTP job API and range streaming limited to cataloged files inside the download directory. diff --git a/README.md b/README.md index fa6febb..4e3b944 100644 --- a/README.md +++ b/README.md @@ -96,7 +96,7 @@ If a source times out (for example, `nyaa.si`), Helm keeps results from other co - Enter a nonempty, specific query. A request containing `q=` has an empty query; current Helm rejects blank interactive and CLI searches. - Use `helm-torrent logs` for recent source errors, or `HELM_VERBOSE=true helm-torrent search "artist album" --type music --lite --json` for verbose diagnostics on stderr. -- If raw results exist but the final list is empty, check content filters and `min_seeds` in `config.json` (default: 3). Use `helm-torrent paths` to locate it. +- If raw results exist but the final list is empty, check content filters and `search.min_seeds` in `config.toml` (default: 3). Use `helm-torrent paths` to locate it. - Content types are mapped to plugin category keys when supported (video searches movies/TV/anime); general sources fall back to `all`. Inline feeds and unsupported categories still rely on local scoring/filtering. - A source summary on stderr distinguishes empty results from timeouts, HTTP failures, connection failures, and parse failures. Bundled plugins report swallowed failures; third-party plugins may need the `novaprinter.report_error` hook. Jobs whose queue budget expires are marked `budget_exhausted`; JSON stdout stays separate. @@ -161,14 +161,34 @@ With the adoption of XDG standards, your configuration and state are stored nati What these do: -- `config.json`: Settings only (indexers, URLs, flags) — never secrets. +- `config.toml` or `config.jsonc`: Your settings, never secrets. Helm does not rewrite this file. If both exist, `config.toml` is used and the two are not merged. +- `state/settings.json`: Choices Helm saves at runtime, such as wizard answers. Your config file overrides these. - `secrets.env`: API keys and passwords (e.g. `JACKETT_API_KEY`, `JACKETT_PASSWORD`, `QB_PASSWORD`). Written with mode `0600` and resolved with env vars taking priority. - `state/.env.docker`: Environment variables for the containers - `state/jackett/`: Jackett configuration and indexers - `state/qbittorrent/`: qBittorrent configuration and state - `Downloads/helm/`: Your downloaded files -The first run migrates any legacy secrets found in older `config.json` files into `secrets.env` and rewrites the config file scrubbed. +```toml +# ~/.config/helm/config.toml +[search] +min_seeds = 3 +lite_workers = 6 +default_type = "video" +indexer_manager = "jackett" # jackett, prowlarr or both +lite_only = false + +[services] +jackett = "http://localhost:19117" +prowlarr = "http://localhost:19696" +qbittorrent = "http://localhost:18080" +qbittorrent_user = "admin" +qbittorrent_downloads_root = "/downloads" +``` + +`config.jsonc` uses the same keys and allows comments and trailing commas. Command-line flags and environment variables such as `QB_WEBUI` override the file. Values you leave out use the defaults above. + +The first run creates `config.toml` from any non-default values in an older `config.json`, moves legacy secrets into `secrets.env`, and leaves `config.json` in place with a `.pre-toml.bak` copy. After that, `config.json` is ignored. ## Usage diff --git a/pyproject.toml b/pyproject.toml index b7ea7dd..262ac2c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -19,7 +19,8 @@ classifiers = [ dependencies = [ "requests>=2.31.0", "python-dotenv>=1.0.0", - "beautifulsoup4>=4.12.0" + "beautifulsoup4>=4.12.0", + "tomli>=1.1.0; python_version<'3.11'" ] [project.optional-dependencies] diff --git a/requirements.txt b/requirements.txt index 4a7051d..cc8e74d 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,3 +1,4 @@ requests>=2.31.0 python-dotenv>=1.0.0 beautifulsoup4>=4.12.0 +tomli>=1.1.0; python_version<'3.11' diff --git a/setup.sh b/setup.sh index 519ef85..3fd40ca 100755 --- a/setup.sh +++ b/setup.sh @@ -368,6 +368,9 @@ data["INDEXER_MANAGER"] = manager with open(path, "w") as f: json.dump(data, f, indent=4) PY +if [ -f "$HELM_CONFIG/config.toml" ] || [ -f "$HELM_CONFIG/config.jsonc" ]; then + echo "[WARN] Your config file takes priority. Set search.indexer_manager = \"$INDEXER_MANAGER\" there if needed." +fi echo "" if [ -n "$SKIP_PROMPTS" ]; then diff --git a/src/helm/cli.py b/src/helm/cli.py index e7b5a3d..efabc86 100644 --- a/src/helm/cli.py +++ b/src/helm/cli.py @@ -10,9 +10,10 @@ from dotenv import load_dotenv -from helm.core.config_manager import CONTENT_PROFILES, NEGATIVE_KEYWORDS, load_config, worker_count # noqa: E402 +from helm.core.config_manager import CONTENT_PROFILES, NEGATIVE_KEYWORDS, worker_count # noqa: E402 from helm.core.logger import configure_logging, tail_log # noqa: E402 from helm.core.secret_manager import get_secret, get_secrets_file # noqa: E402 +from helm.core.settings import ConfigError, load_settings, remember # noqa: E402 from helm.ui.colors import C_ERR, C_LOGO, C_RST, C_SUB, C_TEXT, logo # noqa: E402 @@ -77,21 +78,21 @@ def _cmd_status(): print("\n".join(helm_containers) if helm_containers else "No helm containers found.") print("-" * 40) - cfg = load_config() + settings = load_settings() container_text = (res.stdout or "").lower() if res else "" print("\n--- Web UIs ---") if container_text and "jackett" not in container_text: print("Jackett: not running") else: - print(f"Jackett: {cfg.get('JACKETT_URL') or 'http://localhost:19117'}") + print(f"Jackett: {settings.get('services.jackett')}") if container_text and "prowlarr" not in container_text: print("Prowlarr: not running") else: - print(f"Prowlarr: {cfg.get('PROWLARR_URL') or 'http://localhost:19696'}") + print(f"Prowlarr: {settings.get('services.prowlarr')}") if container_text and "qbittorrent" not in container_text: print("qBittorrent: not running") else: - print(f"qBittorrent: {cfg.get('QB_WEBUI') or 'http://localhost:18080'}") + print(f"qBittorrent: {settings.get('services.qbittorrent')}") print("---------------") @@ -253,8 +254,11 @@ def _parse_args(parser): if getattr(args, "dl_dir", None): os.environ["HELM_DL_DIR"] = os.path.abspath(args.dl_dir) + requested = getattr(args, "lite_workers", None) + if requested is None and "HELM_LITE_WORKERS" not in os.environ: + requested = load_settings().get("search.lite_workers") try: - workers = worker_count(getattr(args, "lite_workers", None)) + workers = worker_count(requested) except ValueError as error: parser.error(str(error)) os.environ["HELM_LITE_WORKERS"] = str(workers) @@ -317,9 +321,9 @@ def _run_download(source, lite): def _run_headless(args, parser): - config = load_config() - lite = args.lite or config.get("LITE_MODE_ONLY", False) - if not lite and not (get_secret("QB_PASSWORD") or config.get("QB_WEBUI") or os.getenv("QB_WEBUI")): + settings = load_settings() + lite = args.lite or settings.get("search.lite_only") + if not lite and not (get_secret("QB_PASSWORD") or settings.origin("services.qbittorrent") != "default"): lite = True if args.command == "watch": from helm.core.watch import run_watch @@ -362,13 +366,14 @@ def _run_utility(command): if command == "bug-report": import zipfile - from helm.core.config_manager import get_config_file, get_log_dir + from helm.core.config_manager import get_log_dir + from helm.core.settings import read_file, report_config_file desktop = os.path.join(os.path.expanduser("~"), "Desktop") if not os.path.exists(desktop): desktop = os.path.expanduser("~") zip_path = os.path.join(desktop, "helm-bug-report.zip") - config_file = get_config_file() + config_file = report_config_file() log_file = os.path.join(get_log_dir(), "helm.log") with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zipf: @@ -376,11 +381,9 @@ def _run_utility(command): from helm.core.secret_manager import redact_config try: - with open(config_file, "r") as f: - cfg_data = json.load(f) - zipf.writestr("config.json", json.dumps(redact_config(cfg_data), indent=4)) + zipf.writestr("config.json", json.dumps(redact_config(read_file(config_file)), indent=4)) except Exception: - print("Could not redact config.json; omitting it from the bug report.", file=sys.stderr) + print("Could not redact the config; omitting it from the bug report.", file=sys.stderr) if os.path.exists(log_file): from helm.core.secret_manager import redact_text @@ -395,6 +398,15 @@ def _run_utility(command): def main(): + """Console entry point. It bypasses the __main__ block below.""" + try: + run() + except ConfigError as error: + print(f"\033[31m[!] {error}\033[0m", file=sys.stderr) + raise SystemExit(1) from None + + +def run(): parser = build_parser() args = _parse_args(parser) if _dispatch_background(args, parser): @@ -423,8 +435,7 @@ def main(): raise SystemExit(0) from None if not args.lite: - config = load_config() - if config.get("LITE_MODE_ONLY"): + if load_settings().get("search.lite_only"): args.lite = True elif ( not os.getenv("JACKETT_API_KEY") @@ -436,10 +447,7 @@ def main(): # Machine-readable output must never interleave prompts; fall # back to Lite Mode silently instead of asking the user. args.lite = True - config["LITE_MODE_ONLY"] = True - from helm.core.config_manager import save_config - - save_config(config) + remember({"search.lite_only": True}) else: try: choice = ( @@ -451,10 +459,7 @@ def main(): ) if choice != "n": args.lite = True - config["LITE_MODE_ONLY"] = True - from helm.core.config_manager import save_config - - save_config(config) + remember({"search.lite_only": True}) else: ensure_config() except (KeyboardInterrupt, EOFError): @@ -495,13 +500,11 @@ def _manage_indexers(args): raise SystemExit(1) from None ensure_config() - config = load_config() - use_prowlarr = getattr(args, "prowlarr", False) use_jackett = getattr(args, "jackett", False) if not use_prowlarr and not use_jackett: - manager_type = config.get("INDEXER_MANAGER", "jackett") + manager_type = load_settings().get("search.indexer_manager") elif use_prowlarr: manager_type = "prowlarr" else: @@ -657,8 +660,7 @@ def _run_session(args, teardown_oneshot): if not args.json: print(f"{C_LOGO}{source_name} returned {len(all_items)} raw results{C_RST}") - config = load_config() - min_seeds = config.get("min_seeds", 3) + min_seeds = load_settings().get("search.min_seeds") unique_items = dedupe(all_items) filtered = filter_items(unique_items, cat_profiles, negatives, min_score=0, min_seeds=min_seeds) diff --git a/src/helm/core/config_manager.py b/src/helm/core/config_manager.py index 77af526..6a200ba 100644 --- a/src/helm/core/config_manager.py +++ b/src/helm/core/config_manager.py @@ -7,7 +7,6 @@ """ ## imports## -import json import os import shutil import sys @@ -15,7 +14,7 @@ ## setting up the URL and the API key from .env ## # These are loaded dynamically in the modules that need them to avoid import crashes. -# Credentials that must never be persisted in config.json; they live in secrets.env. +# Credentials that must never be persisted in config files; they live in secrets.env. SECRET_KEYS = frozenset( [ "JACKETT_API_KEY", @@ -178,10 +177,6 @@ def worker_count(value=None): return count -def get_qb_url(): - return (os.getenv("QB_WEBUI") or load_config().get("QB_WEBUI") or "http://localhost:18080").rstrip("/") - - def get_config_file(): config_dir = get_config_dir() os.makedirs(config_dir, exist_ok=True) @@ -199,51 +194,3 @@ def _migrate_old_config(): print(f"Migrated config from {old_file} to {new_file}") except Exception as e: print(f"Failed to migrate config: {e}") - - -def load_config(): - _migrate_old_config() - config_file = get_config_file() - - default_config = { - "indexers": [], - "qualities": CONTENT_PROFILES["video"], - "min_seeds": 3, - "EXECUTION_MODE": "native", - "LITE_MODE_ONLY": False, - } - - if not os.path.exists(config_file): - return default_config - - with open(config_file) as f: - try: - content = f.read().strip() - if not content: - return default_config - - loaded = json.loads(content) - # Ensure new keys exist (after secrets are stripped so migrations - # never re-introduce credentials into config.json) - for k, v in default_config.items(): - if k not in loaded: - loaded[k] = v - except json.JSONDecodeError: - print("Config file is corrupted. Backing up to config.json.bak and resetting.") - shutil.copy(config_file, config_file + ".bak") - return default_config - - # One-way migration: legacy secrets found in config.json move to secrets.env. - from helm.core.secret_manager import migrate_config_secrets - - had_secrets = any(k in loaded for k in SECRET_KEYS) - loaded = migrate_config_secrets(loaded) - if had_secrets: - # Persist the scrubbed config so the legacy secret is removed from disk. - save_config(loaded) - return loaded - - -def save_config(config): - with open(get_config_file(), "w") as f: - json.dump(config, f, indent=4) diff --git a/src/helm/core/config_wizard.py b/src/helm/core/config_wizard.py index 6ef3e8a..f3c325b 100644 --- a/src/helm/core/config_wizard.py +++ b/src/helm/core/config_wizard.py @@ -3,8 +3,13 @@ import requests -from helm.core.config_manager import load_config, save_config from helm.core.secret_manager import get_secret, set_secrets +from helm.core.settings import load_settings, remember + + +def save_answers(updates): + for path in remember(updates): + print(f"\033[33m[WARN] {path} stays as set in your config file; edit it there to change it.\033[0m") def run_wizard(): @@ -14,7 +19,8 @@ def run_wizard(): print("\033[1mWelcome to Helm Interactive Configuration Wizard!\033[0m") print("It looks like some essential configurations are missing.\n") - config = load_config() + settings = load_settings() + updates = {} print("You can run Helm in two modes:") print(" 1. Lite Mode (Native plugins only, no media server required)") @@ -27,17 +33,16 @@ def run_wizard(): ) if choice not in ("y", "yes"): print("\n\033[32mOpting for Lite Mode. You can change this later.\033[0m\n") - config["LITE_MODE_ONLY"] = True - save_config(config) + save_answers({"search.lite_only": True}) return - config["LITE_MODE_ONLY"] = False + updates["search.lite_only"] = False indexer_choice = input("Which Indexer Manager are you using? [1] Jackett [2] Prowlarr (default 1): ").strip() if indexer_choice == "2": # Prowlarr - prowlarr_url = config.get("PROWLARR_URL", os.getenv("PROWLARR_URL", "http://localhost:19696")) + prowlarr_url = settings.get("services.prowlarr") prowlarr_api = get_secret("PROWLARR_API_KEY") or "" while True: @@ -76,12 +81,12 @@ def run_wizard(): else: print("Prowlarr API key is required.\n") - config["PROWLARR_URL"] = prowlarr_url + updates["services.prowlarr"] = prowlarr_url set_secrets({"PROWLARR_API_KEY": prowlarr_api}) - config["INDEXER_MANAGER"] = "prowlarr" + updates["search.indexer_manager"] = "prowlarr" else: # Jackett - jackett_url = config.get("JACKETT_URL", os.getenv("JACKETT_URL", "http://localhost:9117")) + jackett_url = settings.get("services.jackett") jackett_api = get_secret("JACKETT_API_KEY") or "" jackett_pwd = get_secret("JACKETT_PASSWORD") or "" @@ -138,13 +143,13 @@ def run_wizard(): else: print("Jackett API key is required.\n") - config["JACKETT_URL"] = jackett_url + updates["services.jackett"] = jackett_url set_secrets({"JACKETT_API_KEY": jackett_api, "JACKETT_PASSWORD": jackett_pwd}) - config["INDEXER_MANAGER"] = "jackett" + updates["search.indexer_manager"] = "jackett" # qBittorrent - qb_webui = config.get("QB_WEBUI", os.getenv("QB_WEBUI", "http://localhost:18080")) - qb_username = config.get("QB_USERNAME", os.getenv("QB_USERNAME", "admin")) + qb_webui = settings.get("services.qbittorrent") + qb_username = settings.get("services.qbittorrent_user") qb_password = get_secret("QB_PASSWORD") or "" while True: @@ -193,12 +198,12 @@ def run_wizard(): else: print("qBittorrent password is required.\n") - config["QB_WEBUI"] = qb_webui - config["QB_USERNAME"] = qb_username + updates["services.qbittorrent"] = qb_webui + updates["services.qbittorrent_user"] = qb_username set_secrets({"QB_PASSWORD": qb_password}) - save_config(config) - print("Configuration saved! (settings -> config.json, secrets -> secrets.env)\n") + save_answers(updates) + print("Configuration saved! Secrets are in secrets.env.\n") except KeyboardInterrupt: print("\n\n\033[33mConfiguration aborted. later bozo!\033[0m") sys.exit(0) @@ -209,19 +214,22 @@ def run_wizard(): sys.exit(1) +# Non-secret settings the full stack needs, and the variables other processes read. +REQUIRED_SETTINGS = { + "services.jackett": "JACKETT_URL", + "services.qbittorrent": "QB_WEBUI", + "services.qbittorrent_user": "QB_USERNAME", +} + + def ensure_config(): - config = load_config() + settings = load_settings() - if config.get("LITE_MODE_ONLY"): + if settings.get("search.lite_only"): return - needs_wizard = False # Check required settings (secrets are resolved via the secret store) - keys = ["JACKETT_URL", "QB_WEBUI", "QB_USERNAME"] - for k in keys: - if k not in config and not os.getenv(k): - needs_wizard = True - break + needs_wizard = any(settings.origin(path) == "default" for path in REQUIRED_SETTINGS) for k in ["JACKETT_API_KEY", "QB_PASSWORD"]: if not needs_wizard and not get_secret(k): needs_wizard = True @@ -229,7 +237,7 @@ def ensure_config(): # Dynamically check if JACKETT_PASSWORD is required if not needs_wizard and not get_secret("JACKETT_PASSWORD"): - jackett_url = config.get("JACKETT_URL", os.getenv("JACKETT_URL", "http://localhost:9117")) + jackett_url = settings.get("services.jackett") try: session = requests.Session() r = session.get(f"{jackett_url}/UI/Dashboard", timeout=2) @@ -246,11 +254,11 @@ def ensure_config(): # We don't exit here so the rest of the app can try to run, or fail with a native API error else: run_wizard() - config = load_config() + settings = load_settings() - for k in keys: - if k in config: - os.environ[k] = config[k] + for path, variable in REQUIRED_SETTINGS.items(): + if settings.origin(path) != "default": + os.environ[variable] = settings.get(path) # Push all resolved secrets into the environment so native modules can use them. from helm.core.config_manager import SECRET_KEYS diff --git a/src/helm/core/indexer_manager.py b/src/helm/core/indexer_manager.py index f42ba58..a08c2a4 100644 --- a/src/helm/core/indexer_manager.py +++ b/src/helm/core/indexer_manager.py @@ -1,17 +1,17 @@ -import os import xml.etree.ElementTree as ET import requests from helm.core.logger import get_logger from helm.core.secret_manager import get_secret +from helm.core.settings import load_settings logger = get_logger(__name__) class JackettManager: def __init__(self): - self.url = os.getenv("JACKETT_URL", "http://localhost:9117") + self.url = load_settings().get("services.jackett") self.api_key = get_secret("JACKETT_API_KEY") if not self.api_key: raise RuntimeError("JACKETT_API_KEY environment variable not set") @@ -80,7 +80,7 @@ class ProwlarrManager: DEFAULT_SEED_NAMES = ("1337x", "yts", "torrentgalaxy", "nyaapantsu", "eztv") def __init__(self): - self.url = os.getenv("PROWLARR_URL", "http://localhost:19696") + self.url = load_settings().get("services.prowlarr") self.api_key = get_secret("PROWLARR_API_KEY") if not self.api_key: raise RuntimeError("PROWLARR_API_KEY environment variable not set") diff --git a/src/helm/core/jobs.py b/src/helm/core/jobs.py index 79c9c7f..8b3b1f2 100644 --- a/src/helm/core/jobs.py +++ b/src/helm/core/jobs.py @@ -298,9 +298,9 @@ def process_one(store, stop=None, cancel_poll=1.0): def host_path(save_path, name): """Map a path reported by qBittorrent, possibly inside its container, to this host.""" - from helm.core.config_manager import load_config + from helm.core.settings import load_settings - mount = PurePosixPath(os.getenv("QB_DOWNLOADS_ROOT") or load_config().get("QB_DOWNLOADS_ROOT") or "/downloads") + mount = PurePosixPath(load_settings().get("services.qbittorrent_downloads_root")) reported = PurePosixPath(save_path or mount) / name if mount in reported.parents: return Path(get_dl_dir()) / reported.relative_to(mount) diff --git a/src/helm/core/qbittorrent_client.py b/src/helm/core/qbittorrent_client.py index ffa9cfb..9d1fb25 100644 --- a/src/helm/core/qbittorrent_client.py +++ b/src/helm/core/qbittorrent_client.py @@ -7,14 +7,13 @@ """ -import os import threading import requests -from helm.core.config_manager import get_qb_url, load_config from helm.core.logger import get_logger from helm.core.secret_manager import get_secret +from helm.core.settings import get_qb_url, load_settings from helm.core.torrent_links import resolve_torrent logger = get_logger(__name__) @@ -33,7 +32,7 @@ def login_qbittorrent(force=False): """ global _session, _session_key qb_webui = get_qb_url() - qb_username = os.getenv("QB_USERNAME") or load_config().get("QB_USERNAME", "admin") + qb_username = load_settings().get("services.qbittorrent_user") qb_password = get_secret("QB_PASSWORD") key = (qb_webui, qb_username, qb_password) with _session_lock: diff --git a/src/helm/core/rss_fetcher.py b/src/helm/core/rss_fetcher.py index e464143..fdb9c41 100644 --- a/src/helm/core/rss_fetcher.py +++ b/src/helm/core/rss_fetcher.py @@ -6,7 +6,6 @@ """ import email.utils -import os import urllib.error import xml.etree.ElementTree as ET from dataclasses import dataclass @@ -154,11 +153,10 @@ def _fetch_aggregate(jackett_url, api_key, query, cat): def search_prowlarr(query, content_type="video"): - from helm.core.config_manager import load_config from helm.core.secret_manager import get_secret + from helm.core.settings import load_settings - config = load_config() - prowlarr_url = config.get("PROWLARR_URL", "http://localhost:19696") + prowlarr_url = load_settings().get("services.prowlarr") api_key = get_secret("PROWLARR_API_KEY") if not api_key or "your_prowlarr_api_key_here" in api_key.lower(): @@ -172,7 +170,6 @@ def search_prowlarr(query, content_type="video"): logger.info("Event: Prowlarr indexers empty. Seeding defaults...") from helm.core.indexer_manager import ProwlarrManager - os.environ["PROWLARR_URL"] = prowlarr_url seed_count = ProwlarrManager().seed_default_indexers() logger.info("Event: Seeded %s default Prowlarr indexers.", seed_count) except Exception: @@ -249,10 +246,9 @@ def search_indexers(query, content_type="video", fallback_lite=True): other manager when configured, and finally to native Lite Mode plugins so a search never comes up empty. """ - from helm.core.config_manager import load_config + from helm.core.settings import load_settings - config = load_config() - manager = config.get("INDEXER_MANAGER", "jackett") + manager = load_settings().get("search.indexer_manager") def dedupe(items): seen = set() @@ -288,7 +284,9 @@ def dedupe(items): def search_jackett(query, content_type="video"): - jackett_url = os.getenv("JACKETT_URL", "http://localhost:9117") + from helm.core.settings import load_settings + + jackett_url = load_settings().get("services.jackett") api_key = get_secret("JACKETT_API_KEY") if not api_key: logger.info("Event: Jackett API key not configured. Seamlessly falling back to native Lite Mode plugins.") diff --git a/src/helm/core/settings.py b/src/helm/core/settings.py new file mode 100644 index 0000000..ccac4a3 --- /dev/null +++ b/src/helm/core/settings.py @@ -0,0 +1,412 @@ +"""Layered settings: defaults, runtime state, the user's config file, environment. + +The user's config.toml or config.jsonc is never rewritten after it is created, +so its comments survive. Values Helm decides at runtime go to the state layer, +which ranks below the user's file. Secrets stay in secrets.env. +""" + +import json +import os +import shutil +import sys +import tempfile +from dataclasses import dataclass +from typing import Any, Tuple + +from helm.core import config_manager +from helm.core.config_manager import CONTENT_PROFILES, get_config_dir, get_state_dir + + +class ConfigError(ValueError): + """A configuration value or file that needs the user's attention.""" + + +@dataclass(frozen=True) +class Field: + path: str + kind: str + default: Any + env: str = "" + legacy: str = "" + choices: Tuple[str, ...] = () + minimum: Any = None + maximum: Any = None + + +FIELDS = ( + Field("search.min_seeds", "int", 3, legacy="min_seeds", minimum=0), + Field("search.lite_workers", "int", 6, env="HELM_LITE_WORKERS", minimum=1, maximum=12), + Field("search.default_type", "str", "video", choices=tuple(sorted(CONTENT_PROFILES))), + Field( + "search.indexer_manager", + "str", + "jackett", + env="INDEXER_MANAGER", + legacy="INDEXER_MANAGER", + choices=("both", "jackett", "prowlarr"), + ), + Field("search.lite_only", "bool", False, env="HELM_LITE_ONLY", legacy="LITE_MODE_ONLY"), + Field("services.jackett", "url", "http://localhost:19117", env="JACKETT_URL", legacy="JACKETT_URL"), + Field("services.prowlarr", "url", "http://localhost:19696", env="PROWLARR_URL", legacy="PROWLARR_URL"), + Field("services.qbittorrent", "url", "http://localhost:18080", env="QB_WEBUI", legacy="QB_WEBUI"), + Field("services.qbittorrent_user", "str", "admin", env="QB_USERNAME", legacy="QB_USERNAME"), + Field( + "services.qbittorrent_downloads_root", + "str", + "/downloads", + env="QB_DOWNLOADS_ROOT", + legacy="QB_DOWNLOADS_ROOT", + ), +) +BY_PATH = {field.path: field for field in FIELDS} +USER_FILES = ("config.toml", "config.jsonc") + +_file_cache: dict = {} + + +def parse_jsonc(text): + """Parse JSON with // and /* */ comments and trailing commas.""" + output = [] + index = 0 + in_string = False + while index < len(text): + character = text[index] + pair = text[index : index + 2] + if in_string: + output.append(character) + if character == "\\": + output.append(text[index + 1 : index + 2]) + index += 1 + elif character == '"': + in_string = False + index += 1 + elif character == '"': + in_string = True + output.append(character) + index += 1 + elif pair == "//": + end = text.find("\n", index) + index = len(text) if end == -1 else end + elif pair == "/*": + end = text.find("*/", index + 2) + if end == -1: + raise ValueError("Unterminated block comment") + # Keeping line breaks keeps parser error positions accurate. + output.append("\n" * text.count("\n", index, end)) + index = end + 2 + else: + if character in "]}": + position = len(output) - 1 + while position >= 0 and output[position].isspace(): + position -= 1 + if position >= 0 and output[position] == ",": + output[position] = " " + output.append(character) + index += 1 + return json.loads("".join(output)) + + +def read_file(path): + """Read a TOML, JSONC or JSON config file into a dictionary.""" + try: + with open(path, encoding="utf-8") as stream: + text = stream.read() + except (OSError, UnicodeDecodeError) as error: + raise ConfigError(f"Cannot read {path}: {error}") from error + try: + if str(path).endswith(".toml"): + try: + import tomllib + except ImportError: + import tomli as tomllib # type: ignore[no-redef] + data = tomllib.loads(text) + else: + data = parse_jsonc(text) if text.strip() else {} + except ValueError as error: + raise ConfigError(f"Invalid syntax in {path}: {error}") from error + if not isinstance(data, dict): + raise ConfigError(f"{path} must contain a table of settings") + return data + + +def flatten(data, prefix=""): + values = {} + for key, value in data.items(): + path = prefix + str(key) + if isinstance(value, dict): + values.update(flatten(value, path + ".")) + else: + values[path] = value + return values + + +def check(field, value): + """Return a valid value for a field, or raise ValueError.""" + if field.kind == "bool": + if not isinstance(value, bool): + raise ValueError("must be true or false") + elif field.kind == "int": + if isinstance(value, bool) or not isinstance(value, int): + raise ValueError("must be a whole number") + if field.minimum is not None and value < field.minimum: + raise ValueError(f"must be at least {field.minimum}") + if field.maximum is not None and value > field.maximum: + raise ValueError(f"must be at most {field.maximum}") + else: + if not isinstance(value, str) or not value: + raise ValueError("must be a non-empty string") + if field.kind == "url": + if not value.lower().startswith(("http://", "https://")): + raise ValueError("must start with http:// or https://") + value = value.rstrip("/") + if field.choices and value not in field.choices: + raise ValueError("must be one of " + ", ".join(field.choices)) + return value + + +def from_env(field, text): + if field.kind == "bool": + return text.strip().lower() in ("1", "true", "yes", "on") + if field.kind == "int": + try: + return int(text) + except ValueError: + raise ValueError("must be a whole number") from None + return text + + +class Settings: + """Resolved values, and the layer each one came from.""" + + def __init__(self, values=None, origins=None, path=None, unknown=()): + self._values = {field.path: field.default for field in FIELDS} + self._values.update(values or {}) + self._origins = dict(origins or {}) + self.path = path + self.unknown = tuple(unknown) + + @classmethod + def from_legacy(cls, config): + values = map_legacy(config) + return cls(values, {path: "file" for path in values}) + + def get(self, path): + return self._values[path] + + def origin(self, path): + if path not in BY_PATH: + raise KeyError(path) + return self._origins.get(path, "default") + + +def state_file(): + return os.path.join(get_state_dir(), "settings.json") + + +def active_config_file(): + """Return the config file in use. TOML wins, and files are never merged.""" + for name in USER_FILES: + path = os.path.join(get_config_dir(), name) + if os.path.isfile(path): + return path + return None + + +def shadowed_config_files(): + """Return config files ignored because a higher-priority one exists.""" + paths = [os.path.join(get_config_dir(), name) for name in USER_FILES] + return [path for path in paths if os.path.isfile(path)][1:] + + +def report_config_file(): + """Return the file a bug report should describe.""" + return active_config_file() or config_manager.get_config_file() + + +def atomic_write(path, text): + directory = os.path.dirname(path) + os.makedirs(directory, exist_ok=True) + descriptor, temporary = tempfile.mkstemp(dir=directory, prefix=".helm-", suffix=".tmp") + try: + with os.fdopen(descriptor, "w", encoding="utf-8") as stream: + stream.write(text) + os.replace(temporary, path) + finally: + if os.path.exists(temporary): + os.unlink(temporary) + + +def map_legacy(config): + """Convert config.json keys, keeping only valid values that differ from defaults. + + A default written by old code must not outrank later runtime changes. + """ + values = {} + for field in FIELDS: + if field.legacy and field.legacy in config: + try: + value = check(field, config[field.legacy]) + except ValueError: + continue + if value != field.default: + values[field.path] = value + return values + + +def render_toml(values): + sections: dict = {} + for path, value in values.items(): + section, key = path.split(".", 1) + sections.setdefault(section, []).append((key, value)) + lines = ["# Helm settings. Helm never rewrites this file, so edit it freely.", ""] + for section, items in sections.items(): + lines.append(f"[{section}]") + # JSON strings, booleans and integers are all valid TOML values here. + lines.extend(f"{key} = {json.dumps(value)}" for key, value in items) + lines.append("") + return "\n".join(lines) + + +def migrate_legacy(): + """Create config.toml from config.json once. The original file stays in place.""" + if active_config_file(): + return + config_manager._migrate_old_config() + legacy = config_manager.get_config_file() + if not os.path.isfile(legacy): + return + try: + data = read_file(legacy) + except ConfigError: + backup = legacy + ".bak" + if not os.path.exists(backup): + shutil.copy(legacy, backup) + print(f"Ignoring corrupted config; a copy is at {backup}", file=sys.stderr) + return + if not data: + return + + from helm.core.secret_manager import migrate_config_secrets + + had_secrets = any(key in data for key in config_manager.SECRET_KEYS) + data = migrate_config_secrets(data) + if had_secrets: + atomic_write(legacy, json.dumps(data, indent=4)) + values = map_legacy(data) + if values: + shutil.copy2(legacy, legacy + ".pre-toml.bak") + target = os.path.join(get_config_dir(), USER_FILES[0]) + atomic_write(target, render_toml(values)) + print(f"Migrated settings to {target}", file=sys.stderr) + + +def _load_cached(path): + """Parse a file once per change, so long-running services see edits cheaply.""" + details = os.stat(path) + key = (details.st_mtime_ns, details.st_size) + cached = _file_cache.get(path) + if cached and cached[0] == key: + return cached[1] + data = flatten(read_file(path)) + _file_cache[path] = (key, data) + return data + + +def _load_state(): + """Read runtime values. Helm owns this file, so damage only loses those values.""" + path = state_file() + if not os.path.isfile(path): + return {} + try: + data = _load_cached(path) + except ConfigError: + return {} + values = {} + for key, value in data.items(): + if key in BY_PATH: + try: + values[key] = check(BY_PATH[key], value) + except ValueError: + continue + return values + + +def load_settings(): + """Resolve settings: environment, then config file, then state, then defaults.""" + migrate_legacy() + values = {} + origins = {} + for path, value in _load_state().items(): + values[path] = value + origins[path] = "state" + + active = active_config_file() + unknown = [] + problems = [] + if active: + for path, value in _load_cached(active).items(): + field = BY_PATH.get(path) + if field is None: + unknown.append(path) + continue + try: + values[path] = check(field, value) + origins[path] = "file" + except ValueError as error: + problems.append(f"{path} {error}") + + for field in FIELDS: + text = os.environ.get(field.env) if field.env else None + if text: + try: + values[field.path] = check(field, from_env(field, text)) + origins[field.path] = "env" + except ValueError as error: + problems.append(f"{field.env} {error}") + + if problems: + raise ConfigError(f"Invalid settings ({active or 'environment'}): " + "; ".join(problems)) + return Settings(values, origins, active, unknown) + + +def remember(updates): + """Store runtime values, and return those the user's file will keep overriding.""" + clean = {} + for path, value in updates.items(): + if path not in BY_PATH: + raise KeyError(path) + clean[path] = check(BY_PATH[path], value) + existing = {} + path = state_file() + if os.path.isfile(path): + try: + existing = flatten(read_file(path)) + except ConfigError: + pass + existing.update(clean) + atomic_write(path, json.dumps(existing, indent=4)) + settings = load_settings() + return [key for key in clean if settings.origin(key) == "file"] + + +def get_qb_url(): + return load_settings().get("services.qbittorrent") + + +def settings_schema(): + """Return one JSON Schema that describes both config formats.""" + kinds = {"bool": "boolean", "int": "integer", "str": "string", "url": "string"} + sections: dict = {} + for field in FIELDS: + section, key = field.path.split(".", 1) + entry: dict = {"type": kinds[field.kind], "default": field.default} + if field.kind == "url": + entry["pattern"] = "^[Hh][Tt][Tt][Pp][Ss]?://" + if field.choices: + entry["enum"] = list(field.choices) + if field.minimum is not None: + entry["minimum"] = field.minimum + if field.maximum is not None: + entry["maximum"] = field.maximum + sections.setdefault(section, {"type": "object", "properties": {}})["properties"][key] = entry + return {"$schema": "https://json-schema.org/draft/2020-12/schema", "type": "object", "properties": sections} diff --git a/tests/test_cli.py b/tests/test_cli.py index 0436e50..a0e2935 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -5,6 +5,7 @@ import pytest import helm.cli +from helm.core.settings import Settings class FakeItem: @@ -122,7 +123,7 @@ def test_search_rejects_blank_query(monkeypatch, capsys, query): def test_empty_search_explains_sources_or_filters(monkeypatch, capsys, has_raw_results): items = _make_items() if has_raw_results else [] monkeypatch.setattr(helm.cli, "animated_search", lambda *a, **kw: (items, True)) - monkeypatch.setattr(helm.cli, "load_config", lambda: {"min_seeds": 1000}) + monkeypatch.setattr(helm.cli, "load_settings", lambda: Settings.from_legacy({"min_seeds": 1000})) monkeypatch.setattr(sys, "argv", ["helm-torrent", "search", "--lite", "ubuntu"]) with pytest.raises(SystemExit) as exc_info: helm.cli.main() @@ -222,7 +223,7 @@ def test_search_rejects_invalid_options_before_setup(monkeypatch, capsys, argume from unittest.mock import Mock setup = Mock(side_effect=AssertionError("Validation must precede setup")) - monkeypatch.setattr(helm.cli, "load_config", setup) + monkeypatch.setattr(helm.cli, "load_settings", setup) monkeypatch.setattr(sys, "argv", ["helm-torrent", "search", "ubuntu"] + arguments) with pytest.raises(SystemExit) as error: helm.cli.main() @@ -253,7 +254,7 @@ def test_lite_oneshot_never_starts_or_stops_containers(monkeypatch, explicit_lit stop = Mock() monkeypatch.setattr(oneshot, "spin_up_oneshot", start) monkeypatch.setattr(oneshot, "teardown_oneshot", stop) - monkeypatch.setattr(helm.cli, "load_config", lambda: {"LITE_MODE_ONLY": True}) + monkeypatch.setattr(helm.cli, "load_settings", lambda: Settings.from_legacy({"LITE_MODE_ONLY": True})) monkeypatch.setattr(helm.cli, "animated_search", lambda *a, **kw: (_make_items(), True)) arguments = ["helm-torrent", "search", "ubuntu", "--oneshot", "--json"] monkeypatch.setattr(sys, "argv", arguments + (["--lite"] if explicit_lite else [])) @@ -284,7 +285,7 @@ def test_oneshot_cleans_up_once_on_every_exit(monkeypatch, outcome): events = [] monkeypatch.setenv("JACKETT_API_KEY", "testkey") monkeypatch.setattr(helm.cli, "ensure_config", lambda: None) - monkeypatch.setattr(helm.cli, "load_config", lambda: {"min_seeds": 3}) + monkeypatch.setattr(helm.cli, "load_settings", lambda: Settings.from_legacy({"min_seeds": 3})) def start(): events.append("start") @@ -373,7 +374,7 @@ def unavailable(*args, **kwargs): raise RuntimeError("indexer unavailable with private-token") monkeypatch.setenv("JACKETT_API_KEY", "testkey") - monkeypatch.setattr(helm.cli, "load_config", lambda: {"min_seeds": 3}) + monkeypatch.setattr(helm.cli, "load_settings", lambda: Settings.from_legacy({"min_seeds": 3})) monkeypatch.setattr(helm.cli, "ensure_config", lambda: None) monkeypatch.setattr(rss_fetcher, "search_indexers", unavailable) monkeypatch.setattr(lite_fetcher, "search_lite", lambda query, content_type: results) @@ -396,7 +397,7 @@ def test_indexer_exit_cleans_up_once(monkeypatch): events = [] monkeypatch.setenv("JACKETT_API_KEY", "testkey") monkeypatch.setattr(helm.cli, "ensure_config", lambda: None) - monkeypatch.setattr(helm.cli, "load_config", lambda: {}) + monkeypatch.setattr(helm.cli, "load_settings", lambda: Settings.from_legacy({})) monkeypatch.setattr(oneshot, "spin_up_oneshot", lambda: events.append("start")) monkeypatch.setattr(oneshot, "teardown_oneshot", lambda: events.append("stop")) monkeypatch.setattr(indexer_manager, "JackettManager", lambda: SimpleNamespace(get_all_indexers=lambda: [])) diff --git a/tests/test_config_manager.py b/tests/test_config_manager.py index e781498..6b74ded 100644 --- a/tests/test_config_manager.py +++ b/tests/test_config_manager.py @@ -1,36 +1,4 @@ -import tempfile - -from helm.core.config_manager import CONTENT_PROFILES, NEGATIVE_KEYWORDS, load_config, save_config - - -def test_save_and_load_config(monkeypatch): - with tempfile.TemporaryDirectory() as tmpdirname: - monkeypatch.setenv("HELM_CONFIG_DIR", tmpdirname) - monkeypatch.delenv("JACKETT_API_KEY", raising=False) - config = {"indexers": ["yts"], "JACKETT_API_KEY": "12345"} - save_config(config) - loaded = load_config() - # Secrets must never persist inside config.json - assert "JACKETT_API_KEY" not in loaded - assert loaded["indexers"] == ["yts"] - - -def test_secrets_are_migrated_out_of_config(monkeypatch): - import os - - from helm.core.secret_manager import get_secret - - with tempfile.TemporaryDirectory() as tmpdirname: - monkeypatch.setenv("HELM_CONFIG_DIR", tmpdirname) - monkeypatch.delenv("JACKETT_API_KEY", raising=False) - save_config({"JACKETT_API_KEY": "abc123", "indexers": ["yts"]}) - loaded = load_config() - assert "JACKETT_API_KEY" not in loaded - assert get_secret("JACKETT_API_KEY") == "abc123" - # And it was persisted to the secrets file, not the config file - config_path = os.path.join(tmpdirname, "config.json") - with open(config_path) as f: - assert "JACKETT_API_KEY" not in f.read() +from helm.core.config_manager import CONTENT_PROFILES, NEGATIVE_KEYWORDS def test_negative_keywords_derived_from_other_categories(): diff --git a/tests/test_rss_fetcher.py b/tests/test_rss_fetcher.py index 8161bb4..c7ad348 100644 --- a/tests/test_rss_fetcher.py +++ b/tests/test_rss_fetcher.py @@ -67,10 +67,12 @@ def test_search_jackett_returns_empty_without_api_key(monkeypatch): def test_search_indexers_falls_back_to_lite_when_manager_returns_nothing(monkeypatch): - from helm.core import config_manager, lite_fetcher + from helm.core import lite_fetcher, settings from helm.core.rss_fetcher import TorrentItem - monkeypatch.setattr(config_manager, "load_config", lambda: {"INDEXER_MANAGER": "jackett"}) + monkeypatch.setattr( + settings, "load_settings", lambda: settings.Settings.from_legacy({"INDEXER_MANAGER": "jackett"}) + ) monkeypatch.setattr(rf, "search_jackett", lambda *a, **k: []) lite = TorrentItem("Ubuntu 24.04 Lite", "magnet:?xt=urn:btih:cafe", 5) @@ -83,10 +85,12 @@ def test_search_indexers_falls_back_to_lite_when_manager_returns_nothing(monkeyp def test_search_indexers_falls_back_to_lite_with_prowlarr_manager(monkeypatch): - from helm.core import config_manager, lite_fetcher + from helm.core import lite_fetcher, settings from helm.core.rss_fetcher import TorrentItem - monkeypatch.setattr(config_manager, "load_config", lambda: {"INDEXER_MANAGER": "prowlarr"}) + monkeypatch.setattr( + settings, "load_settings", lambda: settings.Settings.from_legacy({"INDEXER_MANAGER": "prowlarr"}) + ) monkeypatch.setattr(rf, "search_prowlarr", lambda *a, **k: []) monkeypatch.setattr(rf, "search_jackett", lambda *a, **k: []) diff --git a/tests/test_service_boundaries.py b/tests/test_service_boundaries.py index a1ba492..d0ef386 100644 --- a/tests/test_service_boundaries.py +++ b/tests/test_service_boundaries.py @@ -11,8 +11,9 @@ import helm.core.config_wizard as wizard import helm.core.oneshot as oneshot -from helm.core.config_manager import get_state_dir, load_config, save_config +from helm.core.config_manager import get_state_dir from helm.core.secret_manager import get_secret +from helm.core.settings import load_settings, remember def install_engine(tmp_path, monkeypatch, status): @@ -109,8 +110,8 @@ def answers(monkeypatch, values): def test_wizard_lite_choice_is_saved(monkeypatch): answers(monkeypatch, ["n"]) wizard.run_wizard() - assert load_config()["LITE_MODE_ONLY"] is True - save_config({"LITE_MODE_ONLY": False}) + assert load_settings().get("search.lite_only") is True + remember({"search.lite_only": False}) def test_wizard_without_a_terminal_exits_with_guidance(monkeypatch, capsys): @@ -129,14 +130,14 @@ def test_ensure_config_runs_wizard_only_when_settings_are_missing(monkeypatch): monkeypatch.setattr(wizard, "run_wizard", lambda: calls.append(1)) for key in ("JACKETT_URL", "QB_WEBUI", "QB_USERNAME", "JACKETT_API_KEY", "QB_PASSWORD"): monkeypatch.delenv(key, raising=False) - save_config({"LITE_MODE_ONLY": False}) + remember({"search.lite_only": False}) wizard.ensure_config() # Not a terminal: warn instead of blocking on a prompt. assert calls == [] monkeypatch.setattr(wizard.sys, "stdin", SimpleNamespace(isatty=lambda: True)) wizard.ensure_config() assert calls == [1] - save_config({"LITE_MODE_ONLY": True}) + remember({"search.lite_only": True}) wizard.ensure_config() assert calls == [1] - save_config({"LITE_MODE_ONLY": False}) + remember({"search.lite_only": False}) assert get_secret("QB_PASSWORD") is None diff --git a/tests/test_settings.py b/tests/test_settings.py new file mode 100644 index 0000000..e644ea3 --- /dev/null +++ b/tests/test_settings.py @@ -0,0 +1,436 @@ +import json +import os +import stat +import subprocess +import sys +from pathlib import Path + +import pytest + +from helm.core import settings as settings_module +from helm.core.secret_manager import get_secret +from helm.core.settings import ( + BY_PATH, + FIELDS, + ConfigError, + Settings, + active_config_file, + get_qb_url, + load_settings, + map_legacy, + parse_jsonc, + read_file, + remember, + render_toml, + report_config_file, + settings_schema, + shadowed_config_files, +) + +SRC = str(Path(__file__).resolve().parents[1] / "src") +TOML = """ +# comment +[search] +min_seeds = 7 +lite_workers = 2 +indexer_manager = "prowlarr" +lite_only = true + +[services] +jackett = "http://jackett.test:9117/" +qbittorrent_user = "pirate" +""" +JSONC = """ +// comment +{ + "search": { + "min_seeds": 7, /* inline */ + "lite_workers": 2, + "indexer_manager": "prowlarr", + "lite_only": true, + }, + "services": { + "jackett": "http://jackett.test:9117/", + "qbittorrent_user": "pirate", + }, +} +""" + + +@pytest.fixture +def config_dir(tmp_path, monkeypatch): + path = tmp_path / "config" + path.mkdir() + monkeypatch.setenv("HELM_CONFIG_DIR", str(path)) + monkeypatch.setenv("HELM_STATE_DIR", str(tmp_path / "state")) + for field in FIELDS: + if field.env: + monkeypatch.delenv(field.env, raising=False) + for key in ("JACKETT_API_KEY", "QB_PASSWORD"): + monkeypatch.delenv(key, raising=False) + return path + + +def snapshot(settings): + return {field.path: settings.get(field.path) for field in FIELDS} + + +def test_defaults_without_any_file(config_dir): + settings = load_settings() + assert settings.get("search.min_seeds") == 3 + assert settings.origin("search.min_seeds") == "default" + assert settings.path is None + assert list(config_dir.iterdir()) == [] + + +def test_toml_and_jsonc_load_identically(config_dir): + (config_dir / "config.toml").write_text(TOML) + from_toml = snapshot(load_settings()) + (config_dir / "config.toml").unlink() + (config_dir / "config.jsonc").write_text(JSONC) + from_jsonc = snapshot(load_settings()) + assert from_toml == from_jsonc + assert from_toml["search.min_seeds"] == 7 + assert from_toml["services.jackett"] == "http://jackett.test:9117" + + +def test_toml_wins_when_both_exist_and_files_never_merge(config_dir): + (config_dir / "config.toml").write_text("[search]\nmin_seeds = 1\n") + (config_dir / "config.jsonc").write_text('{"search": {"min_seeds": 9, "lite_workers": 2}}') + settings = load_settings() + assert settings.get("search.min_seeds") == 1 + assert settings.get("search.lite_workers") == 6 + assert active_config_file().endswith("config.toml") + assert [Path(path).name for path in shadowed_config_files()] == ["config.jsonc"] + + +def test_literal_art_is_preserved_in_toml(config_dir): + path = config_dir / "config.toml" + quotes = "'" * 3 + path.write_text("[logo]\nart = " + quotes + "\n _\\_/_\n" + quotes + "\n") + assert read_file(str(path)) == {"logo": {"art": " _\\_/_\n"}} + + +@pytest.mark.parametrize( + "text,expected", + [ + ('{"a": "http://x//y"}', {"a": "http://x//y"}), + ('{"a": "/* not a comment */"}', {"a": "/* not a comment */"}), + ('{"a": "quote \\" // still text"}', {"a": 'quote " // still text'}), + ('{"a": ",]"}', {"a": ",]"}), + ("[1, 2, ]", [1, 2]), + ('{"a": [1,],}', {"a": [1]}), + ("/* a\nb */ {}", {}), + ("{} // end", {}), + ], +) +def test_parse_jsonc(text, expected): + assert parse_jsonc(text) == expected + + +@pytest.mark.parametrize("text", ["{", "/* open", '{"a": 1,,}']) +def test_parse_jsonc_rejects_invalid_input(text): + with pytest.raises(ValueError): + parse_jsonc(text) + + +def test_jsonc_error_keeps_line_number(): + with pytest.raises(json.JSONDecodeError) as error: + parse_jsonc('/* one\ntwo */\n{"a" 1}') + assert error.value.lineno == 3 + + +@pytest.mark.parametrize( + "name,text,message", + [ + ("config.toml", "[search\n", "Invalid syntax"), + ("config.jsonc", "{", "Invalid syntax"), + ("config.jsonc", "[1]", "table of settings"), + ], +) +def test_broken_user_file_is_reported_and_left_alone(config_dir, name, text, message): + path = config_dir / name + path.write_text(text) + with pytest.raises(ConfigError, match=message): + load_settings() + assert path.read_text() == text + + +@pytest.mark.parametrize( + "text,message", + [ + ("[search]\nmin_seeds = -1\n", "at least 0"), + ('[search]\nmin_seeds = "3"\n', "whole number"), + ("[search]\nmin_seeds = true\n", "whole number"), + ("[search]\nlite_workers = 13\n", "at most 12"), + ('[search]\nlite_only = "yes"\n', "true or false"), + ('[search]\nindexer_manager = "other"\n', "one of"), + ('[search]\ndefault_type = "other"\n', "one of"), + ('[services]\njackett = "jackett:9117"\n', "http"), + ('[services]\nqbittorrent_user = ""\n', "non-empty"), + ], +) +def test_invalid_values_name_key_and_file(config_dir, text, message): + (config_dir / "config.toml").write_text(text) + with pytest.raises(ConfigError, match=message) as error: + load_settings() + assert "config.toml" in str(error.value) + + +def test_all_problems_are_reported_together(config_dir): + (config_dir / "config.toml").write_text('[search]\nmin_seeds = -1\nlite_only = "x"\n') + with pytest.raises(ConfigError) as error: + load_settings() + assert "search.min_seeds" in str(error.value) and "search.lite_only" in str(error.value) + + +def test_unknown_keys_are_kept_for_doctor(config_dir): + (config_dir / "config.toml").write_text("[search]\ntypo = 1\n[theme]\npreset = 'helm'\n") + assert sorted(load_settings().unknown) == ["search.typo", "theme.preset"] + + +def test_precedence_env_file_state_default(config_dir, monkeypatch): + path = "services.prowlarr" + remember({path: "http://state.test"}) + assert (load_settings().get(path), load_settings().origin(path)) == ("http://state.test", "state") + (config_dir / "config.toml").write_text('[services]\nprowlarr = "http://file.test"\n') + assert (load_settings().get(path), load_settings().origin(path)) == ("http://file.test", "file") + monkeypatch.setenv("PROWLARR_URL", "http://env.test/") + assert (load_settings().get(path), load_settings().origin(path)) == ("http://env.test", "env") + + +def test_empty_environment_value_is_unset(config_dir, monkeypatch): + monkeypatch.setenv("QB_WEBUI", "") + assert load_settings().origin("services.qbittorrent") == "default" + + +@pytest.mark.parametrize("text,expected", [("1", True), ("TRUE", True), ("yes", True), ("0", False), ("no", False)]) +def test_environment_booleans(config_dir, monkeypatch, text, expected): + monkeypatch.setenv("HELM_LITE_ONLY", text) + assert load_settings().get("search.lite_only") is expected + + +def test_invalid_environment_names_the_variable(config_dir, monkeypatch): + monkeypatch.setenv("QB_WEBUI", "not-a-url") + with pytest.raises(ConfigError, match="QB_WEBUI"): + load_settings() + monkeypatch.delenv("QB_WEBUI") + monkeypatch.setenv("HELM_LITE_WORKERS", "many") + with pytest.raises(ConfigError, match="HELM_LITE_WORKERS"): + load_settings() + + +def test_get_qb_url(config_dir, monkeypatch): + monkeypatch.setenv("QB_WEBUI", "http://qb.test/") + assert get_qb_url() == "http://qb.test" + + +def test_edits_are_seen_without_restarting(config_dir): + path = config_dir / "config.toml" + path.write_text("[search]\nmin_seeds = 1\n") + assert load_settings().get("search.min_seeds") == 1 + path.write_text("[search]\nmin_seeds = 22\n") + assert load_settings().get("search.min_seeds") == 22 + + +def test_repeated_loads_parse_once(config_dir, monkeypatch): + (config_dir / "config.toml").write_text("[search]\nmin_seeds = 1\n") + calls = [] + real = settings_module.read_file + monkeypatch.setattr(settings_module, "read_file", lambda path: calls.append(path) or real(path)) + for _ in range(5): + load_settings() + assert len(calls) == 1 + + +def test_remember_is_private_keeps_user_file_and_reports_shadowing(config_dir): + user = config_dir / "config.toml" + original = "# keep me\n[search]\nmin_seeds = 9\n" + user.write_text(original) + assert remember({"search.min_seeds": 4, "search.lite_only": True}) == ["search.min_seeds"] + assert user.read_text() == original + settings = load_settings() + assert settings.get("search.min_seeds") == 9 + assert settings.get("search.lite_only") is True + state = Path(settings_module.state_file()) + assert stat.S_IMODE(state.stat().st_mode) == 0o600 + assert not [item for item in state.parent.iterdir() if item.suffix == ".tmp"] + + +def test_remember_validates(config_dir): + with pytest.raises(KeyError): + remember({"search.nope": 1}) + with pytest.raises(ValueError): + remember({"search.min_seeds": "x"}) + + +def test_damaged_state_does_not_stop_startup(config_dir): + state = Path(settings_module.state_file()) + state.parent.mkdir(parents=True) + state.write_text("{") + assert load_settings().get("search.min_seeds") == 3 + remember({"search.min_seeds": 5}) + assert load_settings().get("search.min_seeds") == 5 + state.write_text('{"search.min_seeds": "bad", "other": 1}') + assert load_settings().origin("search.min_seeds") == "default" + + +def test_map_legacy_drops_defaults_invalid_values_and_retired_keys(): + assert map_legacy( + { + "min_seeds": 3, + "LITE_MODE_ONLY": False, + "QB_USERNAME": "pirate", + "JACKETT_URL": "http://localhost:9117", + "INDEXER_MANAGER": "unknown", + "qualities": ["1080p"], + "EXECUTION_MODE": "native", + "indexers": ["yts"], + } + ) == {"services.qbittorrent_user": "pirate", "services.jackett": "http://localhost:9117"} + + +def test_render_toml_round_trips(tmp_path): + values = {"search.min_seeds": 5, "search.lite_only": True, "services.jackett": 'http://x/"q"'} + path = tmp_path / "config.toml" + path.write_text(render_toml(values)) + assert read_file(str(path)) == { + "search": {"min_seeds": 5, "lite_only": True}, + "services": {"jackett": 'http://x/"q"'}, + } + + +def test_migration_creates_toml_once_and_keeps_original(config_dir, capsys): + legacy = config_dir / "config.json" + original = json.dumps({"min_seeds": 8, "QB_WEBUI": "http://localhost:8080", "qualities": ["x"]}) + legacy.write_text(original) + settings = load_settings() + assert settings.get("search.min_seeds") == 8 + assert settings.get("services.qbittorrent") == "http://localhost:8080" + assert settings.origin("search.min_seeds") == "file" + assert legacy.read_text() == original + assert (config_dir / "config.json.pre-toml.bak").read_text() == original + assert "Migrated" in capsys.readouterr().err + + target = config_dir / "config.toml" + target.write_text("[search]\nmin_seeds = 2\n") + legacy.write_text(json.dumps({"min_seeds": 99})) + assert load_settings().get("search.min_seeds") == 2 + assert target.read_text() == "[search]\nmin_seeds = 2\n" + + +def test_migration_moves_secrets_out_of_config_json(config_dir): + legacy = config_dir / "config.json" + legacy.write_text(json.dumps({"JACKETT_API_KEY": "abc123", "min_seeds": 8})) + load_settings() + assert get_secret("JACKETT_API_KEY") == "abc123" + assert "abc123" not in legacy.read_text() + assert "abc123" not in (config_dir / "config.toml").read_text() + + +@pytest.mark.parametrize("text", ["", "{}", '{"min_seeds": 3, "qualities": []}']) +def test_nothing_to_migrate_creates_no_file(config_dir, text): + (config_dir / "config.json").write_text(text) + assert load_settings().path is None + assert not (config_dir / "config.toml").exists() + + +def test_corrupt_legacy_file_is_backed_up_once(config_dir, capsys): + (config_dir / "config.json").write_text("{broken") + assert load_settings().get("search.min_seeds") == 3 + assert load_settings().get("search.min_seeds") == 3 + assert (config_dir / "config.json.bak").read_text() == "{broken" + assert capsys.readouterr().err.count("corrupted") == 1 + + +def test_setup_rerun_before_migration_is_honoured(config_dir): + (config_dir / "config.json").write_text('{"INDEXER_MANAGER": "prowlarr"}') + assert load_settings().get("search.indexer_manager") == "prowlarr" + + +def test_report_config_file_prefers_active_file(config_dir): + assert report_config_file().endswith("config.json") + (config_dir / "config.jsonc").write_text("{}") + assert report_config_file().endswith("config.jsonc") + + +def test_settings_from_legacy_and_unknown_origin(): + settings = Settings.from_legacy({"min_seeds": 9}) + assert settings.get("search.min_seeds") == 9 + assert settings.origin("search.min_seeds") == "file" + with pytest.raises(KeyError): + settings.origin("search.nope") + + +def test_schema_covers_every_field_and_its_defaults(): + schema = settings_schema() + for field in FIELDS: + section, key = field.path.split(".", 1) + entry = schema["properties"][section]["properties"][key] + assert entry["default"] == field.default + assert schema["properties"]["search"]["properties"]["lite_workers"]["maximum"] == 12 + assert "prowlarr" in schema["properties"]["search"]["properties"]["indexer_manager"]["enum"] + assert BY_PATH["services.jackett"].default == "http://localhost:19117" + + +def helm(config_dir, *arguments): + state = str(config_dir.parent / "state") + environment = { + **os.environ, + "PYTHONPATH": SRC, + "HELM_CONFIG_DIR": str(config_dir), + "HELM_STATE_DIR": state, + } + return subprocess.run( + [sys.executable, "-m", "helm.cli", *arguments], + env=environment, + stdin=subprocess.DEVNULL, + capture_output=True, + text=True, + timeout=30, + ) + + +def test_broken_config_gives_clean_error_through_cli(config_dir): + (config_dir / "config.toml").write_text("[search]\nmin_seeds = -1\n") + result = helm(config_dir, "paths") + assert result.returncode == 1 + assert "search.min_seeds" in result.stderr + assert "Traceback" not in result.stderr + + +def test_console_entry_point_reports_config_errors_cleanly(config_dir): + (config_dir / "config.toml").write_text("[search\n") + environment = { + **os.environ, + "PYTHONPATH": SRC, + "HELM_CONFIG_DIR": str(config_dir), + "HELM_STATE_DIR": str(config_dir.parent / "state"), + } + code = "import sys, helm.cli; sys.argv = ['helm-torrent', 'status']; helm.cli.main()" + result = subprocess.run([sys.executable, "-c", code], env=environment, capture_output=True, text=True, timeout=30) + assert result.returncode == 1 + assert "Invalid syntax" in result.stderr + assert "Traceback" not in result.stderr + + +def test_config_worker_count_reaches_the_process(config_dir): + (config_dir / "config.toml").write_text("[search]\nlite_workers = 3\n") + code = ( + "import os, sys\n" + "sys.argv = ['helm-torrent', 'paths']\n" + "import helm.cli\n" + "try:\n" + " helm.cli.main()\n" + "except SystemExit:\n" + " pass\n" + "print(os.environ['HELM_LITE_WORKERS'])\n" + ) + environment = { + **{key: value for key, value in os.environ.items() if key != "HELM_LITE_WORKERS"}, + "PYTHONPATH": SRC, + "HELM_CONFIG_DIR": str(config_dir), + "HELM_STATE_DIR": str(config_dir.parent / "state"), + } + result = subprocess.run([sys.executable, "-c", code], env=environment, capture_output=True, text=True, timeout=30) + assert result.stdout.strip().endswith("3"), result.stderr diff --git a/uninstall.sh b/uninstall.sh index fc2dca5..429a8ba 100755 --- a/uninstall.sh +++ b/uninstall.sh @@ -8,7 +8,7 @@ Usage: uninstall.sh [OPTIONS] Preview by default. Select components and pass --yes to remove them. --containers Remove this Compose project's containers and networks --volumes Also delete labeled named volumes and ALL their contents - --config Remove config.json and secrets.env; preserve other files + --config Remove config files and secrets.env; preserve other files --state Remove known service data, generated Compose files and logs --package Uninstall helm-torrent using HELM_PYTHON (default: python3) --engine docker|podman Container engine (otherwise detected) @@ -111,13 +111,13 @@ if $remove_config; then [[ ! -L "$config_dir" ]] || die "Configuration directory must not be a symlink" config_dir="$(canonical_path "$config_dir")" check_path "$config_dir" - paths+=("$config_dir/config.json" "$config_dir/secrets.env") + paths+=("$config_dir/config.json" "$config_dir/config.toml" "$config_dir/config.jsonc" "$config_dir/secrets.env") fi if $remove_state; then [[ ! -L "$state_dir" ]] || die "State directory must not be a symlink" state_dir="$(canonical_path "$state_dir")" check_path "$state_dir" - for name in docker-compose.yml .env.docker jackett prowlarr qbittorrent flaresolverr gluetun logs; do + for name in docker-compose.yml .env.docker settings.json jackett prowlarr qbittorrent flaresolverr gluetun logs; do paths+=("$state_dir/$name") done for path in "$state_dir"/helm.log*; do From 8daf58a8f5b2590ac9c96667a0c4b83c1b8a6cec Mon Sep 17 00:00:00 2001 From: Piratebird <141295458+Piratebird@users.noreply.github.com> Date: Mon, 2 Nov 2026 13:25:54 +0200 Subject: [PATCH 03/18] :shipit: feat(config): add config init, edit, doctor and show commands - Add helm-torrent config init, edit, doctor and show --origin - Generate a commented template from the settings fields in TOML or JSONC - Check syntax, values, unknown keys, ignored files, secrets.env mode, directories and services - Keep config commands working on a broken file by skipping the early settings load - Add resolve_settings to collect problems without raising or migrating - Hide passwords in URLs and never print secrets - Add subprocess tests with a fake editor and a real local HTTP server --- CHANGELOG.md | 1 + README.md | 11 + src/helm/cli.py | 27 +- src/helm/core/config_commands.py | 316 +++++++++++++++++++++++ src/helm/core/settings.py | 25 +- tests/test_config_commands.py | 419 +++++++++++++++++++++++++++++++ 6 files changed, 787 insertions(+), 12 deletions(-) create mode 100644 src/helm/core/config_commands.py create mode 100644 tests/test_config_commands.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 7ebfcb7..5171d3f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ All notable changes to this project will be documented in this file. - Respect the configured download directory and reject unknown flags, blank queries, and invalid content types. ### Added +- `helm-torrent config init`, `edit`, `doctor` and `show --origin`. They run even when the config file is broken. `doctor` checks syntax, values, unknown keys, ignored files, `secrets.env` permissions, writable directories and service reachability, and never prints secrets. - Layered settings from `config.toml` or `config.jsonc`, with validation and a shared JSON Schema. Existing `config.json` values migrate once, and the original file stays in place. If both new files exist, `config.toml` is used. - Durable job queue with process-isolated workers, crash recovery, cancellation and a completed-file catalog. - `helm-torrent download`, `watch`, `serve`, `files`, `attach` and `daemon`, plus `--daemon` and `--session`. diff --git a/README.md b/README.md index 4e3b944..7d76ff6 100644 --- a/README.md +++ b/README.md @@ -190,6 +190,17 @@ qbittorrent_downloads_root = "/downloads" The first run creates `config.toml` from any non-default values in an older `config.json`, moves legacy secrets into `secrets.env`, and leaves `config.json` in place with a `.pre-toml.bak` copy. After that, `config.json` is ignored. +Manage the file with the `config` commands. They also work when the file is broken, so you can fix it: + +```bash +helm-torrent config init # Write a commented config.toml once (--format jsonc for JSONC) +helm-torrent config edit # Open it in $VISUAL or $EDITOR, then validate it +helm-torrent config doctor # Check values, files, permissions, directories and services +helm-torrent config show --origin # Print every value and whether it came from env, file, state or default +``` + +`config init` never overwrites an existing file. `config doctor` exits with status 1 on errors. Unreachable services only produce warnings, and the service checks are skipped when `search.lite_only` is set. Neither command prints secrets, and passwords in URLs are shown as `***`. + ## Usage Run `helm-torrent` for the interactive CLI. Use subcommands for scripted searches and administration: diff --git a/src/helm/cli.py b/src/helm/cli.py index efabc86..e85e96b 100644 --- a/src/helm/cli.py +++ b/src/helm/cli.py @@ -217,6 +217,10 @@ def build_parser(): daemon_parser.add_argument("action", choices=["status", "stop"]) daemon_parser.add_argument("id", nargs="?") + from helm.core.config_commands import add_parser as add_config_parser + + add_config_parser(subparsers, [base_parser]) + return parser @@ -254,14 +258,17 @@ def _parse_args(parser): if getattr(args, "dl_dir", None): os.environ["HELM_DL_DIR"] = os.path.abspath(args.dl_dir) - requested = getattr(args, "lite_workers", None) - if requested is None and "HELM_LITE_WORKERS" not in os.environ: - requested = load_settings().get("search.lite_workers") - try: - workers = worker_count(requested) - except ValueError as error: - parser.error(str(error)) - os.environ["HELM_LITE_WORKERS"] = str(workers) + # Config commands must run on a broken file and report true origins, so they + # neither load settings early nor export the worker count. + if args.command != "config": + requested = getattr(args, "lite_workers", None) + if requested is None and "HELM_LITE_WORKERS" not in os.environ: + requested = load_settings().get("search.lite_workers") + try: + workers = worker_count(requested) + except ValueError as error: + parser.error(str(error)) + os.environ["HELM_LITE_WORKERS"] = str(workers) load_dotenv(get_secrets_file()) configure_logging() @@ -411,6 +418,10 @@ def run(): args = _parse_args(parser) if _dispatch_background(args, parser): return + if args.command == "config": + from helm.core.config_commands import run as run_config + + raise SystemExit(run_config(args)) if args.command in ("watch", "serve", "files", "download"): raise SystemExit(_run_headless(args, parser)) diff --git a/src/helm/core/config_commands.py b/src/helm/core/config_commands.py new file mode 100644 index 0000000..1cfd53d --- /dev/null +++ b/src/helm/core/config_commands.py @@ -0,0 +1,316 @@ +"""The `helm-torrent config` commands: init, edit, doctor and show. + +These commands must keep working when the config file is broken, so they never +rely on load_settings() succeeding, except `show`, which reports the error. +""" + +import json +import os +import shlex +import stat +import subprocess +import sys +import urllib.error +import urllib.request +from urllib.parse import urlsplit, urlunsplit + +from helm.core.config_manager import get_config_dir, get_dl_dir, get_state_dir +from helm.core.secret_manager import get_secrets_file +from helm.core.settings import ( + FIELDS, + USER_FILES, + ConfigError, + active_config_file, + atomic_write, + load_settings, + map_legacy, + migrate_legacy, + read_file, + resolve_settings, + shadowed_config_files, +) + +DESCRIPTIONS = { + "search.min_seeds": "Hide results with fewer seeders than this.", + "search.lite_workers": "Maximum concurrent Lite source processes, 1 to 12.", + "search.default_type": "Content profile used when none is given.", + "search.indexer_manager": "Which manager to search: jackett, prowlarr or both.", + "search.lite_only": "Always use Lite mode and skip the indexer managers.", + "services.jackett": "Jackett web address.", + "services.prowlarr": "Prowlarr web address.", + "services.qbittorrent": "qBittorrent Web UI address.", + "services.qbittorrent_user": "qBittorrent user name. The password stays in secrets.env.", + "services.qbittorrent_downloads_root": "Download path as qBittorrent sees it, such as a container mount.", +} +FORMATS = {"toml": USER_FILES[0], "jsonc": USER_FILES[1]} +PROBE_TIMEOUT = 2.0 + + +def add_parser(subparsers, parents): + """Register `config` and its required nested actions.""" + config_parser = subparsers.add_parser("config", help="Create, edit, check and show settings", parents=parents) + actions = config_parser.add_subparsers(dest="config_action", metavar="") + actions.required = True + init_parser = actions.add_parser("init", help="Create a commented config file once", parents=parents) + init_parser.add_argument("--format", choices=sorted(FORMATS), default="toml", help="File format (default: toml)") + actions.add_parser("edit", help="Open the config file in $VISUAL or $EDITOR", parents=parents) + actions.add_parser("doctor", help="Check settings, paths and service reachability", parents=parents) + show_parser = actions.add_parser("show", help="Print every setting", parents=parents) + show_parser.add_argument("--origin", action="store_true", help="Also show where each value came from") + + +def run(args): + """Run one config action and return its exit code.""" + if args.config_action == "init": + return init(args.format) + if args.config_action == "show": + return show(args.origin) + return edit() if args.config_action == "edit" else doctor() + + +def _sections(): + sections: dict = {} + for field in FIELDS: + section, key = field.path.split(".", 1) + sections.setdefault(section, []).append((key, field)) + return sections + + +def render_template(file_format): + """Return a config file where every setting is commented out at its default.""" + header = [ + "Helm settings. Helm never rewrites this file, so edit it freely.", + "Every value below is the default. Uncomment a line to change it.", + "Environment variables override this file. Secrets belong in secrets.env.", + ] + if file_format == "toml": + lines = ["# " + line for line in header] + [""] + for section, items in _sections().items(): + lines.append(f"[{section}]") + for key, field in items: + lines.append("# " + DESCRIPTIONS[field.path]) + lines.append(f"# {key} = {json.dumps(field.default)}") + lines.append("") + return "\n".join(lines) + lines = ["// " + line for line in header] + ["{"] + for section, items in _sections().items(): + lines.append(f' "{section}": {{') + for key, field in items: + lines.append(" // " + DESCRIPTIONS[field.path]) + lines.append(f' // "{key}": {json.dumps(field.default)},') + lines.append(" },") + lines.append("}") + return "\n".join(lines) + "\n" + + +def _existing_user_files(): + paths = [os.path.join(get_config_dir(), name) for name in USER_FILES] + return [path for path in paths if os.path.exists(path)] + + +def init(file_format="toml"): + migrate_legacy() + existing = _existing_user_files() + if existing: + print(f"[error] {existing[0]} already exists. Use `helm-torrent config edit` to change it.", file=sys.stderr) + return 1 + path = os.path.join(get_config_dir(), FORMATS[file_format]) + atomic_write(path, render_template(file_format)) + print(f"Created {path}") + return 0 + + +def _editor_command(): + for name in ("VISUAL", "EDITOR"): + value = os.environ.get(name, "").strip() + if value: + return shlex.split(value) + return None + + +def edit(): + command = _editor_command() + if not command: + print("[error] Set $VISUAL or $EDITOR to choose an editor.", file=sys.stderr) + return 1 + path = active_config_file() + if path is None: + code = init("toml") + if code: + return code + path = active_config_file() + try: + result = subprocess.run([*command, path]) + except OSError as error: + print(f"[error] Cannot start {command[0]}: {error}", file=sys.stderr) + return 1 + if result.returncode: + print(f"[error] {command[0]} exited with status {result.returncode}", file=sys.stderr) + return result.returncode + current, problems = resolve_settings() + report = Report() + report.check_file(current, problems) + report.print() + return report.exit_code() + + +def redact_url(value): + """Hide user information such as passwords in a URL.""" + parts = urlsplit(value) + if "@" not in parts.netloc: + return value + host = parts.netloc.rsplit("@", 1)[1] + return urlunsplit((parts.scheme, "***@" + host, parts.path, parts.query, parts.fragment)) + + +def _display(field, value): + if field.kind == "url": + value = redact_url(value) + return json.dumps(value) + + +class Report: + """Collect [ok], [warn] and [error] lines.""" + + def __init__(self): + self.lines = [] + + def add(self, level, message): + self.lines.append((level, message)) + + def print(self): + for level, message in self.lines: + print(f"[{level}] {message}") + + def exit_code(self): + return 1 if any(level == "error" for level, _message in self.lines) else 0 + + def check_file(self, settings, problems): + if settings.path: + if problems: + for problem in problems: + self.add("error", problem) + else: + self.add("ok", f"{settings.path} is valid") + else: + self.add("ok", "No config file; using defaults. Create one with `helm-torrent config init`.") + for problem in problems: + self.add("error", problem) + for key in settings.unknown: + self.add("warn", f"Unknown setting {key} is ignored") + + +def _check_shadowed(report): + for path in shadowed_config_files(): + report.add("warn", f"{path} is ignored because {active_config_file()} exists. Files are never merged.") + + +def _check_legacy(report, settings): + path = os.path.join(get_config_dir(), "config.json") + if not os.path.isfile(path): + return + try: + values = map_legacy(read_file(path)) + except ConfigError: + report.add("warn", f"{path} cannot be parsed and is ignored") + return + if not values: + return + if settings.path is None: + report.add("warn", f"{path} has settings that the next run migrates to config.toml") + return + differing = sorted(key for key, value in values.items() if settings.get(key) != value) + if differing: + report.add( + "warn", + f"{path} is ignored for settings; set {', '.join(differing)} in {os.path.basename(settings.path)}", + ) + + +def _check_secrets(report): + path = get_secrets_file() + if not os.path.isfile(path): + report.add("ok", "No secrets.env yet") + return + if os.name != "posix": + return + mode = stat.S_IMODE(os.stat(path).st_mode) + if mode & 0o077: + report.add("warn", f"{path} has mode {mode:04o}; run `chmod 600 {shlex.quote(path)}`") + else: + report.add("ok", f"{path} is private ({mode:04o})") + + +def _nearest_existing(path): + while not os.path.exists(path): + parent = os.path.dirname(path) + if parent == path: + break + path = parent + return path + + +def _check_directory(report, label, path): + existing = _nearest_existing(os.path.abspath(path)) + writable = os.path.isdir(existing) and os.access(existing, os.W_OK | os.X_OK) + if not writable: + report.add("error", f"{label} {path} is not writable") + elif existing == os.path.abspath(path): + report.add("ok", f"{label} {path} is writable") + else: + report.add("ok", f"{label} {path} will be created") + + +def probe(url, timeout=PROBE_TIMEOUT): + """Return None when a server answers at url, or a short reason when not.""" + try: + with urllib.request.urlopen(url, timeout=timeout): + return None + except urllib.error.HTTPError: + # Any HTTP answer, such as 401 from a login page, proves reachability. + return None + except (urllib.error.URLError, OSError, ValueError) as error: + reason = getattr(error, "reason", error) + return str(reason) or type(error).__name__ + + +def _check_services(report, settings): + if settings.get("search.lite_only"): + report.add("ok", "Service checks skipped because search.lite_only is set") + return + manager = settings.get("search.indexer_manager") + names = [name for name in ("jackett", "prowlarr") if manager in (name, "both")] + for name in [*names, "qbittorrent"]: + url = settings.get(f"services.{name}") + reason = probe(url) + shown = redact_url(url) + if reason is None: + report.add("ok", f"{name} answers at {shown}") + else: + report.add("warn", f"{name} is not reachable at {shown}: {reason}") + + +def doctor(): + settings, problems = resolve_settings() + report = Report() + report.check_file(settings, problems) + _check_shadowed(report) + _check_legacy(report, settings) + _check_secrets(report) + _check_directory(report, "Download directory", get_dl_dir()) + _check_directory(report, "State directory", get_state_dir()) + _check_services(report, settings) + report.print() + return report.exit_code() + + +def show(with_origin=False): + current = load_settings() + print(f"# Config file: {current.path or 'none, using defaults'}") + width = max(len(field.path) for field in FIELDS) + for field in FIELDS: + line = f"{field.path.ljust(width)} = {_display(field, current.get(field.path))}" + if with_origin: + line += f" ({current.origin(field.path)})" + print(line) + return 0 diff --git a/src/helm/core/settings.py b/src/helm/core/settings.py index ccac4a3..63ed534 100644 --- a/src/helm/core/settings.py +++ b/src/helm/core/settings.py @@ -334,6 +334,18 @@ def _load_state(): def load_settings(): """Resolve settings: environment, then config file, then state, then defaults.""" migrate_legacy() + settings, problems = resolve_settings(strict=True) + if problems: + raise ConfigError(f"Invalid settings ({settings.path or 'environment'}): " + "; ".join(problems)) + return settings + + +def resolve_settings(strict=False): + """Resolve settings without migrating, and return them with every problem found. + + Invalid values are skipped, so the result holds what would be used if they + were removed. With strict=True a file that cannot be parsed raises instead. + """ values = {} origins = {} for path, value in _load_state().items(): @@ -343,8 +355,15 @@ def load_settings(): active = active_config_file() unknown = [] problems = [] + data = {} if active: - for path, value in _load_cached(active).items(): + try: + data = _load_cached(active) + except ConfigError as error: + if strict: + raise + problems.append(str(error)) + for path, value in data.items(): field = BY_PATH.get(path) if field is None: unknown.append(path) @@ -364,9 +383,7 @@ def load_settings(): except ValueError as error: problems.append(f"{field.env} {error}") - if problems: - raise ConfigError(f"Invalid settings ({active or 'environment'}): " + "; ".join(problems)) - return Settings(values, origins, active, unknown) + return Settings(values, origins, active, unknown), problems def remember(updates): diff --git a/tests/test_config_commands.py b/tests/test_config_commands.py new file mode 100644 index 0000000..f33bb9d --- /dev/null +++ b/tests/test_config_commands.py @@ -0,0 +1,419 @@ +import http.server +import os +import shlex +import socket +import stat +import subprocess +import sys +import threading +from pathlib import Path + +import pytest + +from helm.core.config_commands import DESCRIPTIONS, redact_url, render_template +from helm.core.settings import FIELDS, flatten, load_settings, parse_jsonc, read_file + +SRC = str(Path(__file__).resolve().parents[1] / "src") +SCRUBBED = {field.env for field in FIELDS if field.env} | { + "VISUAL", + "EDITOR", + "QB_PASSWORD", + "JACKETT_API_KEY", + "PROWLARR_API_KEY", +} + + +@pytest.fixture +def home(tmp_path, monkeypatch): + """Private config, state and download directories, with no inherited settings.""" + paths = { + "HELM_CONFIG_DIR": tmp_path / "config", + "HELM_STATE_DIR": tmp_path / "state", + "HELM_DL_DIR": tmp_path / "downloads", + } + paths["HELM_CONFIG_DIR"].mkdir() + for key, value in paths.items(): + monkeypatch.setenv(key, str(value)) + for key in SCRUBBED: + monkeypatch.delenv(key, raising=False) + return tmp_path + + +def helm(*arguments, **extra_env): + environment = {key: value for key, value in os.environ.items() if key not in SCRUBBED} + environment["PYTHONPATH"] = SRC + environment.update(extra_env) + return subprocess.run( + [sys.executable, "-m", "helm.cli", "config", *arguments], + env=environment, + stdin=subprocess.DEVNULL, + capture_output=True, + text=True, + timeout=60, + ) + + +def config_file(home, name="config.toml"): + return home / "config" / name + + +def lines_with(output, level): + return [line for line in output.splitlines() if line.startswith(f"[{level}]")] + + +@pytest.fixture +def http_server(): + """A real local HTTP server that answers every request with 401.""" + + class Handler(http.server.BaseHTTPRequestHandler): + def do_GET(self): + self.send_response(401) + self.end_headers() + + def log_message(self, *args): + pass + + server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + yield f"http://127.0.0.1:{server.server_address[1]}" + server.shutdown() + server.server_close() + + +def closed_port_url(): + with socket.socket() as sock: + sock.bind(("127.0.0.1", 0)) + port = sock.getsockname()[1] + return f"http://127.0.0.1:{port}" + + +# Template + + +@pytest.mark.parametrize("file_format", ["toml", "jsonc"]) +def test_template_parses_and_yields_only_defaults(home, file_format): + name = "config." + file_format + path = config_file(home, name) + path.write_text(render_template(file_format)) + assert flatten(read_file(str(path))) == {} + settings = load_settings() + assert settings.path == str(path) + for field in FIELDS: + assert settings.get(field.path) == field.default + assert settings.origin(field.path) == "default" + + +@pytest.mark.parametrize("file_format", ["toml", "jsonc"]) +def test_template_documents_every_field(file_format): + text = render_template(file_format) + for field in FIELDS: + assert DESCRIPTIONS[field.path] in text + assert field.path.split(".", 1)[1] in text + + +def test_uncommented_jsonc_template_line_takes_effect(): + text = render_template("jsonc").replace('// "min_seeds": 3,', '"min_seeds": 9,') + assert parse_jsonc(text)["search"]["min_seeds"] == 9 + + +# init + + +@pytest.mark.parametrize("file_format", ["toml", "jsonc"]) +def test_init_creates_private_template(home, file_format): + result = helm("init", "--format", file_format) + assert result.returncode == 0, result.stderr + path = config_file(home, "config." + file_format) + assert str(path) in result.stdout + assert path.read_text() == render_template(file_format) + if os.name == "posix": + assert stat.S_IMODE(path.stat().st_mode) == 0o600 + + +def test_init_refuses_to_overwrite_any_config_file(home): + path = config_file(home, "config.jsonc") + path.write_text('{"search": {"min_seeds": 5}}') + result = helm("init") + assert result.returncode == 1 + assert "already exists" in result.stderr + assert path.read_text() == '{"search": {"min_seeds": 5}}' + assert not config_file(home).exists() + + +def test_init_migrates_legacy_config_first(home): + (home / "config" / "config.json").write_text('{"min_seeds": 8}') + result = helm("init") + assert result.returncode == 1 + assert "min_seeds = 8" in config_file(home).read_text() + + +def test_config_requires_an_action(home): + result = helm() + assert result.returncode == 2 + assert "" in result.stderr + + +# edit + + +def fake_editor(home, body, exit_code=0): + script = home / "fake editor.py" + script.write_text( + "import sys\n" + "flag, path = sys.argv[1], sys.argv[2]\n" + "assert flag == '--wait'\n" + f"open(path, 'w').write({body!r})\n" + f"sys.exit({exit_code})\n" + ) + return f"{shlex.quote(sys.executable)} {shlex.quote(str(script))} --wait" + + +def test_edit_creates_file_runs_editor_without_shell_and_validates(home): + editor = fake_editor(home, "[search]\nmin_seeds = 4\n") + result = helm("edit", EDITOR=editor) + assert result.returncode == 0, result.stderr + assert config_file(home).read_text() == "[search]\nmin_seeds = 4\n" + assert lines_with(result.stdout, "ok") + assert not lines_with(result.stdout, "error") + + +def test_edit_prefers_visual_over_editor(home): + visual = fake_editor(home, "[search]\nmin_seeds = 6\n") + result = helm("edit", VISUAL=visual, EDITOR="/nonexistent-editor") + assert result.returncode == 0, result.stderr + assert "min_seeds = 6" in config_file(home).read_text() + + +def test_edit_reports_invalid_values(home): + editor = fake_editor(home, "[search]\nlite_workers = 99\nmystery = 1\n") + result = helm("edit", EDITOR=editor) + assert result.returncode == 1 + assert any("search.lite_workers" in line for line in lines_with(result.stdout, "error")) + assert any("search.mystery" in line for line in lines_with(result.stdout, "warn")) + + +def test_edit_opens_a_broken_file(home): + config_file(home).write_text("[search\n") + editor = fake_editor(home, "[search]\n") + result = helm("edit", EDITOR=editor) + assert result.returncode == 0, result.stderr + assert config_file(home).read_text() == "[search]\n" + + +def test_edit_passes_on_editor_failure(home): + editor = fake_editor(home, "", exit_code=3) + result = helm("edit", EDITOR=editor) + assert result.returncode == 3 + assert "status 3" in result.stderr + + +def test_edit_without_editor_explains(home): + result = helm("edit") + assert result.returncode == 1 + assert "$EDITOR" in result.stderr + assert not config_file(home).exists() + + +def test_edit_reports_missing_editor_program(home): + result = helm("edit", EDITOR="/nonexistent/editor") + assert result.returncode == 1 + assert "Cannot start" in result.stderr + + +# doctor + + +def test_doctor_healthy_setup_with_reachable_services(home, http_server): + config_file(home).write_text( + f'[search]\nindexer_manager = "both"\n[services]\n' + f'jackett = "{http_server}"\nprowlarr = "{http_server}"\nqbittorrent = "{http_server}"\n' + ) + secrets = home / "config" / "secrets.env" + secrets.write_text("QB_PASSWORD=hunter2-very-secret\n") + secrets.chmod(0o600) + result = helm("doctor") + assert result.returncode == 0, result.stdout + result.stderr + assert lines_with(result.stdout, "warn") == [] + assert len([line for line in result.stdout.splitlines() if "answers at" in line]) == 3 + assert "hunter2" not in result.stdout + result.stderr + + +def test_doctor_warns_but_passes_for_unreachable_service(home): + config_file(home).write_text(f'[services]\nqbittorrent = "{closed_port_url()}"\n') + result = helm("doctor") + assert result.returncode == 0 + assert any("qbittorrent is not reachable" in line for line in lines_with(result.stdout, "warn")) + + +def test_doctor_skips_services_in_lite_only_mode(home): + config_file(home).write_text(f'[search]\nlite_only = true\n[services]\njackett = "{closed_port_url()}"\n') + result = helm("doctor") + assert result.returncode == 0 + assert "skipped" in result.stdout + assert "not reachable" not in result.stdout + + +def test_doctor_reports_syntax_error_without_traceback(home): + config_file(home).write_text("[search\n") + result = helm("doctor") + assert result.returncode == 1 + assert any("Invalid syntax" in line for line in lines_with(result.stdout, "error")) + assert "Traceback" not in result.stderr + assert "Download directory" in result.stdout + + +def test_doctor_reports_bad_values_and_environment(home): + config_file(home).write_text("[search]\nmin_seeds = -1\n") + result = helm("doctor", HELM_LITE_WORKERS="50") + assert result.returncode == 1 + errors = "\n".join(lines_with(result.stdout, "error")) + assert "search.min_seeds" in errors + assert "HELM_LITE_WORKERS" in errors + + +def test_doctor_warns_about_unknown_shadowed_and_ignored_files(home): + config_file(home).write_text("[search]\nmin_seeds = 2\nextra = true\n") + config_file(home, "config.jsonc").write_text("{}") + (home / "config" / "config.json").write_text('{"min_seeds": 9}') + result = helm("doctor", HELM_LITE_ONLY="1") + assert result.returncode == 0 + warnings = "\n".join(lines_with(result.stdout, "warn")) + assert "search.extra" in warnings + assert "config.jsonc is ignored" in warnings + assert "config.json is ignored for settings; set search.min_seeds" in warnings + + +def test_doctor_warns_about_open_secrets_file(home): + secrets = home / "config" / "secrets.env" + secrets.write_text("QB_PASSWORD=do-not-print-me\n") + secrets.chmod(0o644) + result = helm("doctor", HELM_LITE_ONLY="1") + assert result.returncode == 0 + assert any("chmod 600" in line for line in lines_with(result.stdout, "warn")) + assert "do-not-print-me" not in result.stdout + result.stderr + + +@pytest.mark.skipif(os.name != "posix" or os.geteuid() == 0, reason="needs POSIX permissions without root") +def test_doctor_fails_for_unwritable_download_directory(home): + locked = home / "locked" + locked.mkdir() + locked.chmod(0o500) + try: + result = helm("doctor", HELM_DL_DIR=str(locked / "downloads"), HELM_LITE_ONLY="1") + finally: + locked.chmod(0o700) + assert result.returncode == 1 + assert any("Download directory" in line for line in lines_with(result.stdout, "error")) + + +def test_doctor_redacts_credentials_in_urls(home): + config_file(home).write_text(f'[services]\nqbittorrent = "http://user:pa55word@{closed_port_url()[7:]}"\n') + result = helm("doctor") + assert "pa55word" not in result.stdout + result.stderr + assert "***@127.0.0.1" in result.stdout + + +# show + + +def test_show_lists_values_and_origins(home): + config_file(home).write_text("[search]\nmin_seeds = 4\n") + state = home / "state" + state.mkdir() + (state / "settings.json").write_text('{"search.default_type": "music"}') + result = helm("show", "--origin", HELM_LITE_WORKERS="2") + assert result.returncode == 0, result.stderr + lines = {line.split("=")[0].strip(): line for line in result.stdout.splitlines() if "=" in line} + assert len(lines) == len(FIELDS) + assert lines["search.min_seeds"].endswith("= 4 (file)") + assert lines["search.lite_workers"].endswith("= 2 (env)") + assert lines["search.default_type"].endswith('= "music" (state)') + assert lines["search.lite_only"].endswith("= false (default)") + + +def test_show_without_origin_and_without_file(home): + result = helm("show") + assert result.returncode == 0 + assert "none, using defaults" in result.stdout + assert "(default)" not in result.stdout + + +def test_show_redacts_url_credentials(home): + config_file(home).write_text('[services]\njackett = "http://me:s3cret@jackett.test"\n') + result = helm("show") + assert "s3cret" not in result.stdout + assert '"http://***@jackett.test"' in result.stdout + + +def test_show_reports_broken_config_cleanly(home): + config_file(home).write_text("[search\n") + result = helm("show") + assert result.returncode == 1 + assert "Invalid syntax" in result.stderr + assert "Traceback" not in result.stderr + + +def test_redact_url_leaves_plain_urls_alone(): + assert redact_url("http://localhost:18080") == "http://localhost:18080" + assert redact_url("https://a:b@host:1/x?y=1") == "https://***@host:1/x?y=1" + + +# In process, so coverage sees the same paths the subprocess tests run. + + +def run_in_process(arguments, capsys): + from helm.cli import build_parser + from helm.core import config_commands + + args = build_parser().parse_args(["config", *arguments]) + code = config_commands.run(args) + captured = capsys.readouterr() + return code, captured.out, captured.err + + +def test_in_process_init_show_and_doctor(home, capsys, http_server, monkeypatch): + assert run_in_process(["init", "--format", "jsonc"], capsys)[0] == 0 + assert run_in_process(["init"], capsys)[0] == 1 + config_file(home, "config.jsonc").write_text( + f'{{"services": {{"qbittorrent": "{http_server}", "jackett": "{http_server}"}}, "x": {{"y": 1}}}}' + ) + code, out, _err = run_in_process(["show", "--origin"], capsys) + assert code == 0 and "(file)" in out + code, out, _err = run_in_process(["doctor"], capsys) + assert code == 0 + assert "x.y" in out and "answers at" in out + monkeypatch.setenv("HELM_LITE_ONLY", "1") + config_file(home, "config.jsonc").write_text("{") + code, out, _err = run_in_process(["doctor"], capsys) + assert code == 1 and "Invalid syntax" in out + + +def test_in_process_edit(home, capsys, monkeypatch): + monkeypatch.setenv("EDITOR", fake_editor(home, "[search]\nmin_seeds = 1\n")) + assert run_in_process(["edit"], capsys)[0] == 0 + monkeypatch.setenv("EDITOR", fake_editor(home, "", exit_code=2)) + assert run_in_process(["edit"], capsys)[0] == 2 + monkeypatch.setenv("EDITOR", "/nonexistent/editor") + assert run_in_process(["edit"], capsys)[0] == 1 + monkeypatch.delenv("EDITOR") + assert run_in_process(["edit"], capsys)[0] == 1 + + +def test_in_process_legacy_and_secrets_checks(home, capsys, monkeypatch): + monkeypatch.setenv("HELM_LITE_ONLY", "1") + legacy = home / "config" / "config.json" + legacy.write_text("{broken") + secrets = home / "config" / "secrets.env" + secrets.write_text("QB_PASSWORD=x\n") + secrets.chmod(0o640) + code, out, _err = run_in_process(["doctor"], capsys) + assert code == 0 + assert "cannot be parsed" in out and "chmod 600" in out + legacy.write_text('{"min_seeds": 8}') + code, out, _err = run_in_process(["doctor"], capsys) + assert "next run migrates" in out + config_file(home).write_text("[search]\nmin_seeds = 8\n") + secrets.chmod(0o600) + code, out, _err = run_in_process(["doctor"], capsys) + assert "config.json" not in out and "is private" in out From 704917d90446bfdee3da2251e0ceb2e26a201d86 Mon Sep 17 00:00:00 2001 From: Piratebird <141295458+Piratebird@users.noreply.github.com> Date: Mon, 2 Nov 2026 13:39:36 +0200 Subject: [PATCH 04/18] :shipit: feat(ui): theme presets, banner modules and banner command - Add helm, tokyo-night, nord and catppuccin-mocha presets with single-colour overrides - Add theme, logo and banner settings with validation, schema and template entries - Build banner data from built-in, file or command logos and built-in or command modules - Run every banner part under one deadline so a slow or failing part cannot delay or break it - Add an ANSI renderer that follows NO_COLOR and FORCE_COLOR - Add helm-torrent banner with --json, and logo checks in config doctor - Keep the default look: the helm preset and logo match the current UI --- CHANGELOG.md | 1 + README.md | 21 ++ src/helm/cli.py | 25 ++ src/helm/core/config_commands.py | 47 +++- src/helm/core/settings.py | 113 +++++++- src/helm/ui/ansi.py | 96 +++++++ src/helm/ui/banner.py | 312 ++++++++++++++++++++++ src/helm/ui/theme.py | 63 +++++ tests/test_settings.py | 81 +++++- tests/test_theme_banner.py | 427 +++++++++++++++++++++++++++++++ 10 files changed, 1178 insertions(+), 8 deletions(-) create mode 100644 src/helm/ui/ansi.py create mode 100644 src/helm/ui/banner.py create mode 100644 src/helm/ui/theme.py create mode 100644 tests/test_theme_banner.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 5171d3f..e1d4eeb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ All notable changes to this project will be documented in this file. - Respect the configured download directory and reject unknown flags, blank queries, and invalid content types. ### Added +- Theme presets (`helm`, `tokyo-night`, `nord`, `catppuccin-mocha`) with single-colour overrides, and `helm-torrent banner [--json]`. Banner modules and logo sources (built-in, file, command) run under one time limit, so a slow or failing part cannot break or delay the banner. - `helm-torrent config init`, `edit`, `doctor` and `show --origin`. They run even when the config file is broken. `doctor` checks syntax, values, unknown keys, ignored files, `secrets.env` permissions, writable directories and service reachability, and never prints secrets. - Layered settings from `config.toml` or `config.jsonc`, with validation and a shared JSON Schema. Existing `config.json` values migrate once, and the original file stays in place. If both new files exist, `config.toml` is used. - Durable job queue with process-isolated workers, crash recovery, cancellation and a completed-file catalog. diff --git a/README.md b/README.md index 7d76ff6..42ba10b 100644 --- a/README.md +++ b/README.md @@ -201,6 +201,27 @@ helm-torrent config show --origin # Print every value and whether it came `config init` never overwrites an existing file. `config doctor` exits with status 1 on errors. Unreachable services only produce warnings, and the service checks are skipped when `search.lite_only` is set. Neither command prints secrets, and passwords in URLs are shown as `***`. +### Theme and banner + +```toml +[theme] +preset = "helm" # helm, tokyo-night, nord or catppuccin-mocha +# logo = "#4A69BD" # Override one preset colour: logo, accent, text, line, error, muted + +[logo] +source = "builtin:helm" # builtin:helm, file, cmd: or none +position = "left" # left or top +# art_file = "~/.config/helm/logo.txt" + +[banner] +enabled = true +modules = ["version", "mode", "indexers", "jobs", "downloads"] +timeout_ms = 400 +``` + +`helm-torrent banner` prints the banner, and `--json` prints its data. Modules are `version`, `mode`, `indexers`, `jobs`, `downloads`, `services` and `separator`, plus your own commands, such as `{ type = "command", label = "Uptime", command = ["uptime", "-p"] }`. Commands run without a shell, and only the first line of their output is shown. All modules share the `timeout_ms` limit: a slow one shows `timed out`, a failing one shows `unavailable`, and a logo that fails falls back to the built-in one. For `source = "file"`, art can use `{logo}`, `{accent}`, `{text}`, `{line}`, `{muted}` and `{reset}` colour placeholders. `HELM_THEME` and `HELM_BANNER` override the file, and `NO_COLOR` turns colours off. + + ## Usage Run `helm-torrent` for the interactive CLI. Use subcommands for scripted searches and administration: diff --git a/src/helm/cli.py b/src/helm/cli.py index e85e96b..38f8d9a 100644 --- a/src/helm/cli.py +++ b/src/helm/cli.py @@ -217,6 +217,8 @@ def build_parser(): daemon_parser.add_argument("action", choices=["status", "stop"]) daemon_parser.add_argument("id", nargs="?") + subparsers.add_parser("banner", help="Print the banner, even when banner.enabled is false", parents=[base_parser]) + from helm.core.config_commands import add_parser as add_config_parser add_config_parser(subparsers, [base_parser]) @@ -404,6 +406,26 @@ def _run_utility(command): return +def _cmd_banner(args): + from helm.ui.ansi import color_enabled, render_banner + from helm.ui.banner import build_banner + from helm.ui.theme import load_theme + + settings = load_settings() + context = {"mode": "lite"} if args.lite else {} + banner = build_banner(settings, context) + if args.json: + data = { + "theme": settings.get("theme.preset"), + "logo": ["".join(text for _color, text in line) for line in banner.logo], + "modules": [entry.__dict__ for entry in banner.entries], + } + print(json.dumps(data, ensure_ascii=False)) + return + text = render_banner(banner, load_theme(settings), color=color_enabled(sys.stdout)) + sys.stdout.write(text) + + def main(): """Console entry point. It bypasses the __main__ block below.""" try: @@ -422,6 +444,9 @@ def run(): from helm.core.config_commands import run as run_config raise SystemExit(run_config(args)) + if args.command == "banner": + _cmd_banner(args) + return if args.command in ("watch", "serve", "files", "download"): raise SystemExit(_run_headless(args, parser)) diff --git a/src/helm/core/config_commands.py b/src/helm/core/config_commands.py index 1cfd53d..19779a3 100644 --- a/src/helm/core/config_commands.py +++ b/src/helm/core/config_commands.py @@ -7,6 +7,7 @@ import json import os import shlex +import shutil import stat import subprocess import sys @@ -41,6 +42,20 @@ "services.qbittorrent": "qBittorrent Web UI address.", "services.qbittorrent_user": "qBittorrent user name. The password stays in secrets.env.", "services.qbittorrent_downloads_root": "Download path as qBittorrent sees it, such as a container mount.", + "theme.preset": "Colour preset: helm, tokyo-night, nord or catppuccin-mocha.", + "theme.logo": "Override the preset's logo colour.", + "theme.accent": "Override the preset's accent colour, used for labels.", + "theme.text": "Override the preset's text colour.", + "theme.line": "Override the preset's line colour, used for separators.", + "theme.error": "Override the preset's error colour.", + "theme.muted": "Override the preset's muted colour, used for placeholders.", + "logo.source": 'Logo to show: "builtin:helm", "file" (art or art_file), "cmd:" or "none".', + "logo.position": "Logo position next to the banner text: left or top.", + "logo.art": 'Your own art for source = "file". Colour placeholders: {logo} {accent} {text} {line} {muted} {reset}.', + "logo.art_file": 'File holding your art, used when source = "file" and art is not set.', + "banner.enabled": "Show the banner when the UI starts. `helm-torrent banner` always prints it.", + "banner.modules": 'Banner lines in order. Built in: version, mode, indexers, jobs, downloads, services, separator. Custom: { type = "command", label = "...", command = ["..."] }.', + "banner.timeout_ms": "Time limit for all banner lines together. Slow lines show a placeholder.", } FORMATS = {"toml": USER_FILES[0], "jsonc": USER_FILES[1]} PROBE_TIMEOUT = 2.0 @@ -68,6 +83,12 @@ def run(args): return edit() if args.config_action == "edit" else doctor() +def _sample(field): + """Return the value shown for a field in the template.""" + value = field.example if field.default is None else field.default + return json.dumps(list(value) if isinstance(value, tuple) else value) + + def _sections(): sections: dict = {} for field in FIELDS: @@ -89,7 +110,7 @@ def render_template(file_format): lines.append(f"[{section}]") for key, field in items: lines.append("# " + DESCRIPTIONS[field.path]) - lines.append(f"# {key} = {json.dumps(field.default)}") + lines.append(f"# {key} = {_sample(field)}") lines.append("") return "\n".join(lines) lines = ["// " + line for line in header] + ["{"] @@ -97,7 +118,7 @@ def render_template(file_format): lines.append(f' "{section}": {{') for key, field in items: lines.append(" // " + DESCRIPTIONS[field.path]) - lines.append(f' // "{key}": {json.dumps(field.default)},') + lines.append(f' // "{key}": {_sample(field)},') lines.append(" },") lines.append("}") return "\n".join(lines) + "\n" @@ -290,10 +311,32 @@ def _check_services(report, settings): report.add("warn", f"{name} is not reachable at {shown}: {reason}") +def _check_logo(report, settings): + """Warn about logo settings that would fall back to the built-in logo.""" + source = settings.get("logo.source") + if source.startswith("builtin:"): + from helm.ui.banner import LOGOS + + name = source.split(":", 1)[1] + if name not in LOGOS: + report.add("warn", f"logo.source names unknown logo {name!r}; built in: {', '.join(sorted(LOGOS))}") + elif source == "file" and settings.get("logo.art") is None: + path = settings.get("logo.art_file") + if not path: + report.add("warn", 'logo.source = "file" needs logo.art or logo.art_file') + elif not os.path.isfile(os.path.expanduser(path)): + report.add("warn", f"logo.art_file {path} does not exist") + elif source.startswith("cmd:"): + program = shlex.split(source[4:])[0] + if shutil.which(program) is None: + report.add("warn", f"logo command {program!r} is not installed; the built-in logo is used") + + def doctor(): settings, problems = resolve_settings() report = Report() report.check_file(settings, problems) + _check_logo(report, settings) _check_shadowed(report) _check_legacy(report, settings) _check_secrets(report) diff --git a/src/helm/core/settings.py b/src/helm/core/settings.py index 63ed534..1788197 100644 --- a/src/helm/core/settings.py +++ b/src/helm/core/settings.py @@ -7,6 +7,8 @@ import json import os +import re +import shlex import shutil import sys import tempfile @@ -31,7 +33,23 @@ class Field: choices: Tuple[str, ...] = () minimum: Any = None maximum: Any = None - + # Shown in the config template for settings that have no default value. + example: Any = None + + +THEMES = ("helm", "tokyo-night", "nord", "catppuccin-mocha") +COLOR_NAMES = ("logo", "accent", "text", "line", "error", "muted") +MODULE_NAMES = ("version", "mode", "indexers", "jobs", "downloads", "services", "separator") +DEFAULT_MODULES = ("version", "mode", "indexers", "jobs", "downloads") +HEX_COLOR = re.compile(r"^#[0-9A-Fa-f]{6}$") +HELM_COLORS = { + "logo": "#4A69BD", + "accent": "#B33939", + "text": "#EADAC9", + "line": "#CD6133", + "error": "#FF5252", + "muted": "#918383", +} FIELDS = ( Field("search.min_seeds", "int", 3, legacy="min_seeds", minimum=0), @@ -57,6 +75,15 @@ class Field: env="QB_DOWNLOADS_ROOT", legacy="QB_DOWNLOADS_ROOT", ), + Field("theme.preset", "str", "helm", env="HELM_THEME", choices=THEMES), + *(Field(f"theme.{name}", "color", None, example=HELM_COLORS[name]) for name in COLOR_NAMES), + Field("logo.source", "logo", "builtin:helm"), + Field("logo.position", "str", "left", choices=("left", "top")), + Field("logo.art", "art", None, example="{logo} ~~ my helm ~~ {accent}<3"), + Field("logo.art_file", "path", None, example="~/.config/helm/logo.txt"), + Field("banner.enabled", "bool", True, env="HELM_BANNER"), + Field("banner.modules", "modules", DEFAULT_MODULES), + Field("banner.timeout_ms", "int", 400, minimum=50, maximum=5000), ) BY_PATH = {field.path: field for field in FIELDS} USER_FILES = ("config.toml", "config.jsonc") @@ -140,8 +167,64 @@ def flatten(data, prefix=""): return values +def _check_logo_source(value): + if not isinstance(value, str): + raise ValueError("must be a string") + if value in ("none", "file"): + return value + kind, _, rest = value.partition(":") + if kind == "builtin" and rest.strip(): + return value + if kind == "cmd": + try: + if shlex.split(rest): + return value + except ValueError as error: + raise ValueError(f"has an invalid command: {error}") from None + raise ValueError('must be "none", "file", "builtin:" or "cmd:"') + + +def _check_art(value): + if isinstance(value, list) and all(isinstance(line, str) for line in value): + return "\n".join(value) + if isinstance(value, str): + return value + raise ValueError("must be a string or a list of strings") + + +def _check_module(item): + if isinstance(item, str): + if item not in MODULE_NAMES: + raise ValueError(f"has unknown module {item!r}; use one of " + ", ".join(MODULE_NAMES)) + return item + if not isinstance(item, dict) or item.get("type") != "command": + raise ValueError('entries must be module names or tables with type = "command"') + extra = set(item) - {"type", "label", "command"} + if extra: + raise ValueError("command entries only take type, label and command, not " + ", ".join(sorted(extra))) + label = item.get("label") + command = item.get("command") + if not isinstance(label, str) or not label.strip(): + raise ValueError("command entries need a non-empty label") + if not isinstance(command, list) or not command or not all(isinstance(part, str) and part for part in command): + raise ValueError("command entries need command as a non-empty list of strings") + return {"type": "command", "label": label, "command": list(command)} + + def check(field, value): """Return a valid value for a field, or raise ValueError.""" + if field.kind == "color": + if not isinstance(value, str) or not HEX_COLOR.match(value): + raise ValueError('must be a colour like "#4A69BD"') + return value + if field.kind == "logo": + return _check_logo_source(value) + if field.kind == "art": + return _check_art(value) + if field.kind == "modules": + if not isinstance(value, list): + raise ValueError("must be a list") + return tuple(_check_module(item) for item in value) if field.kind == "bool": if not isinstance(value, bool): raise ValueError("must be true or false") @@ -412,11 +495,35 @@ def get_qb_url(): def settings_schema(): """Return one JSON Schema that describes both config formats.""" - kinds = {"bool": "boolean", "int": "integer", "str": "string", "url": "string"} + kinds = { + "bool": "boolean", + "int": "integer", + "str": "string", + "url": "string", + "color": "string", + "logo": "string", + "path": "string", + } + strings = {"type": "array", "items": {"type": "string", "minLength": 1}, "minItems": 1} + command = { + "type": "object", + "properties": {"type": {"const": "command"}, "label": {"type": "string", "minLength": 1}, "command": strings}, + "required": ["type", "label", "command"], + "additionalProperties": False, + } + special = { + "art": {"anyOf": [{"type": "string"}, {"type": "array", "items": {"type": "string"}}]}, + "modules": {"type": "array", "items": {"anyOf": [{"enum": list(MODULE_NAMES)}, command]}}, + } sections: dict = {} for field in FIELDS: section, key = field.path.split(".", 1) - entry: dict = {"type": kinds[field.kind], "default": field.default} + entry: dict = dict(special[field.kind]) if field.kind in special else {"type": kinds[field.kind]} + entry["default"] = list(field.default) if isinstance(field.default, tuple) else field.default + if field.kind == "color": + entry["pattern"] = HEX_COLOR.pattern + if field.kind == "logo": + entry["pattern"] = "^(none|file|builtin:.+|cmd:.+)$" if field.kind == "url": entry["pattern"] = "^[Hh][Tt][Tt][Pp][Ss]?://" if field.choices: diff --git a/src/helm/ui/ansi.py b/src/helm/ui/ansi.py new file mode 100644 index 0000000..06e13ec --- /dev/null +++ b/src/helm/ui/ansi.py @@ -0,0 +1,96 @@ +"""ANSI renderer for banner data and theme colours. The only place that writes escapes.""" + +import os +import unicodedata + +from helm.ui.banner import SGR + +RESET = "\033[0m" +BOLD = "\033[1m" +GAP = " " + + +def sgr(hex_color): + """Return the 24-bit foreground escape for a #RRGGBB colour.""" + value = hex_color.lstrip("#") + red, green, blue = (int(value[index : index + 2], 16) for index in (0, 2, 4)) + return f"\033[38;2;{red};{green};{blue}m" + + +def color_enabled(stream): + """Follow NO_COLOR and FORCE_COLOR, and otherwise colour only terminals.""" + if os.environ.get("NO_COLOR"): + return False + if os.environ.get("FORCE_COLOR"): + return True + isatty = getattr(stream, "isatty", None) + return bool(isatty and isatty()) + + +def visible_width(text): + """Terminal columns used by text, ignoring SGR codes and counting wide characters twice.""" + width = 0 + for character in SGR.sub("", text): + if unicodedata.combining(character): + continue + width += 2 if unicodedata.east_asian_width(character) in ("W", "F") else 1 + return width + + +class Painter: + def __init__(self, theme, color): + self.theme = theme + self.color = color + + def paint(self, name, text, bold=False): + if not self.color or not text: + return text + return (BOLD if bold else "") + sgr(self.theme.get(name)) + text + RESET + + def raw(self, text): + return text + RESET if self.color and SGR.search(text) else (text if self.color else SGR.sub("", text)) + + +def _logo_lines(banner, painter): + lines = [] + for segments in banner.logo: + parts = [painter.raw(text) if name is None else painter.paint(name, text) for name, text in segments] + lines.append("".join(parts)) + return lines + + +def _entry_lines(banner, painter): + labelled = [entry for entry in banner.entries if entry.status != "separator"] + label_width = max((visible_width(entry.label) for entry in labelled), default=0) + text_width = max((label_width + 2 + visible_width(entry.value) for entry in labelled), default=0) + lines = [] + for entry in banner.entries: + if entry.status == "separator": + lines.append(painter.paint("line", "─" * max(text_width, 8))) + continue + padding = " " * (label_width - visible_width(entry.label)) + value_color = {"timeout": "muted", "error": "error"}.get(entry.status, "text") + lines.append( + painter.paint("accent", entry.label, bold=True) + padding + " " + painter.paint(value_color, entry.value) + ) + return lines + + +def render_banner(banner, theme, color=True): + """Return the banner as text, logo left of or above the module lines.""" + painter = Painter(theme, color) + logo = _logo_lines(banner, painter) + entries = _entry_lines(banner, painter) + if banner.position == "top" or not logo or not entries: + lines = logo + ([""] if logo and entries else []) + entries + else: + width = max(visible_width(line) for line in logo) + height = max(len(logo), len(entries)) + lines = [] + for index in range(height): + left = logo[index] if index < len(logo) else "" + right = entries[index] if index < len(entries) else "" + if right: + left += " " * (width - visible_width(left)) + GAP + lines.append(left + right) + return "\n".join(lines) + "\n" if lines else "" diff --git a/src/helm/ui/banner.py b/src/helm/ui/banner.py new file mode 100644 index 0000000..a764456 --- /dev/null +++ b/src/helm/ui/banner.py @@ -0,0 +1,312 @@ +"""Banner data: the logo and module lines, with no colour or layout. + +Every part runs in its own daemon thread under one shared deadline. A part that +fails shows "unavailable" and one that is too slow shows "timed out". Neither can +break the caller or delay it past banner.timeout_ms, and a stuck part cannot +block interpreter exit either. +""" + +import os +import re +import shlex +import shutil +import sqlite3 +import subprocess +import threading +import time +from dataclasses import dataclass, field +from typing import List, Optional, Tuple + +from helm.core.config_manager import get_config_dir, get_dl_dir, get_state_dir +from helm.ui.colors import logo as wordmark + +# The current UI's wordmark, shared so the default look cannot drift. +LOGOS = {"helm": wordmark.strip("\n").split("\n")} +PLACEHOLDER = re.compile(r"\{(logo|accent|text|line|error|muted|reset)\}") +SGR = re.compile(r"\x1b\[[0-9;]*m") +# Any other escape sequence or control character from a command is dropped. +UNSAFE = re.compile(r"\x1b(\[[0-9;?]*[ -/]*[@-~]|\][^\x07\x1b]*(\x07|\x1b\\)|.)|[\x00-\x08\x0b-\x1f\x7f]") +MAX_ART_BYTES = 64 * 1024 +MAX_ART_LINES = 60 +MAX_VALUE = 200 +TIMED_OUT = "timed out" +UNAVAILABLE = "unavailable" + +# A logo line is a list of (colour name, text). Colour None marks raw command +# output, whose own SGR colours the renderer keeps or strips. +Segment = Tuple[Optional[str], str] + + +@dataclass +class Entry: + label: str + value: str = "" + status: str = "ok" # ok, timeout, error, separator + + +@dataclass +class Banner: + logo: List[List[Segment]] = field(default_factory=list) + entries: List[Entry] = field(default_factory=list) + position: str = "left" + + +def parse_art(text): + """Split art into coloured segments. Unknown braces stay as written.""" + lines = [] + color = "logo" + for raw in text.split("\n")[:MAX_ART_LINES]: + segments: List[Segment] = [] + position = 0 + for match in PLACEHOLDER.finditer(raw): + if match.start() > position: + segments.append((color, raw[position : match.start()])) + name = match.group(1) + color = "text" if name == "reset" else name + position = match.end() + if position < len(raw): + segments.append((color, raw[position:])) + lines.append(segments) + while lines and not lines[-1]: + lines.pop() + return lines + + +def clean_output(text): + """Keep SGR colours from a command's output and drop every other control code.""" + kept = [] + for line in text.replace("\r\n", "\n").split("\n")[:MAX_ART_LINES]: + parts = SGR.split(line) + codes = SGR.findall(line) + safe = UNSAFE.sub("", parts[0]) + for code, part in zip(codes, parts[1:]): + safe += code + UNSAFE.sub("", part) + kept.append(safe.replace("\t", " ")) + while kept and not SGR.sub("", kept[-1]).strip(): + kept.pop() + return kept + + +def _builtin(name="helm"): + return [[("logo", line)] for line in LOGOS[name]] + + +def _command_output(command, timeout): + result = subprocess.run( + command, + stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, + timeout=timeout, + check=True, + ) + return result.stdout[:MAX_ART_BYTES].decode("utf-8", errors="replace") + + +def _read_art_file(path): + with open(os.path.expanduser(path), "rb") as stream: + return stream.read(MAX_ART_BYTES).decode("utf-8", errors="replace") + + +def resolve_logo(settings, timeout): + """Return logo lines. Any failure falls back to the built-in Helm logo.""" + source = settings.get("logo.source") + if source == "none": + return [] + if source.startswith("builtin:"): + name = source.split(":", 1)[1] + return _builtin(name if name in LOGOS else "helm") + if source == "file": + art = settings.get("logo.art") + path = settings.get("logo.art_file") + if art is None and path: + art = _read_art_file(path) + if not art or not art.strip(): + return _builtin() + return parse_art(art) + lines = clean_output(_command_output(shlex.split(source[4:]), timeout)) + return [[(None, line)] for line in lines] or _builtin() + + +def _version(): + try: + from importlib.metadata import version + except ImportError: # pragma: no cover - Python 3.8 has importlib.metadata + return "unknown" + try: + return version("helm-torrent") + except Exception: + return "unknown" + + +def _mode(settings, context): + if context.get("mode"): + return context["mode"] + if settings.get("search.lite_only"): + return "lite" + return settings.get("search.indexer_manager") + + +def _lite_sources(): + from helm.core.lite_plugin_loader import plugin_jobs + + bundled = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "plugins") + return len(plugin_jobs([os.path.join(get_config_dir(), "plugins"), bundled])) + + +def _manager_count(name, settings, timeout): + import xml.etree.ElementTree as ET + + import requests + + from helm.core.secret_manager import get_secret + + url = settings.get(f"services.{name}") + key = get_secret(f"{name.upper()}_API_KEY") + if not key: + return f"{name} has no API key" + if name == "jackett": + response = requests.get( + f"{url}/api/v2.0/indexers/all/results/torznab/api", + params={"apikey": key, "t": "indexers", "configured": "true"}, + timeout=timeout, + ) + response.raise_for_status() + count = len(ET.fromstring(response.content).findall("indexer")) + else: + response = requests.get(f"{url}/api/v1/indexer", headers={"X-Api-Key": key}, timeout=timeout) + response.raise_for_status() + count = sum(1 for indexer in response.json() if indexer.get("enable")) + return f"{count} in {name}" + + +def _indexers(settings, timeout): + if settings.get("search.lite_only"): + return f"{_lite_sources()} Lite sources" + manager = settings.get("search.indexer_manager") + names = [name for name in ("jackett", "prowlarr") if manager in (name, "both")] + return ", ".join(_manager_count(name, settings, timeout) for name in names) + + +def _jobs(): + path = os.path.join(get_state_dir(), "jobs.sqlite3") + if not os.path.isfile(path): + return "none yet" + # Read only, so the banner never creates or migrates the queue. + connection = sqlite3.connect(f"file:{path}?mode=ro", uri=True, timeout=0.2) + try: + rows = dict(connection.execute("SELECT status, COUNT(*) FROM jobs GROUP BY status").fetchall()) + finally: + connection.close() + active = [ + f"{rows[status]} {label}" + for status, label in (("running", "running"), ("submitted", "in qBittorrent"), ("pending", "queued")) + if rows.get(status) + ] + return ", ".join(active) if active else "idle" + + +def _downloads(): + path = get_dl_dir() + existing = path + while not os.path.exists(existing) and os.path.dirname(existing) != existing: + existing = os.path.dirname(existing) + free = shutil.disk_usage(existing).free / 1024**3 + home = os.path.expanduser("~") + shown = "~" + path[len(home) :] if path == home or path.startswith(home + os.sep) else path + return f"{shown} ({free:.1f} GiB free)" + + +def _services(settings, timeout): + from helm.core.config_commands import probe + + if settings.get("search.lite_only"): + return "not used in Lite mode" + manager = settings.get("search.indexer_manager") + names = [name for name in ("jackett", "prowlarr") if manager in (name, "both")] + ["qbittorrent"] + states = [] + for name in names: + reachable = probe(settings.get(f"services.{name}"), timeout=timeout) is None + states.append(f"{name} {'up' if reachable else 'down'}") + return ", ".join(states) + + +def _custom(command, timeout): + lines = clean_output(_command_output(command, timeout)) + first = next((SGR.sub("", line).strip() for line in lines if SGR.sub("", line).strip()), "") + return first[:MAX_VALUE] + + +LABELS = { + "version": "Version", + "mode": "Mode", + "indexers": "Indexers", + "jobs": "Jobs", + "downloads": "Downloads", + "services": "Services", +} + + +def _task(module, settings, context, timeout): + """Return (label, function) for one module setting.""" + if isinstance(module, dict): + return module["label"], lambda: _custom(module["command"], timeout) + functions = { + "version": _version, + "mode": lambda: _mode(settings, context), + "indexers": lambda: _indexers(settings, timeout), + "jobs": _jobs, + "downloads": _downloads, + "services": lambda: _services(settings, timeout), + } + return LABELS[module], functions[module] + + +def run_with_deadline(functions, timeout): + """Run functions in daemon threads and return {index: (status, value)} by the deadline.""" + results: dict = {} + + def work(index, function): + try: + results[index] = ("ok", function()) + except Exception: + results[index] = ("error", None) + + threads = [] + for index, function in enumerate(functions): + thread = threading.Thread(target=work, args=(index, function), name=f"helm-banner-{index}", daemon=True) + thread.start() + threads.append(thread) + deadline = time.monotonic() + timeout + for thread in threads: + thread.join(max(0.0, deadline - time.monotonic())) + return {index: results.get(index, ("timeout", None)) for index in range(len(functions))} + + +def build_banner(settings, context=None): + """Collect banner data within banner.timeout_ms. Never raises for a failing part.""" + context = context or {} + timeout = settings.get("banner.timeout_ms") / 1000 + modules = settings.get("banner.modules") + tasks = [_task(module, settings, context, timeout) for module in modules if module != "separator"] + functions = [lambda: resolve_logo(settings, timeout)] + [function for _label, function in tasks] + results = run_with_deadline(functions, timeout) + + status, logo = results[0] + if status != "ok": + logo = _builtin() + entries = [] + index = 1 + for module in modules: + if module == "separator": + entries.append(Entry("", status="separator")) + continue + label = tasks[index - 1][0] + status, value = results[index] + index += 1 + if status == "ok": + text = str(value)[:MAX_VALUE] if value is not None and str(value) else "none" + entries.append(Entry(label, text)) + else: + entries.append(Entry(label, TIMED_OUT if status == "timeout" else UNAVAILABLE, status)) + return Banner(logo, entries, settings.get("logo.position")) diff --git a/src/helm/ui/theme.py b/src/helm/ui/theme.py new file mode 100644 index 0000000..30064fb --- /dev/null +++ b/src/helm/ui/theme.py @@ -0,0 +1,63 @@ +"""Colour themes as plain hex values. Renderers turn them into ANSI or Textual styles. + +Every preset defines the same names, so modules and renderers never depend on a +particular theme. The upstream sources were checked on 2026-11-02: + +- tokyo-night: folke/tokyonight.nvim, lua/tokyonight/colors/storm.lua (night shares these) +- nord: nordtheme/nord, src/nord.css +- catppuccin-mocha: catppuccin/palette, palette.json +""" + +from dataclasses import dataclass, field +from typing import Dict + +from helm.core.settings import COLOR_NAMES, HELM_COLORS + +PRESETS: Dict[str, Dict[str, str]] = { + # The colours the current UI hardcodes in helm.ui.colors, so the default look stays the same. + "helm": dict(HELM_COLORS), + "tokyo-night": { + "logo": "#7aa2f7", # blue + "accent": "#bb9af7", # magenta + "text": "#c0caf5", # fg + "line": "#ff9e64", # orange + "error": "#f7768e", # red + "muted": "#565f89", # comment + }, + "nord": { + "logo": "#88c0d0", # nord8 + "accent": "#b48ead", # nord15 + "text": "#d8dee9", # nord4 + "line": "#d08770", # nord12 + "error": "#bf616a", # nord11 + "muted": "#4c566a", # nord3 + }, + "catppuccin-mocha": { + "logo": "#89b4fa", # blue + "accent": "#cba6f7", # mauve + "text": "#cdd6f4", # text + "line": "#fab387", # peach + "error": "#f38ba8", # red + "muted": "#6c7086", # overlay0 + }, +} + + +@dataclass(frozen=True) +class Theme: + name: str + colors: Dict[str, str] = field(default_factory=dict) + + def get(self, name): + return self.colors[name] + + +def load_theme(settings): + """Build the theme from theme.preset plus any single-colour overrides.""" + name = settings.get("theme.preset") + colors = dict(PRESETS[name]) + for color in COLOR_NAMES: + override = settings.get(f"theme.{color}") + if override: + colors[color] = override + return Theme(name, colors) diff --git a/tests/test_settings.py b/tests/test_settings.py index e644ea3..7da34b7 100644 --- a/tests/test_settings.py +++ b/tests/test_settings.py @@ -185,8 +185,8 @@ def test_all_problems_are_reported_together(config_dir): def test_unknown_keys_are_kept_for_doctor(config_dir): - (config_dir / "config.toml").write_text("[search]\ntypo = 1\n[theme]\npreset = 'helm'\n") - assert sorted(load_settings().unknown) == ["search.typo", "theme.preset"] + (config_dir / "config.toml").write_text("[search]\ntypo = 1\n[future]\nsetting = 'x'\n") + assert sorted(load_settings().unknown) == ["future.setting", "search.typo"] def test_precedence_env_file_state_default(config_dir, monkeypatch): @@ -367,7 +367,7 @@ def test_schema_covers_every_field_and_its_defaults(): for field in FIELDS: section, key = field.path.split(".", 1) entry = schema["properties"][section]["properties"][key] - assert entry["default"] == field.default + assert entry["default"] == json.loads(json.dumps(field.default)) assert schema["properties"]["search"]["properties"]["lite_workers"]["maximum"] == 12 assert "prowlarr" in schema["properties"]["search"]["properties"]["indexer_manager"]["enum"] assert BY_PATH["services.jackett"].default == "http://localhost:19117" @@ -434,3 +434,78 @@ def test_config_worker_count_reaches_the_process(config_dir): } result = subprocess.run([sys.executable, "-c", code], env=environment, capture_output=True, text=True, timeout=30) assert result.stdout.strip().endswith("3"), result.stderr + + +@pytest.mark.parametrize( + "path, value, expected", + [ + ("theme.preset", "nord", "nord"), + ("theme.logo", "#aabbcc", "#aabbcc"), + ("logo.source", "builtin:helm", "builtin:helm"), + ("logo.source", "cmd:figlet 'the helm'", "cmd:figlet 'the helm'"), + ("logo.source", "none", "none"), + ("logo.art", ["a", "b"], "a\nb"), + ("logo.art", "a\nb", "a\nb"), + ("banner.modules", ["version", "separator"], ("version", "separator")), + ( + "banner.modules", + [{"type": "command", "label": "Up", "command": ["uptime"]}], + ({"type": "command", "label": "Up", "command": ["uptime"]},), + ), + ], +) +def test_banner_and_theme_values_are_accepted(path, value, expected): + from helm.core.settings import check + + assert check(BY_PATH[path], value) == expected + + +@pytest.mark.parametrize( + "path, value, message", + [ + ("theme.preset", "solarized", "must be one of"), + ("theme.logo", "blue", "colour"), + ("theme.logo", "#abc", "colour"), + ("logo.source", "cmd:", "must be"), + ("logo.source", "cmd:'unclosed", "invalid command"), + ("logo.source", "builtin:", "must be"), + ("logo.source", 3, "string"), + ("logo.art", ["a", 1], "list of strings"), + ("banner.modules", "version", "must be a list"), + ("banner.modules", ["weather"], "unknown module"), + ("banner.modules", [{"type": "shell"}], 'type = "command"'), + ("banner.modules", [{"type": "command", "label": "", "command": ["x"]}], "label"), + ("banner.modules", [{"type": "command", "label": "x", "command": "uptime"}], "list of strings"), + ("banner.modules", [{"type": "command", "label": "x", "command": ["x"], "shell": True}], "not shell"), + ("banner.timeout_ms", 10, "at least 50"), + ], +) +def test_banner_and_theme_values_are_rejected(path, value, message): + from helm.core.settings import check + + with pytest.raises(ValueError, match=message): + check(BY_PATH[path], value) + + +def test_banner_settings_load_from_toml_and_jsonc(config_dir): + (config_dir / "config.toml").write_text( + '[theme]\npreset = "nord"\n[banner]\nmodules = ["jobs", { type = "command", label = "Up", command = ["uptime"] }]\n' + ) + from_toml = load_settings() + (config_dir / "config.toml").unlink() + (config_dir / "config.jsonc").write_text( + '{"theme": {"preset": "nord"}, "banner": {"modules": ["jobs", {"type": "command", "label": "Up", "command": ["uptime"]}]}}' + ) + from_jsonc = load_settings() + for path in ("theme.preset", "banner.modules"): + assert from_toml.get(path) == from_jsonc.get(path) + assert from_toml.get("banner.modules")[1]["command"] == ["uptime"] + + +def test_theme_and_banner_environment_overrides(config_dir, monkeypatch): + monkeypatch.setenv("HELM_THEME", "tokyo-night") + monkeypatch.setenv("HELM_BANNER", "0") + settings = load_settings() + assert settings.get("theme.preset") == "tokyo-night" + assert settings.get("banner.enabled") is False + assert settings.origin("theme.preset") == "env" diff --git a/tests/test_theme_banner.py b/tests/test_theme_banner.py new file mode 100644 index 0000000..c175a6c --- /dev/null +++ b/tests/test_theme_banner.py @@ -0,0 +1,427 @@ +import http.server +import json +import os +import re +import subprocess +import sys +import threading +import time +from pathlib import Path + +import pytest + +from helm.core.settings import BY_PATH, COLOR_NAMES, FIELDS, HEX_COLOR, THEMES, Settings, check +from helm.ui import colors +from helm.ui.ansi import color_enabled, render_banner, sgr, visible_width +from helm.ui.banner import ( + LOGOS, + TIMED_OUT, + UNAVAILABLE, + Banner, + Entry, + build_banner, + clean_output, + parse_art, + resolve_logo, + run_with_deadline, +) +from helm.ui.theme import PRESETS, load_theme + +SRC = str(Path(__file__).resolve().parents[1] / "src") +ANSI = re.compile(r"\x1b\[[0-9;]*m") +SCRUBBED = {field.env for field in FIELDS if field.env} | { + "NO_COLOR", + "FORCE_COLOR", + "JACKETT_API_KEY", + "PROWLARR_API_KEY", +} + + +@pytest.fixture +def home(tmp_path, monkeypatch): + for key, name in (("HELM_CONFIG_DIR", "config"), ("HELM_STATE_DIR", "state"), ("HELM_DL_DIR", "downloads")): + monkeypatch.setenv(key, str(tmp_path / name)) + (tmp_path / "config").mkdir() + for key in SCRUBBED: + monkeypatch.delenv(key, raising=False) + return tmp_path + + +def make_settings(**values): + """Settings with the given values, written as theme__preset for theme.preset.""" + resolved = {} + for key, value in values.items(): + path = key.replace("__", ".") + resolved[path] = check(BY_PATH[path], value) if value is not None else None + return Settings(resolved) + + +def python_command(code): + return [sys.executable, "-c", code] + + +@pytest.fixture +def server(): + """A real local HTTP server. Set server.routes[path] = (status, content type, body).""" + routes = {} + + class Handler(http.server.BaseHTTPRequestHandler): + def do_GET(self): + status, kind, body = routes.get(self.path.split("?")[0], (404, "text/plain", b"")) + self.send_response(status) + self.send_header("Content-Type", kind) + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + routes.setdefault("_seen", []).append(self.path) + + def log_message(self, *args): + pass + + httpd = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) + thread = threading.Thread(target=httpd.serve_forever, daemon=True) + thread.start() + httpd.url = f"http://127.0.0.1:{httpd.server_address[1]}" + httpd.routes = routes + yield httpd + httpd.shutdown() + httpd.server_close() + + +# Themes + + +def test_presets_match_settings_and_define_every_colour(): + assert tuple(PRESETS) == THEMES + for preset in PRESETS.values(): + assert tuple(preset) == COLOR_NAMES + assert all(HEX_COLOR.match(value) for value in preset.values()) + + +def test_helm_preset_keeps_the_current_look(): + theme = load_theme(make_settings()) + assert theme.name == "helm" + assert sgr(theme.get("logo")) == colors.C_LOGO + assert sgr(theme.get("accent")) == colors.C_SUB + assert sgr(theme.get("text")) == colors.C_TEXT + assert sgr(theme.get("line")) == colors.C_LINE + assert sgr(theme.get("error")) == colors.C_ERR + assert LOGOS["helm"] == colors.logo.strip("\n").split("\n") + + +def test_single_colour_override_keeps_the_rest_of_the_preset(): + theme = load_theme(make_settings(theme__preset="nord", theme__logo="#123456")) + assert theme.get("logo") == "#123456" + assert theme.get("accent") == PRESETS["nord"]["accent"] + + +# Logo + + +def test_parse_art_placeholders_carry_across_lines(): + lines = parse_art("{accent}A{line}B\nC{reset}D {unknown} {logo}E\n\n") + assert lines == [ + [("accent", "A"), ("line", "B")], + [("line", "C"), ("text", "D {unknown} "), ("logo", "E")], + ] + + +def test_parse_art_limits_lines(): + assert len(parse_art("x\n" * 500)) == 60 + + +def test_clean_output_keeps_colour_and_drops_other_control_codes(): + raw = "\x1b[31mred\x1b[0m\x1b[2J\x1b]0;title\x07\x07ok\r\nnext\tline\x1b[?25l\n\n" + assert clean_output(raw) == ["\x1b[31mred\x1b[0mok", "next line"] + + +def test_resolve_logo_sources(home): + timeout = 2 + assert resolve_logo(make_settings(logo__source="none"), timeout) == [] + assert resolve_logo(make_settings(logo__source="builtin:missing"), timeout) == resolve_logo( + make_settings(), timeout + ) + assert resolve_logo(make_settings(logo__source="file", logo__art="{accent}hi"), timeout) == [[("accent", "hi")]] + art = home / "art.txt" + art.write_text("{line}rope\n") + from_file = make_settings(logo__source="file", logo__art_file=str(art)) + assert resolve_logo(from_file, timeout) == [[("line", "rope")]] + blank = make_settings(logo__source="file", logo__art=" ") + assert resolve_logo(blank, timeout) == resolve_logo(make_settings(), timeout) + printing = "cmd:" + " ".join(map(repr, python_command("print('\\x1b[32mgreen\\x1b[0m')"))) + assert resolve_logo(make_settings(logo__source=printing), timeout) == [[(None, "\x1b[32mgreen\x1b[0m")]] + silent = "cmd:" + " ".join(map(repr, python_command("pass"))) + assert resolve_logo(make_settings(logo__source=silent), timeout) == resolve_logo(make_settings(), timeout) + + +@pytest.mark.parametrize( + "source", + [ + "cmd:/nonexistent/figlet", + "cmd:" + " ".join(map(repr, python_command("import sys; sys.exit(4)"))), + "cmd:" + " ".join(map(repr, python_command("import time; time.sleep(5)"))), + ], +) +def test_failing_or_slow_logo_command_falls_back_quickly(home, source): + settings = make_settings(logo__source=source, banner__timeout_ms=300, banner__modules=["version"]) + started = time.monotonic() + banner = build_banner(settings) + assert time.monotonic() - started < 1.5 + assert banner.logo == [[("logo", line)] for line in LOGOS["helm"]] + + +def test_missing_art_file_falls_back(home): + settings = make_settings(logo__source="file", logo__art_file=str(home / "missing.txt"), banner__modules=[]) + assert build_banner(settings).logo == [[("logo", line)] for line in LOGOS["helm"]] + + +# Modules + + +def test_run_with_deadline_reports_errors_and_timeouts(): + def fail(): + raise RuntimeError("boom") + + started = time.monotonic() + results = run_with_deadline([lambda: 1, fail, lambda: time.sleep(5)], 0.2) + assert time.monotonic() - started < 1 + assert results == {0: ("ok", 1), 1: ("error", None), 2: ("timeout", None)} + + +def test_custom_modules_and_separator(home): + modules = [ + {"type": "command", "label": "Hello", "command": python_command("print('\\n\\x1b[1mhi there\\x1b[0m')")}, + "separator", + {"type": "command", "label": "Broken", "command": python_command("import sys; sys.exit(1)")}, + {"type": "command", "label": "Slow", "command": python_command("import time; time.sleep(5)")}, + {"type": "command", "label": "Quiet", "command": python_command("pass")}, + ] + started = time.monotonic() + banner = build_banner(make_settings(banner__modules=modules, banner__timeout_ms=1500)) + assert time.monotonic() - started < 3 + assert [(entry.label, entry.value, entry.status) for entry in banner.entries] == [ + ("Hello", "hi there", "ok"), + ("", "", "separator"), + ("Broken", UNAVAILABLE, "error"), + ("Slow", TIMED_OUT, "timeout"), + ("Quiet", "none", "ok"), + ] + + +def entry_value(banner, label): + return next(entry.value for entry in banner.entries if entry.label == label) + + +def test_builtin_modules_without_services(home): + settings = make_settings( + search__lite_only=True, + banner__modules=["version", "mode", "indexers", "jobs", "downloads", "services"], + banner__timeout_ms=3000, + ) + banner = build_banner(settings) + assert all(entry.status == "ok" for entry in banner.entries), banner.entries + assert entry_value(banner, "Version") not in ("", "unknown") + assert entry_value(banner, "Mode") == "lite" + assert re.match(r"^\d+ Lite sources$", entry_value(banner, "Indexers")) + assert int(entry_value(banner, "Indexers").split()[0]) > 0 + assert entry_value(banner, "Jobs") == "none yet" + assert not (home / "state" / "jobs.sqlite3").exists() + assert "GiB free" in entry_value(banner, "Downloads") + assert entry_value(banner, "Services") == "not used in Lite mode" + + +def test_mode_follows_context_and_manager(home): + settings = make_settings(search__indexer_manager="both", banner__modules=["mode"]) + assert entry_value(build_banner(settings), "Mode") == "both" + assert entry_value(build_banner(settings, {"mode": "lite"}), "Mode") == "lite" + + +def test_jobs_module_counts_active_jobs(home): + from helm.core.jobs import JobStore + + store = JobStore() + magnets = [f"magnet:?xt=urn:btih:{str(index) * 40}" for index in range(4)] + jobs = [store.enqueue(magnet) for magnet in magnets] + store.update(jobs[0]["id"], "running") + store.update(jobs[1]["id"], "succeeded") + banner = build_banner(make_settings(banner__modules=["jobs"])) + assert entry_value(banner, "Jobs") == "1 running, 2 queued" + for job in jobs: + store.update(job["id"], "succeeded") + assert entry_value(build_banner(make_settings(banner__modules=["jobs"])), "Jobs") == "idle" + + +def test_downloads_module_shortens_home(home, monkeypatch): + monkeypatch.setenv("HELM_DL_DIR", os.path.join(os.path.expanduser("~"), "helm-banner-test-missing", "dl")) + value = entry_value(build_banner(make_settings(banner__modules=["downloads"])), "Downloads") + assert value.startswith("~" + os.sep + "helm-banner-test-missing") + + +def test_indexer_and_service_modules_against_real_servers(home, server, monkeypatch): + server.routes["/api/v2.0/indexers/all/results/torznab/api"] = ( + 200, + "application/xml", + b'', + ) + server.routes["/api/v1/indexer"] = ( + 200, + "application/json", + json.dumps([{"enable": True}, {"enable": False}]).encode(), + ) + monkeypatch.setenv("JACKETT_API_KEY", "jackett-key-123") + monkeypatch.setenv("PROWLARR_API_KEY", "prowlarr-key-456") + settings = make_settings( + search__indexer_manager="both", + services__jackett=server.url, + services__prowlarr=server.url, + services__qbittorrent="http://127.0.0.1:9", + banner__modules=["indexers", "services"], + banner__timeout_ms=3000, + ) + banner = build_banner(settings) + assert entry_value(banner, "Indexers") == "2 in jackett, 1 in prowlarr" + assert entry_value(banner, "Services") == "jackett up, prowlarr up, qbittorrent down" + assert any("configured=true" in path for path in server.routes["_seen"]) + + +def test_indexers_without_api_key(home): + banner = build_banner(make_settings(banner__modules=["indexers"])) + assert entry_value(banner, "Indexers") == "jackett has no API key" + + +def test_indexer_server_error_is_unavailable(home, server, monkeypatch): + monkeypatch.setenv("JACKETT_API_KEY", "jackett-key-123") + settings = make_settings(services__jackett=server.url, banner__modules=["indexers"], banner__timeout_ms=3000) + banner = build_banner(settings) + assert banner.entries[0].status == "error" + + +# Rendering + + +def sample_banner(position="left"): + return Banner( + [[("logo", "AB")], [("accent", "C"), (None, "\x1b[31mD\x1b[0m")]], + [Entry("Version", "1.0"), Entry("", status="separator"), Entry("Jobs", TIMED_OUT, "timeout")], + position, + ) + + +def test_render_plain_left_layout(): + text = render_banner(sample_banner(), load_theme(make_settings()), color=False) + assert text == "AB Version 1.0\nCD " + "─" * len("Jobs timed out") + "\n Jobs timed out\n" + + +def test_render_plain_top_layout_and_empty_parts(): + theme = load_theme(make_settings()) + assert render_banner(sample_banner("top"), theme, color=False).startswith("AB\nCD\n\nVersion 1.0\n") + assert render_banner(Banner([], [Entry("A", "b")]), theme, color=False) == "A b\n" + assert render_banner(Banner([[("logo", "X")]], []), theme, color=False) == "X\n" + assert render_banner(Banner(), theme, color=False) == "" + + +def test_render_colour_uses_theme_and_keeps_alignment(): + theme = load_theme(make_settings(theme__preset="catppuccin-mocha")) + text = render_banner(sample_banner(), theme, color=True) + assert sgr(PRESETS["catppuccin-mocha"]["logo"]) + "AB" in text + assert sgr(PRESETS["catppuccin-mocha"]["muted"]) + TIMED_OUT in text + assert "\x1b[31mD\x1b[0m" in text + plain = render_banner(sample_banner(), theme, color=False) + assert ANSI.sub("", text) == plain + + +def test_visible_width_counts_wide_and_combining_characters(): + assert visible_width("\x1b[31mab\x1b[0m") == 2 + assert visible_width("漢字") == 4 + assert visible_width("é") == 1 + + +def test_color_enabled_follows_environment(monkeypatch): + class Terminal: + def isatty(self): + return True + + monkeypatch.delenv("NO_COLOR", raising=False) + monkeypatch.delenv("FORCE_COLOR", raising=False) + assert color_enabled(Terminal()) + assert not color_enabled(object()) + monkeypatch.setenv("FORCE_COLOR", "1") + assert color_enabled(object()) + monkeypatch.setenv("NO_COLOR", "1") + assert not color_enabled(Terminal()) + + +# Command + + +def helm(*arguments, **extra_env): + environment = {key: value for key, value in os.environ.items() if key not in SCRUBBED} + environment["PYTHONPATH"] = SRC + environment.update(extra_env) + return subprocess.run( + [sys.executable, "-m", "helm.cli", *arguments], + env=environment, + stdin=subprocess.DEVNULL, + capture_output=True, + text=True, + timeout=60, + ) + + +def test_banner_command_prints_even_when_disabled(home): + (home / "config" / "config.toml").write_text("[banner]\nenabled = false\n") + result = helm("banner") + assert result.returncode == 0, result.stderr + assert LOGOS["helm"][0] in result.stdout + assert "Version" in result.stdout + assert "\x1b[" not in result.stdout + + +def test_banner_command_colours_when_forced(home): + result = helm("banner", FORCE_COLOR="1", HELM_THEME="nord") + assert sgr(PRESETS["nord"]["logo"]) in result.stdout + + +def test_banner_command_json_and_lite_mode(home): + result = helm("banner", "--json", "--lite") + assert result.returncode == 0, result.stderr + data = json.loads(result.stdout) + assert data["theme"] == "helm" + assert data["logo"] == LOGOS["helm"] + assert {"label": "Mode", "value": "lite", "status": "ok"} in data["modules"] + + +def test_slow_module_cannot_delay_the_command(home): + slow = json.dumps(python_command("import time; time.sleep(20)")) + (home / "config" / "config.toml").write_text( + f'[banner]\ntimeout_ms = 300\nmodules = ["version", {{ type = "command", label = "Slow", command = {slow} }}]\n' + ) + started = time.monotonic() + result = helm("banner") + elapsed = time.monotonic() - started + assert result.returncode == 0, result.stderr + assert "timed out" in result.stdout + assert elapsed < 10 + + +def test_banner_command_reports_bad_settings(home): + (home / "config" / "config.toml").write_text('[banner]\nmodules = ["weather"]\n') + result = helm("banner") + assert result.returncode == 1 + assert "unknown module" in result.stderr + assert "Traceback" not in result.stderr + + +def test_doctor_warns_about_logo_settings(home): + config = home / "config" / "config.toml" + cases = [ + ('source = "builtin:ship"', "unknown logo"), + ('source = "file"', "needs logo.art"), + (f'source = "file"\nart_file = "{home / "nope.txt"}"', "does not exist"), + ('source = "cmd:/nonexistent/figlet helm"', "not installed"), + ] + for body, message in cases: + config.write_text(f"[search]\nlite_only = true\n[logo]\n{body}\n") + result = helm("config", "doctor") + assert result.returncode == 0, result.stdout + assert any(message in line for line in result.stdout.splitlines() if line.startswith("[warn]")), result.stdout From 0a9529b76ffaed092aa75bd44190136415efbfe7 Mon Sep 17 00:00:00 2001 From: Piratebird <141295458+Piratebird@users.noreply.github.com> Date: Mon, 2 Nov 2026 23:20:51 +0200 Subject: [PATCH 05/18] :shipit: feat(ui): apply the theme across the current UI - Route every colour and terminal code in the CLI, UI, wizard, one-shot mode and Lite downloader through the theme - Keep ansi.py as the only file that writes escape codes, enforced by a test - Remove colors.py and move the wordmark to banner.py, pinned byte for byte - Add success, warning and info colours; the helm preset keeps the terminal's own - Show the banner at UI start, or the plain wordmark when banner.enabled is false - Turn colours off when piped or with NO_COLOR, and back on with FORCE_COLOR - Keep --json output plain even with FORCE_COLOR set --- CHANGELOG.md | 1 + README.md | 2 +- src/helm/cli.py | 97 +++++++++++------- src/helm/core/config_commands.py | 3 + src/helm/core/config_wizard.py | 25 ++--- src/helm/core/lite_downloader.py | 26 ++--- src/helm/core/oneshot.py | 38 +++---- src/helm/core/settings.py | 11 ++- src/helm/ui/ansi.py | 73 +++++++++++++- src/helm/ui/banner.py | 14 ++- src/helm/ui/colors.py | 31 ------ src/helm/ui/theme.py | 11 ++- src/helm/ui/tui.py | 85 ++++++++-------- tests/test_terminal_codes.py | 163 +++++++++++++++++++++++++++++++ tests/test_theme_banner.py | 37 +++++-- 15 files changed, 445 insertions(+), 172 deletions(-) delete mode 100644 src/helm/ui/colors.py create mode 100644 tests/test_terminal_codes.py diff --git a/CHANGELOG.md b/CHANGELOG.md index e1d4eeb..15d5f4b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ All notable changes to this project will be documented in this file. ## [Unreleased] ### Changed +- Use the theme everywhere the UI, wizard, one-shot mode and Lite downloader print colour, and show the banner when the UI starts. Colours are now off when output is piped or `NO_COLOR` is set. Red messages that used the terminal's basic red now use the theme's error colour. - Use one set of service defaults: Jackett `19117`, Prowlarr `19696`, qBittorrent `18080`. Set `[services]` for a native Jackett on `9117`. - Report invalid config files clearly instead of resetting them. Runtime choices are stored in `settings.json` in the state directory, below the user's file. - Start faster by deferring heavy imports, and split the CLI entry point into separate handlers. diff --git a/README.md b/README.md index 42ba10b..455c8ba 100644 --- a/README.md +++ b/README.md @@ -219,7 +219,7 @@ modules = ["version", "mode", "indexers", "jobs", "downloads"] timeout_ms = 400 ``` -`helm-torrent banner` prints the banner, and `--json` prints its data. Modules are `version`, `mode`, `indexers`, `jobs`, `downloads`, `services` and `separator`, plus your own commands, such as `{ type = "command", label = "Uptime", command = ["uptime", "-p"] }`. Commands run without a shell, and only the first line of their output is shown. All modules share the `timeout_ms` limit: a slow one shows `timed out`, a failing one shows `unavailable`, and a logo that fails falls back to the built-in one. For `source = "file"`, art can use `{logo}`, `{accent}`, `{text}`, `{line}`, `{muted}` and `{reset}` colour placeholders. `HELM_THEME` and `HELM_BANNER` override the file, and `NO_COLOR` turns colours off. +`helm-torrent banner` prints the banner, and `--json` prints its data. Modules are `version`, `mode`, `indexers`, `jobs`, `downloads`, `services` and `separator`, plus your own commands, such as `{ type = "command", label = "Uptime", command = ["uptime", "-p"] }`. Commands run without a shell, and only the first line of their output is shown. All modules share the `timeout_ms` limit: a slow one shows `timed out`, a failing one shows `unavailable`, and a logo that fails falls back to the built-in one. For `source = "file"`, art can use `{logo}`, `{accent}`, `{text}`, `{line}`, `{muted}` and `{reset}` colour placeholders. The theme colours the whole interface: the interactive UI, the setup wizard, one-shot mode and the Lite downloader. The banner shows when the UI starts, and with `enabled = false` only the plain wordmark does. `HELM_THEME` and `HELM_BANNER` override the file. Colours are off when output is not a terminal or `NO_COLOR` is set, and `FORCE_COLOR` turns them back on. `--json` output never contains colours or the banner. ## Usage diff --git a/src/helm/cli.py b/src/helm/cli.py index 38f8d9a..a65a196 100644 --- a/src/helm/cli.py +++ b/src/helm/cli.py @@ -14,7 +14,8 @@ from helm.core.logger import configure_logging, tail_log # noqa: E402 from helm.core.secret_manager import get_secret, get_secrets_file # noqa: E402 from helm.core.settings import ConfigError, load_settings, remember # noqa: E402 -from helm.ui.colors import C_ERR, C_LOGO, C_RST, C_SUB, C_TEXT, logo # noqa: E402 +from helm.ui.ansi import T # noqa: E402 +from helm.ui.banner import WORDMARK as logo # noqa: E402 def _lazy(module, name): @@ -46,10 +47,10 @@ def _send_magnet(selected, lite_mode, json_mode=False, success_msg="Torrent sent try: add_magnet(selected.link) if not json_mode: - print(f"{C_TEXT}{success_msg}{C_RST}") + print(f"{T.TEXT}{success_msg}{T.RST}") except Exception as e: print( - f"\n\033[33m[!] qBittorrent not available ({e}). Falling back to LITE MODE downloader...\033[0m\n", + f"\n{T.WARNING}[!] qBittorrent not available ({e}). Falling back to LITE MODE downloader...{T.RST}\n", file=sys.stderr, ) from helm.core.lite_downloader import download_magnet @@ -351,7 +352,7 @@ def _run_utility(command): if command == "paths": from helm.core.config_manager import get_config_dir, get_dl_dir, get_log_dir - print("\033[1m\033[36mHelm Data Locations:\033[0m") + print(f"{T.BOLD}{T.INFO}Helm Data Locations:{T.RST}") print(f" Configuration: {get_config_dir()}") print(f" State/Logs: {get_log_dir()}") print(f" Downloads: {get_dl_dir()}") @@ -406,14 +407,21 @@ def _run_utility(command): return +def _banner_context(args): + if args.lite: + return {"mode": "lite"} + if args.oneshot: + return {"mode": "one-shot"} + return {} + + def _cmd_banner(args): from helm.ui.ansi import color_enabled, render_banner from helm.ui.banner import build_banner from helm.ui.theme import load_theme settings = load_settings() - context = {"mode": "lite"} if args.lite else {} - banner = build_banner(settings, context) + banner = build_banner(settings, _banner_context(args)) if args.json: data = { "theme": settings.get("theme.preset"), @@ -422,8 +430,22 @@ def _cmd_banner(args): } print(json.dumps(data, ensure_ascii=False)) return - text = render_banner(banner, load_theme(settings), color=color_enabled(sys.stdout)) - sys.stdout.write(text) + sys.stdout.write(render_banner(banner, load_theme(settings), color=color_enabled(sys.stdout))) + + +def _print_header(args, subtitle): + """Print the banner at UI start, or the plain wordmark when banner.enabled is false.""" + settings = load_settings() + if settings.get("banner.enabled"): + from helm.ui.ansi import color_enabled, render_banner + from helm.ui.banner import build_banner + from helm.ui.theme import load_theme + + banner = build_banner(settings, _banner_context(args)) + sys.stdout.write("\n" + render_banner(banner, load_theme(settings), color=color_enabled(sys.stdout)) + "\n") + else: + print(f"{T.LOGO}{logo}{T.RST}") + print(f"{T.ACCENT}{subtitle}{T.RST}\n") def main(): @@ -431,7 +453,7 @@ def main(): try: run() except ConfigError as error: - print(f"\033[31m[!] {error}\033[0m", file=sys.stderr) + print(f"{T.ERROR}[!] {error}{T.RST}", file=sys.stderr) raise SystemExit(1) from None @@ -463,7 +485,7 @@ def run(): try: bootstrap_env() except (KeyboardInterrupt, EOFError): - print(f"\n{C_SUB}later bozo!{C_RST}") + print(f"\n{T.ACCENT}later bozo!{T.RST}") raise SystemExit(0) from None if args.command in ("paths", "logs", "bug-report"): @@ -488,7 +510,7 @@ def run(): try: choice = ( input( - f"\n\033[1m{C_TEXT}? No configuration found. Would you like to run in Lite Mode (zero setup)? [Y/n]:{C_RST} " + f"\n{T.BOLD}{T.TEXT}? No configuration found. Would you like to run in Lite Mode (zero setup)? [Y/n]:{T.RST} " ) .strip() .lower() @@ -499,7 +521,7 @@ def run(): else: ensure_config() except (KeyboardInterrupt, EOFError): - print(f"\n{C_SUB}later bozo!{C_RST}") + print(f"\n{T.ACCENT}later bozo!{T.RST}") raise SystemExit(0) from None else: ensure_config() @@ -532,7 +554,7 @@ def cleanup(): def _manage_indexers(args): if args.lite: - print(f"{C_ERR}Cannot manage Indexers in Lite Mode.{C_RST}", file=sys.stderr) + print(f"{T.ERROR}Cannot manage Indexers in Lite Mode.{T.RST}", file=sys.stderr) raise SystemExit(1) from None ensure_config() @@ -558,10 +580,10 @@ def _manage_indexers(args): manager = JackettManager() mgr_name = "Jackett" except Exception as e: - print(f"{C_ERR}Failed to initialize Manager: {e}{C_RST}", file=sys.stderr) + print(f"{T.ERROR}Failed to initialize Manager: {e}{T.RST}", file=sys.stderr) raise SystemExit(1) from None - sys.stdout.write(f"{C_LOGO}Fetching indexers from {mgr_name}...{C_RST}\r\n") + sys.stdout.write(f"{T.LOGO}Fetching indexers from {mgr_name}...{T.RST}\r\n") sys.stdout.flush() all_indexers = manager.get_all_indexers() @@ -570,24 +592,24 @@ def _manage_indexers(args): selected_indexer = interactive_indexer_selector(all_indexers) if selected_indexer: if selected_indexer["configured"]: - sys.stdout.write(f"\r\n{C_TEXT}Removing {selected_indexer['title']}...{C_RST}\r\n") + sys.stdout.write(f"\r\n{T.TEXT}Removing {selected_indexer['title']}...{T.RST}\r\n") sys.stdout.flush() try: manager.remove_indexer(selected_indexer["id"]) selected_indexer["configured"] = False except Exception as e: - sys.stdout.write(f"\r\n{C_ERR}Failed to remove: {e}{C_RST}\r\n") + sys.stdout.write(f"\r\n{T.ERROR}Failed to remove: {e}{T.RST}\r\n") sys.stdout.flush() time.sleep(2) else: if selected_indexer.get("type", "public") != "public": sys.stdout.write( - f"\r\n{C_ERR}Cannot add {selected_indexer['type']} trackers via CLI as they require credentials. Please use the Jackett Web UI ({manager.url}).{C_RST}\r\n" + f"\r\n{T.ERROR}Cannot add {selected_indexer['type']} trackers via CLI as they require credentials. Please use the Jackett Web UI ({manager.url}).{T.RST}\r\n" ) sys.stdout.flush() time.sleep(3) else: - sys.stdout.write(f"\r\n{C_TEXT}Adding {selected_indexer['title']}...{C_RST}\r\n") + sys.stdout.write(f"\r\n{T.TEXT}Adding {selected_indexer['title']}...{T.RST}\r\n") sys.stdout.flush() try: manager.add_indexer(selected_indexer["id"]) @@ -596,18 +618,18 @@ def _manage_indexers(args): error_msg = str(e) if "500" in error_msg: error_msg = "Jackett rejected the default config. Please configure this indexer manually via the Jackett Web UI." - sys.stdout.write(f"\r\n{C_ERR}Failed to add: {error_msg}{C_RST}\r\n") + sys.stdout.write(f"\r\n{T.ERROR}Failed to add: {error_msg}{T.RST}\r\n") sys.stdout.flush() time.sleep(3) except KeyboardInterrupt: - sys.stdout.write(f"\n{C_SUB}Exiting indexer management.{C_RST}\n") + sys.stdout.write(f"\n{T.ACCENT}Exiting indexer management.{T.RST}\n") sys.stdout.flush() try: - choice = input(f"\033[1m{C_TEXT}? Would you like to proceed to search? [Y/n]:{C_RST} ").strip().lower() + choice = input(f"{T.BOLD}{T.TEXT}? Would you like to proceed to search? [Y/n]:{T.RST} ").strip().lower() if choice == "n": raise SystemExit(0) from None except (KeyboardInterrupt, EOFError): - print(f"\n{C_SUB}later bozo!{C_RST}") + print(f"\n{T.ACCENT}later bozo!{T.RST}") raise SystemExit(0) from None @@ -618,8 +640,7 @@ def _run_session(args, teardown_oneshot): mode_str = " (ONE-SHOT MODE)" if args.oneshot else "" if not args.json and not args.query: - print(f"{C_LOGO}{logo}{C_RST}") - print(f"{C_SUB}THE HELM - Torrent automation MVP{mode_str}{C_RST}\n") + _print_header(args, f"THE HELM - Torrent automation MVP{mode_str}") # State Machine Loop state = "PROMPT" @@ -635,9 +656,9 @@ def _run_session(args, teardown_oneshot): state = "SEARCHING" else: try: - search_query = input(f"\033[1m{C_TEXT}? What would you like to search for:{C_RST} ").strip() + search_query = input(f"{T.BOLD}{T.TEXT}? What would you like to search for:{T.RST} ").strip() except (KeyboardInterrupt, EOFError): - print(f"\n{C_SUB}later bozo!{C_RST}") + print(f"\n{T.ACCENT}later bozo!{T.RST}") raise SystemExit(0) from None if not search_query: @@ -650,15 +671,15 @@ def _run_session(args, teardown_oneshot): ["video", "games", "software", "books", "music"], "Content type" ) except KeyboardInterrupt: - print(f"\n{C_SUB}later bozo!{C_RST}") + print(f"\n{T.ACCENT}later bozo!{T.RST}") raise SystemExit(0) from None if selected_cats == "BACK": # Go back to query prompt by staying in PROMPT - print("\033[2J\033[H", end="") + print(f"{T.CLEAR}{T.HOME}", end="") continue categories = selected_cats - print("\033[2J\033[H", end="") + print(f"{T.CLEAR}{T.HOME}", end="") state = "SEARCHING" elif state == "SEARCHING": @@ -689,12 +710,12 @@ def _run_session(args, teardown_oneshot): cleaned_query, ",".join(categories), lite_mode=args.lite, show_spinner=not args.json ) except KeyboardInterrupt: - print(f"\n{C_SUB}later bozo!{C_RST}") + print(f"\n{T.ACCENT}later bozo!{T.RST}") raise SystemExit(0) from None source_name = "Lite mode" if args.lite else "Jackett & Lite" if not args.json: - print(f"{C_LOGO}{source_name} returned {len(all_items)} raw results{C_RST}") + print(f"{T.LOGO}{source_name} returned {len(all_items)} raw results{T.RST}") min_seeds = load_settings().get("search.min_seeds") @@ -706,7 +727,7 @@ def _run_session(args, teardown_oneshot): print(json.dumps([])) raise SystemExit(1) from None else: - print(f"\n{C_ERR}No torrents were found :({C_RST}", file=sys.stderr) + print(f"\n{T.ERROR}No torrents were found :({T.RST}", file=sys.stderr) if not all_items and args.lite: print( "Lite sources may be unreachable or have no matches. " @@ -724,7 +745,7 @@ def _run_session(args, teardown_oneshot): raise SystemExit(1) from None else: input("Press Enter to try again...") - print("\033[2J\033[H", end="") + print(f"{T.CLEAR}{T.HOME}", end="") state = "PROMPT" continue @@ -766,7 +787,7 @@ def _run_session(args, teardown_oneshot): ) if do_teardown == "BACK": - print("\033[2J\033[H", end="") + print(f"{T.CLEAR}{T.HOME}", end="") if args.query: # Cannot go back if started from CLI args raise SystemExit(0) from None @@ -783,7 +804,7 @@ def _run_session(args, teardown_oneshot): break except KeyboardInterrupt: - print(f"\n{C_SUB}later bozo!{C_RST}") + print(f"\n{T.ACCENT}later bozo!{T.RST}") if do_teardown and not args.oneshot and not args.lite: try: teardown_oneshot() @@ -798,10 +819,10 @@ def _run_session(args, teardown_oneshot): except KeyboardInterrupt: import sys - print("\n\033[33m[!] Process interrupted by user.\033[0m", file=sys.stderr) + print(f"\n{T.WARNING}[!] Process interrupted by user.{T.RST}", file=sys.stderr) sys.exit(130) except Exception as e: import sys - print(f"\n\033[31m[!] An unexpected error occurred: {e}\033[0m", file=sys.stderr) + print(f"\n{T.ERROR}[!] An unexpected error occurred: {e}{T.RST}", file=sys.stderr) sys.exit(1) diff --git a/src/helm/core/config_commands.py b/src/helm/core/config_commands.py index 19779a3..7ae2f70 100644 --- a/src/helm/core/config_commands.py +++ b/src/helm/core/config_commands.py @@ -49,6 +49,9 @@ "theme.line": "Override the preset's line colour, used for separators.", "theme.error": "Override the preset's error colour.", "theme.muted": "Override the preset's muted colour, used for placeholders.", + "theme.success": "Override the preset's success colour.", + "theme.warning": "Override the preset's warning colour.", + "theme.info": "Override the preset's info colour, used for progress messages.", "logo.source": 'Logo to show: "builtin:helm", "file" (art or art_file), "cmd:" or "none".', "logo.position": "Logo position next to the banner text: left or top.", "logo.art": 'Your own art for source = "file". Colour placeholders: {logo} {accent} {text} {line} {muted} {reset}.', diff --git a/src/helm/core/config_wizard.py b/src/helm/core/config_wizard.py index f3c325b..3c2e093 100644 --- a/src/helm/core/config_wizard.py +++ b/src/helm/core/config_wizard.py @@ -5,18 +5,19 @@ from helm.core.secret_manager import get_secret, set_secrets from helm.core.settings import load_settings, remember +from helm.ui.ansi import T def save_answers(updates): for path in remember(updates): - print(f"\033[33m[WARN] {path} stays as set in your config file; edit it there to change it.\033[0m") + print(f"{T.WARNING}[WARN] {path} stays as set in your config file; edit it there to change it.{T.RST}") def run_wizard(): import sys try: - print("\033[1mWelcome to Helm Interactive Configuration Wizard!\033[0m") + print(f"{T.BOLD}Welcome to Helm Interactive Configuration Wizard!{T.RST}") print("It looks like some essential configurations are missing.\n") settings = load_settings() @@ -32,7 +33,7 @@ def run_wizard(): .lower() ) if choice not in ("y", "yes"): - print("\n\033[32mOpting for Lite Mode. You can change this later.\033[0m\n") + print(f"\n{T.SUCCESS}Opting for Lite Mode. You can change this later.{T.RST}\n") save_answers({"search.lite_only": True}) return @@ -93,7 +94,7 @@ def run_wizard(): while True: jackett_url_input = input(f"Jackett URL [{jackett_url}]: ").strip() if jackett_url_input.lower() in ("exit", "quit", "q") or "\x03" in jackett_url_input: - print("\n\033[33mConfiguration aborted. later bozo!\033[0m") + print(f"\n{T.WARNING}Configuration aborted. later bozo!{T.RST}") sys.exit(0) if jackett_url_input: jackett_url = jackett_url_input @@ -103,7 +104,7 @@ def run_wizard(): ) jackett_api_input = input(f"Jackett API Key [{masked_api}]: ").strip() if jackett_api_input.lower() in ("exit", "quit", "q") or "\x03" in jackett_api_input: - print("\n\033[33mConfiguration aborted. later bozo!\033[0m") + print(f"\n{T.WARNING}Configuration aborted. later bozo!{T.RST}") sys.exit(0) if jackett_api_input: jackett_api = jackett_api_input @@ -112,7 +113,7 @@ def run_wizard(): f"Jackett Admin Password (leave blank if none) [{'***' if jackett_pwd else ''}]: " ).strip() if jackett_pwd_input.lower() in ("exit", "quit", "q") or "\x03" in jackett_pwd_input: - print("\n\033[33mConfiguration aborted. later bozo!\033[0m") + print(f"\n{T.WARNING}Configuration aborted. later bozo!{T.RST}") sys.exit(0) if jackett_pwd_input: jackett_pwd = jackett_pwd_input @@ -155,21 +156,21 @@ def run_wizard(): while True: qb_webui_input = input(f"qBittorrent WebUI URL [{qb_webui}]: ").strip() if qb_webui_input.lower() in ("exit", "quit", "q") or "\x03" in qb_webui_input: - print("\n\033[33mConfiguration aborted. later bozo!\033[0m") + print(f"\n{T.WARNING}Configuration aborted. later bozo!{T.RST}") sys.exit(0) if qb_webui_input: qb_webui = qb_webui_input qb_username_input = input(f"qBittorrent Username [{qb_username}]: ").strip() if qb_username_input.lower() in ("exit", "quit", "q") or "\x03" in qb_username_input: - print("\n\033[33mConfiguration aborted. later bozo!\033[0m") + print(f"\n{T.WARNING}Configuration aborted. later bozo!{T.RST}") sys.exit(0) if qb_username_input: qb_username = qb_username_input qb_password_input = input(f"qBittorrent Password [{'***' if qb_password else ''}]: ").strip() if qb_password_input.lower() in ("exit", "quit", "q") or "\x03" in qb_password_input: - print("\n\033[33mConfiguration aborted. later bozo!\033[0m") + print(f"\n{T.WARNING}Configuration aborted. later bozo!{T.RST}") sys.exit(0) if qb_password_input: qb_password = qb_password_input @@ -205,11 +206,11 @@ def run_wizard(): save_answers(updates) print("Configuration saved! Secrets are in secrets.env.\n") except KeyboardInterrupt: - print("\n\n\033[33mConfiguration aborted. later bozo!\033[0m") + print(f"\n\n{T.WARNING}Configuration aborted. later bozo!{T.RST}") sys.exit(0) except EOFError: print( - "\n\n\033[31m[ERROR] Cannot read input. If you are running via Docker, make sure to use the '-it' flag for interactive mode, or mount your configuration files!\033[0m" + f"\n\n{T.ERROR}[ERROR] Cannot read input. If you are running via Docker, make sure to use the '-it' flag for interactive mode, or mount your configuration files!{T.RST}" ) sys.exit(1) @@ -249,7 +250,7 @@ def ensure_config(): if needs_wizard: if not sys.stdin.isatty(): print( - "\n\033[33m[WARN] Missing configuration keys, but running non-interactively (e.g. Docker). Skipping interactive wizard.\033[0m\n" + f"\n{T.WARNING}[WARN] Missing configuration keys, but running non-interactively (e.g. Docker). Skipping interactive wizard.{T.RST}\n" ) # We don't exit here so the rest of the app can try to run, or fail with a native API error else: diff --git a/src/helm/core/lite_downloader.py b/src/helm/core/lite_downloader.py index 2e8ce54..2a89c80 100644 --- a/src/helm/core/lite_downloader.py +++ b/src/helm/core/lite_downloader.py @@ -2,14 +2,16 @@ import sys import time +from helm.ui.ansi import T + def download_magnet(magnet_link, save_path=None, on_complete=None): try: import libtorrent as lt except ImportError: - print("\n\033[33m[!] libtorrent is not installed.\033[0m") + print(f"\n{T.WARNING}[!] libtorrent is not installed.{T.RST}") print("To use the built-in lite downloader, install 'helm-torrent[download]' where supported.") - print(f"\n\033[1mMagnet Link:\033[0m {magnet_link}\n") + print(f"\n{T.BOLD}Magnet Link:{T.RST} {magnet_link}\n") print("Copy the above link and paste it into your torrent client.") return False @@ -39,7 +41,7 @@ def download_magnet(magnet_link, save_path=None, on_complete=None): source = resolve_torrent(magnet_link) ses = lt.session(settings) - print("\n\033[1m\033[34mAdding magnet link to libtorrent session...\033[0m") + print(f"\n{T.BOLD}{T.INFO}Adding magnet link to libtorrent session...{T.RST}") try: # Parse the magnet URI properly for libtorrent 2.x @@ -61,12 +63,12 @@ def download_magnet(magnet_link, save_path=None, on_complete=None): sys.stdout.flush() elapsed += 1 if elapsed >= timeout: - print("\n\n\033[31m[!] Timeout reaching metadata. The torrent might be dead or blocked.\033[0m") + print(f"\n\n{T.ERROR}[!] Timeout reaching metadata. The torrent might be dead or blocked.{T.RST}") print(f"Fallback Magnet Link: {magnet_link}") return False print("\nMetadata downloaded. Starting torrent download...") - print(f"Saving to: \033[1m{os.path.abspath(save_path)}\033[0m\n") + print(f"Saving to: {T.BOLD}{os.path.abspath(save_path)}{T.RST}\n") while handle.status().state != lt.torrent_status.seeding: s = handle.status() @@ -82,9 +84,9 @@ def download_magnet(magnet_link, save_path=None, on_complete=None): ] sys.stdout.write( - f"\r\033[K\033[1m{s.progress * 100:.2f}%\033[0m complete " - f"(down: \033[32m{s.download_rate / 1000:.1f} kB/s\033[0m | " - f"up: \033[31m{s.upload_rate / 1000:.1f} kB/s\033[0m | " + f"\r{T.EOL}{T.BOLD}{s.progress * 100:.2f}%{T.RST} complete " + f"(down: {T.SUCCESS}{s.download_rate / 1000:.1f} kB/s{T.RST} | " + f"up: {T.ERROR}{s.upload_rate / 1000:.1f} kB/s{T.RST} | " f"peers: {s.num_peers}) [{state_str[s.state]}]" ) sys.stdout.flush() @@ -93,9 +95,9 @@ def download_magnet(magnet_link, save_path=None, on_complete=None): for a in alerts: msg = a.message() if "Permission denied" in msg or "file_open error" in msg or "access denied" in msg.lower(): - sys.stdout.write(f"\n\n\033[31m[DISK ERROR] {msg}\033[0m\n") + sys.stdout.write(f"\n\n{T.ERROR}[DISK ERROR] {msg}{T.RST}\n") sys.stdout.write( - f"\033[33mEnsure you have write permissions to {os.path.abspath(save_path)}\033[0m\n" + f"{T.WARNING}Ensure you have write permissions to {os.path.abspath(save_path)}{T.RST}\n" ) return False @@ -105,9 +107,9 @@ def download_magnet(magnet_link, save_path=None, on_complete=None): info = handle.torrent_file() files = info.files() on_complete([os.path.join(save_path, files.file_path(index)) for index in range(files.num_files())]) - print("\n\n\033[32m\033[1mDownload complete!\033[0m") + print(f"\n\n{T.SUCCESS}{T.BOLD}Download complete!{T.RST}") except KeyboardInterrupt: - print("\n\n\033[33mDownload interrupted by user. Cleaning up session...\033[0m") + print(f"\n\n{T.WARNING}Download interrupted by user. Cleaning up session...{T.RST}") return False finally: ses.pause() diff --git a/src/helm/core/oneshot.py b/src/helm/core/oneshot.py index 3ee0ff5..cc3222e 100644 --- a/src/helm/core/oneshot.py +++ b/src/helm/core/oneshot.py @@ -6,6 +6,8 @@ import requests +from helm.ui.ansi import T + def print(*args, **kwargs): # Route this module's boot/teardown logs to stderr so `--json` output on @@ -33,8 +35,8 @@ def _container_name(service): def spin_up_oneshot(): - print("\n\033[1m\033[36mInitializing One-Shot Ephemeral Stack...\033[0m") - print("\033[3mBringing up Jackett, Prowlarr, Flaresolverr, and qBittorrent via docker compose...\033[0m") + print(f"\n{T.BOLD}{T.INFO}Initializing One-Shot Ephemeral Stack...{T.RST}") + print(f"{T.ITALIC}Bringing up Jackett, Prowlarr, Flaresolverr, and qBittorrent via docker compose...{T.RST}") from helm.core.config_manager import get_state_dir @@ -54,7 +56,7 @@ def spin_up_oneshot(): pass def check_container_status(service_name, timeout=45): - print(f"\033[3mWaiting for {service_name} to stabilize...\033[0m") + print(f"{T.ITALIC}Waiting for {service_name} to stabilize...{T.RST}") elapsed = 0 while elapsed < timeout: try: @@ -71,7 +73,7 @@ def check_container_status(service_name, timeout=45): return True elif status == "exited": print( - f"\033[31m[ERROR] Container {service_name} crashed immediately. Check 'docker compose logs {service_name}'\033[0m" + f"{T.ERROR}[ERROR] Container {service_name} crashed immediately. Check 'docker compose logs {service_name}'{T.RST}" ) for svc in CONTAINER_SERVICES: _docker_run(["stop", _container_name(svc)], capture_output=True) @@ -80,14 +82,14 @@ def check_container_status(service_name, timeout=45): pass time.sleep(5) elapsed += 5 - print(f"\033[31m[WARNING] Timeout waiting for {service_name} to stabilize.\033[0m") + print(f"{T.ERROR}[WARNING] Timeout waiting for {service_name} to stabilize.{T.RST}") return False check_container_status("jackett") check_container_status("prowlarr") check_container_status("qbittorrent") check_container_status("flaresolverr") - print("\033[36mWaiting for internal HTTP servers to fully boot (this ensures 1337x doesn't fail)...\033[0m") + print(f"{T.INFO}Waiting for internal HTTP servers to fully boot (this ensures 1337x doesn't fail)...{T.RST}") # Wait for Jackett to respond to HTTP requests jackett_url = os.environ.get("JACKETT_URL", "http://jackett:9117") @@ -103,7 +105,7 @@ def check_container_status(service_name, timeout=45): time.sleep(2) if not jackett_ready: - print("\033[31m[WARNING] Jackett HTTP API didn't respond in time.\033[0m") + print(f"{T.ERROR}[WARNING] Jackett HTTP API didn't respond in time.{T.RST}") # Wait for Flaresolverr to respond to HTTP requests flaresolverr_url = os.environ.get("FLARESOLVERR_URL", "http://flaresolverr:8191") @@ -119,13 +121,13 @@ def check_container_status(service_name, timeout=45): time.sleep(2) if not flaresolverr_ready: - print("\033[31m[WARNING] Flaresolverr HTTP API didn't respond in time.\033[0m") + print(f"{T.ERROR}[WARNING] Flaresolverr HTTP API didn't respond in time.{T.RST}") - print("\033[32mEnvironment variables loaded and APIs ready.\033[0m\n") + print(f"{T.SUCCESS}Environment variables loaded and APIs ready.{T.RST}\n") def teardown_oneshot(): - print("\n\033[1m\033[33mTearing down the ephemeral stack to save processing power...\033[0m") + print(f"\n{T.BOLD}{T.WARNING}Tearing down the ephemeral stack to save processing power...{T.RST}") try: # Stop containers individually via 'docker stop' instead of 'docker compose stop' # to avoid network namespace destruction that triggers "rootless netns: permission denied" @@ -134,14 +136,14 @@ def teardown_oneshot(): _docker_run(["stop", _container_name(svc)], capture_output=True) except KeyboardInterrupt: pass - print("\033[1m\033[32mAll containers stopped cleanly. Your RAM is free!\033[0m") + print(f"{T.BOLD}{T.SUCCESS}All containers stopped cleanly. Your RAM is free!{T.RST}") except Exception as e: - print(f"\033[31mCould not tear down docker-compose stack: {e}\033[0m") + print(f"{T.ERROR}Could not tear down docker-compose stack: {e}{T.RST}") def wait_for_download(): - print("\n\033[36mWaiting for download to complete before tearing down the stack...\033[0m") - print("\033[3m(Press Ctrl+C to cancel, or Ctrl+P then Ctrl+Q to detach and run in background)\033[0m") + print(f"\n{T.INFO}Waiting for download to complete before tearing down the stack...{T.RST}") + print(f"{T.ITALIC}(Press Ctrl+C to cancel, or Ctrl+P then Ctrl+Q to detach and run in background){T.RST}") import helm.core.qbittorrent_client as qbc @@ -166,19 +168,19 @@ def wait_for_download(): name = t.get("name", "Unknown") if progress < 1.0: all_done = False - print(f"\r\033[33mDownloading '{name[:40]}...' ({progress * 100:.1f}%) \033[0m", end="") + print(f"\r{T.WARNING}Downloading '{name[:40]}...' ({progress * 100:.1f}%) {T.RST}", end="") sys.stdout.flush() if all_done: - print("\n\033[1m\033[32mDownload(s) 100% complete!\033[0m") + print(f"\n{T.BOLD}{T.SUCCESS}Download(s) 100% complete!{T.RST}") break except Exception: pass time.sleep(3) except KeyboardInterrupt: - print("\n\033[31mDownload cancelled by user!\033[0m") - print("\033[3mRemoving unfinished torrents from qBittorrent...\033[0m") + print(f"\n{T.ERROR}Download cancelled by user!{T.RST}") + print(f"{T.ITALIC}Removing unfinished torrents from qBittorrent...{T.RST}") try: r = session.get(f"{qb_webui}/api/v2/torrents/info", timeout=15) if r.status_code == 200: diff --git a/src/helm/core/settings.py b/src/helm/core/settings.py index 1788197..fb8a46c 100644 --- a/src/helm/core/settings.py +++ b/src/helm/core/settings.py @@ -38,7 +38,7 @@ class Field: THEMES = ("helm", "tokyo-night", "nord", "catppuccin-mocha") -COLOR_NAMES = ("logo", "accent", "text", "line", "error", "muted") +COLOR_NAMES = ("logo", "accent", "text", "line", "error", "muted", "success", "warning", "info") MODULE_NAMES = ("version", "mode", "indexers", "jobs", "downloads", "services", "separator") DEFAULT_MODULES = ("version", "mode", "indexers", "jobs", "downloads") HEX_COLOR = re.compile(r"^#[0-9A-Fa-f]{6}$") @@ -49,7 +49,14 @@ class Field: "line": "#CD6133", "error": "#FF5252", "muted": "#918383", + # The current UI uses the terminal's own palette for these, so the helm + # preset keeps them as basic ANSI colours instead of fixed hex values. + "success": "ansi:32", + "warning": "ansi:33", + "info": "ansi:36", } +COLOR_EXAMPLES = {name: value for name, value in HELM_COLORS.items() if value.startswith("#")} +COLOR_EXAMPLES.update({"success": "#4CAF50", "warning": "#E0AF68", "info": "#7DCFFF"}) FIELDS = ( Field("search.min_seeds", "int", 3, legacy="min_seeds", minimum=0), @@ -76,7 +83,7 @@ class Field: legacy="QB_DOWNLOADS_ROOT", ), Field("theme.preset", "str", "helm", env="HELM_THEME", choices=THEMES), - *(Field(f"theme.{name}", "color", None, example=HELM_COLORS[name]) for name in COLOR_NAMES), + *(Field(f"theme.{name}", "color", None, example=COLOR_EXAMPLES[name]) for name in COLOR_NAMES), Field("logo.source", "logo", "builtin:helm"), Field("logo.position", "str", "left", choices=("left", "top")), Field("logo.art", "art", None, example="{logo} ~~ my helm ~~ {accent}<3"), diff --git a/src/helm/ui/ansi.py b/src/helm/ui/ansi.py index 06e13ec..ea73718 100644 --- a/src/helm/ui/ansi.py +++ b/src/helm/ui/ansi.py @@ -1,6 +1,7 @@ """ANSI renderer for banner data and theme colours. The only place that writes escapes.""" import os +import sys import unicodedata from helm.ui.banner import SGR @@ -10,9 +11,31 @@ GAP = " " -def sgr(hex_color): - """Return the 24-bit foreground escape for a #RRGGBB colour.""" - value = hex_color.lstrip("#") +# Terminal controls. They are not colours, so they stay on when colour is off. +EOL = "\033[K" # Clear to the end of the line +HOME = "\033[H" +CLEAR = "\033[2J" +CLEAR_DOWN = "\033[J" +HIDE_CURSOR = "\033[?25l" +SHOW_CURSOR = "\033[?25h" +ITALIC = "\033[3m" +REVERSE = "\033[7m" +CONTROLS = { + "EOL": EOL, + "HOME": HOME, + "CLEAR": CLEAR, + "CLEAR_DOWN": CLEAR_DOWN, + "HIDE_CURSOR": HIDE_CURSOR, + "SHOW_CURSOR": SHOW_CURSOR, +} +STYLES = {"RST": RESET, "BOLD": BOLD, "ITALIC": ITALIC, "REVERSE": REVERSE} + + +def sgr(color): + """Return the foreground escape for "#RRGGBB" or a basic "ansi:NN" colour.""" + if color.startswith("ansi:"): + return f"\033[{int(color[5:])}m" + value = color.lstrip("#") red, green, blue = (int(value[index : index + 2], 16) for index in (0, 2, 4)) return f"\033[38;2;{red};{green};{blue}m" @@ -94,3 +117,47 @@ def render_banner(banner, theme, color=True): left += " " * (width - visible_width(left)) + GAP lines.append(left + right) return "\n".join(lines) + "\n" if lines else "" + + +class Terminal: + """Named escape codes for the current theme, resolved on first use. + + Use it as T.LOGO, T.ACCENT, T.BOLD, T.RST, T.EOL and so on. Colours and + styles are empty when stdout is not a terminal or NO_COLOR is set. The theme + is read lazily, after the CLI has applied --config-dir and similar flags. + """ + + def __init__(self): + self._codes = None + + def _build(self): + from helm.core.settings import COLOR_NAMES, ConfigError, Settings, load_settings + from helm.ui.theme import load_theme + + try: + theme = load_theme(load_settings()) + except ConfigError: + # A broken config is reported elsewhere; colours must not crash. + theme = load_theme(Settings()) + color = color_enabled(sys.stdout) + codes = dict(CONTROLS) + codes.update({name: code if color else "" for name, code in STYLES.items()}) + codes.update({name.upper(): sgr(theme.get(name)) if color else "" for name in COLOR_NAMES}) + return codes + + def __getattr__(self, name): + if name.startswith("_"): + raise AttributeError(name) + if self._codes is None: + self._codes = self._build() + try: + return self._codes[name] + except KeyError: + raise AttributeError(name) from None + + def reset(self): + """Forget the resolved theme, so the next use reads settings again.""" + self._codes = None + + +T = Terminal() diff --git a/src/helm/ui/banner.py b/src/helm/ui/banner.py index a764456..0a48351 100644 --- a/src/helm/ui/banner.py +++ b/src/helm/ui/banner.py @@ -18,10 +18,18 @@ from typing import List, Optional, Tuple from helm.core.config_manager import get_config_dir, get_dl_dir, get_state_dir -from helm.ui.colors import logo as wordmark -# The current UI's wordmark, shared so the default look cannot drift. -LOGOS = {"helm": wordmark.strip("\n").split("\n")} +# The current UI's block wordmark. +LOGOS = { + "helm": [ + "▗▖ ▗▖▗▄▄▄▖▗▖ ▗▖ ▗▖", + "▐▌ ▐▌▐▌ ▐▌ ▐▛▚▞▜▌", + "▐▛▀▜▌▐▛▀▀▘▐▌ ▐▌ ▐▌", + "▐▌ ▐▌▐▙▄▄▖▐▙▄▄▖▐▌ ▐▌", + ], +} +# The wordmark as one string, with the surrounding blank lines the UI prints. +WORDMARK = "\n" + "\n".join(LOGOS["helm"]) + "\n" PLACEHOLDER = re.compile(r"\{(logo|accent|text|line|error|muted|reset)\}") SGR = re.compile(r"\x1b\[[0-9;]*m") # Any other escape sequence or control character from a command is dropped. diff --git a/src/helm/ui/colors.py b/src/helm/ui/colors.py deleted file mode 100644 index b653362..0000000 --- a/src/helm/ui/colors.py +++ /dev/null @@ -1,31 +0,0 @@ -def hex_to_ansi(hex_color): - hex_color = hex_color.lstrip("#") - r, g, b = tuple(int(hex_color[i : i + 2], 16) for i in (0, 2, 4)) - return f"\033[38;2;{r};{g};{b}m" - - -class Palette: - # change color pallete or move to textual idk vro - NAVY = hex_to_ansi("#192A56") # Text 'The HELM' - MAROON = hex_to_ansi("#542023") # Steering Wheel - BROWN = hex_to_ansi("#5C4026") # Anchor and Ropes - CREAM = hex_to_ansi("#EADAC9") # Background - LIGHT_NAVY = hex_to_ansi("#4A69BD") # Brighter variant for readability - BRIGHT_MAROON = hex_to_ansi("#B33939") - BRIGHT_BROWN = hex_to_ansi("#CD6133") - RESET = "\033[0m" - - -C_LOGO = Palette.LIGHT_NAVY -C_SUB = Palette.BRIGHT_MAROON -C_TEXT = Palette.CREAM -C_LINE = Palette.BRIGHT_BROWN -C_ERR = hex_to_ansi("#FF5252") -C_RST = Palette.RESET - -logo = r""" -▗▖ ▗▖▗▄▄▄▖▗▖ ▗▖ ▗▖ -▐▌ ▐▌▐▌ ▐▌ ▐▛▚▞▜▌ -▐▛▀▜▌▐▛▀▀▘▐▌ ▐▌ ▐▌ -▐▌ ▐▌▐▙▄▄▖▐▙▄▄▖▐▌ ▐▌ -""" diff --git a/src/helm/ui/theme.py b/src/helm/ui/theme.py index 30064fb..d9601d9 100644 --- a/src/helm/ui/theme.py +++ b/src/helm/ui/theme.py @@ -14,7 +14,7 @@ from helm.core.settings import COLOR_NAMES, HELM_COLORS PRESETS: Dict[str, Dict[str, str]] = { - # The colours the current UI hardcodes in helm.ui.colors, so the default look stays the same. + # The colours the UI used before themes existed, so the default look stays the same. "helm": dict(HELM_COLORS), "tokyo-night": { "logo": "#7aa2f7", # blue @@ -23,6 +23,9 @@ "line": "#ff9e64", # orange "error": "#f7768e", # red "muted": "#565f89", # comment + "success": "#9ece6a", # green + "warning": "#e0af68", # yellow + "info": "#7dcfff", # cyan }, "nord": { "logo": "#88c0d0", # nord8 @@ -31,6 +34,9 @@ "line": "#d08770", # nord12 "error": "#bf616a", # nord11 "muted": "#4c566a", # nord3 + "success": "#a3be8c", # nord14 + "warning": "#ebcb8b", # nord13 + "info": "#8fbcbb", # nord7 }, "catppuccin-mocha": { "logo": "#89b4fa", # blue @@ -39,6 +45,9 @@ "line": "#fab387", # peach "error": "#f38ba8", # red "muted": "#6c7086", # overlay0 + "success": "#a6e3a1", # green + "warning": "#f9e2af", # yellow + "info": "#89dceb", # sky }, } diff --git a/src/helm/ui/tui.py b/src/helm/ui/tui.py index 3988280..8391822 100644 --- a/src/helm/ui/tui.py +++ b/src/helm/ui/tui.py @@ -13,7 +13,8 @@ import tty import unicodedata # noqa: E402 -from helm.ui.colors import C_LINE, C_LOGO, C_RST, C_SUB, C_TEXT, logo # noqa: E402 +from helm.ui.ansi import T # noqa: E402 +from helm.ui.banner import WORDMARK as logo # noqa: E402 def _read_key(fd): @@ -75,7 +76,7 @@ def animate(): chars = [". ", ".. ", "...", " "] i = 0 while not done: - sys.stdout.write(f"\r{C_LOGO}Searching" + chars[i % 4] + f"{C_RST}") + sys.stdout.write(f"\r{T.LOGO}Searching" + chars[i % 4] + T.RST) sys.stdout.flush() time.sleep(0.4) i += 1 @@ -175,19 +176,19 @@ def _append_scroll_footer(buf, count, start, stop, limit): return remaining = count - stop if remaining > 0: - buf.append(f"\033[K\r\n\033[3m{C_SUB}... and {remaining} more items below{C_RST}\033[0m\033[K\r\n") + buf.append(f"{T.EOL}\r\n{T.ITALIC}{T.ACCENT}... and {remaining} more items below{T.RST}{T.RST}{T.EOL}\r\n") if start > 0: - buf.append(f"\033[K\r\n\033[3m{C_SUB}... and {start} items above{C_RST}\033[0m\033[K\r\n") + buf.append(f"{T.EOL}\r\n{T.ITALIC}{T.ACCENT}... and {start} items above{T.RST}{T.RST}{T.EOL}\r\n") def _enter_raw_input(fd): if not IS_WINDOWS: tty.setraw(sys.stdin.fileno()) - sys.stdout.write("\033[?25l") + sys.stdout.write(T.HIDE_CURSOR) def _exit_raw_input(fd, old_settings): - sys.stdout.write("\033[?25h") + sys.stdout.write(T.SHOW_CURSOR) if not IS_WINDOWS: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) @@ -201,10 +202,10 @@ def interactive_indexer_selector(indexer_list): def redraw(): nonlocal selected_index buf = [] - buf.append("\033[H") - logo_crlf = logo.replace("\n", "\033[K\r\n") - buf.append(f"{C_LOGO}{logo_crlf}{C_RST}\033[K\r\n") - buf.append(f"{C_SUB}THE HELM - Indexer Management{C_RST}\033[K\r\n\033[K\r\n") + buf.append(T.HOME) + logo_crlf = logo.replace("\n", f"{T.EOL}\r\n") + buf.append(f"{T.LOGO}{logo_crlf}{T.RST}{T.EOL}\r\n") + buf.append(f"{T.ACCENT}THE HELM - Indexer Management{T.RST}{T.EOL}\r\n{T.EOL}\r\n") search_term = current_input.lower() if search_term.startswith("/"): @@ -224,15 +225,15 @@ def redraw(): window_items = disp_items[start_idx:stop_idx] buf.append( - f"\033[1m{C_TEXT}Found {len(disp_items)} indexers (showing {start_idx + 1}-{start_idx + len(window_items)}):{C_RST}\033[K\r\n" + f"{T.BOLD}{T.TEXT}Found {len(disp_items)} indexers (showing {start_idx + 1}-{start_idx + len(window_items)}):{T.RST}{T.EOL}\r\n" ) - buf.append(f"{C_LINE}" + "━" * 80 + f"{C_RST}\033[K\r\n") + buf.append(T.LINE + "━" * 80 + f"{T.RST}{T.EOL}\r\n") for i, idx in enumerate(window_items): actual_i = start_idx + i title = _truncate_to_width(idx["title"], 40) - status = "\033[32m[CONFIGURED]\033[0m" if idx["configured"] else "\033[31m[UNCONFIGURED]\033[0m" + status = f"{T.SUCCESS}[CONFIGURED]{T.RST}" if idx["configured"] else f"{T.ERROR}[UNCONFIGURED]{T.RST}" typ = idx.get("type", "unknown") title_pad = max(2, 42 - get_display_width(title)) @@ -240,18 +241,18 @@ def redraw(): if actual_i == selected_index: buf.append( - f"\033[7m\033[1m{C_LOGO} ❯ {title}{C_RST}\033[7m{' ' * title_pad}{C_TEXT}{info_str}{C_RST}\033[K\r\n" + f"{T.REVERSE}{T.BOLD}{T.LOGO} ❯ {title}{T.RST}{T.REVERSE}{' ' * title_pad}{T.TEXT}{info_str}{T.RST}{T.EOL}\r\n" ) else: buf.append( - f"\033[1m{C_SUB} {C_RST} {C_LOGO}{title}{C_RST}{' ' * title_pad}\033[1m{C_TEXT}{info_str}{C_RST}\033[K\r\n" + f"{T.BOLD}{T.ACCENT} {T.RST} {T.LOGO}{title}{T.RST}{' ' * title_pad}{T.BOLD}{T.TEXT}{info_str}{T.RST}{T.EOL}\r\n" ) _append_scroll_footer(buf, len(disp_items), start_idx, stop_idx, limit) - buf.append(f"{C_LINE}" + "━" * 80 + f"{C_RST}\033[K\r\n") - prompt = f"\033[1m{C_TEXT}❯ Search (Arrows=Move, Enter=Toggle Config, Esc/Ctrl-C=Exit):{C_RST} {current_input}" - buf.append(prompt + "\033[J") + buf.append(T.LINE + "━" * 80 + f"{T.RST}{T.EOL}\r\n") + prompt = f"{T.BOLD}{T.TEXT}❯ Search (Arrows=Move, Enter=Toggle Config, Esc/Ctrl-C=Exit):{T.RST} {current_input}" + buf.append(prompt + T.CLEAR_DOWN) sys.stdout.write("".join(buf)) sys.stdout.flush() return disp_items @@ -305,11 +306,11 @@ def interactive_selector(filtered_list, mode_str="", lite_mode=False, media_type def redraw(): nonlocal selected_index buf = [] - buf.append("\033[H") + buf.append(T.HOME) - logo_crlf = logo.replace("\n", "\033[K\r\n") - buf.append(f"{C_LOGO}{logo_crlf}{C_RST}\033[K\r\n") - buf.append(f"{C_SUB}THE HELM - Torrent automation MVP{mode_str}{C_RST}\033[K\r\n\033[K\r\n") + logo_crlf = logo.replace("\n", f"{T.EOL}\r\n") + buf.append(f"{T.LOGO}{logo_crlf}{T.RST}{T.EOL}\r\n") + buf.append(f"{T.ACCENT}THE HELM - Torrent automation MVP{mode_str}{T.RST}{T.EOL}\r\n{T.EOL}\r\n") raw_terms = current_input.lower().split() title_terms = [] @@ -368,9 +369,9 @@ def redraw(): window_items = disp_items[start_idx:stop_idx] buf.append( - f"\033[1m{C_TEXT}Found {len(disp_items)} results (showing {start_idx + 1}-{start_idx + len(window_items)}):{C_RST}\033[K\r\n" + f"{T.BOLD}{T.TEXT}Found {len(disp_items)} results (showing {start_idx + 1}-{start_idx + len(window_items)}):{T.RST}{T.EOL}\r\n" ) - buf.append(f"{C_LINE}" + "━" * 80 + f"{C_RST}\033[K\r\n") + buf.append(T.LINE + "━" * 80 + f"{T.RST}{T.EOL}\r\n") for i, t in enumerate(window_items): actual_i = start_idx + i @@ -400,27 +401,27 @@ def redraw(): info_str = f"[{size_str:>9}] [{date_str:>10}] [{seeds:>4}↑ {leechs:>3}↓] [{indexer}]" if has_tag: - title = f"\033[33m{tag}{C_LOGO} {title}" + title = f"{T.WARNING}{tag}{T.LOGO} {title}" if actual_i == selected_index: buf.append( - f"\033[7m\033[1m{C_LOGO} ❯ {title}{C_RST}\033[7m{' ' * title_pad}{C_TEXT}{info_str}{C_RST}\033[K\r\n" + f"{T.REVERSE}{T.BOLD}{T.LOGO} ❯ {title}{T.RST}{T.REVERSE}{' ' * title_pad}{T.TEXT}{info_str}{T.RST}{T.EOL}\r\n" ) else: buf.append( - f"\033[1m{C_SUB} {C_RST}{C_LOGO}{title}{C_RST}{' ' * title_pad}\033[1m{C_TEXT}{info_str}{C_RST}\033[K\r\n" + f"{T.BOLD}{T.ACCENT} {T.RST}{T.LOGO}{title}{T.RST}{' ' * title_pad}{T.BOLD}{T.TEXT}{info_str}{T.RST}{T.EOL}\r\n" ) _append_scroll_footer(buf, len(disp_items), start_idx, stop_idx, limit) - buf.append(f"{C_LINE}" + "━" * 80 + f"{C_RST}\033[K\r\n") + buf.append(T.LINE + "━" * 80 + f"{T.RST}{T.EOL}\r\n") if lite_mode: - prompt = f"\033[1m{C_TEXT}❯ Filter (cat:video, sort:size | Esc=Back, Ctrl-C=Exit):{C_RST} {current_input}" + prompt = f"{T.BOLD}{T.TEXT}❯ Filter (cat:video, sort:size | Esc=Back, Ctrl-C=Exit):{T.RST} {current_input}" else: - prompt = f"\033[1m{C_TEXT}❯ Filter (cat:video, sort:size | Esc=Back, Ctrl-C=Exit, Ctrl-E=Teardown):{C_RST} {current_input}" + prompt = f"{T.BOLD}{T.TEXT}❯ Filter (cat:video, sort:size | Esc=Back, Ctrl-C=Exit, Ctrl-E=Teardown):{T.RST} {current_input}" - buf.append(prompt + "\033[J") + buf.append(prompt + T.CLEAR_DOWN) sys.stdout.write("".join(buf)) sys.stdout.flush() return disp_items @@ -481,25 +482,25 @@ def interactive_checkbox_selector(options, title_msg="Select categories", defaul def redraw(): buf = [] - buf.append("\033[H") + buf.append(T.HOME) - logo_crlf = logo.replace("\n", "\033[K\r\n") - buf.append(f"{C_LOGO}{logo_crlf}{C_RST}\033[K\r\n") - buf.append(f"{C_SUB}THE HELM - Torrent automation MVP{C_RST}\033[K\r\n\033[K\r\n") + logo_crlf = logo.replace("\n", f"{T.EOL}\r\n") + buf.append(f"{T.LOGO}{logo_crlf}{T.RST}{T.EOL}\r\n") + buf.append(f"{T.ACCENT}THE HELM - Torrent automation MVP{T.RST}{T.EOL}\r\n{T.EOL}\r\n") - buf.append(f"\033[1m{C_TEXT}? {title_msg}:{C_RST}\033[K\r\n") - buf.append(f"{C_LINE}" + "━" * 80 + f"{C_RST}\033[K\r\n") + buf.append(f"{T.BOLD}{T.TEXT}? {title_msg}:{T.RST}{T.EOL}\r\n") + buf.append(T.LINE + "━" * 80 + f"{T.RST}{T.EOL}\r\n") for i, opt in enumerate(options): check_char = "x" if i in checked else " " - prefix = f"\033[7m\033[1m{C_LOGO} ❯ " if i == selected_index else f"\033[1m{C_SUB} " + prefix = f"{T.REVERSE}{T.BOLD}{T.LOGO} ❯ " if i == selected_index else f"{T.BOLD}{T.ACCENT} " # if selected index we want to invert the colors for the whole line, including the text - suffix = f"{C_RST}" - buf.append(f"{prefix}[{check_char}] {opt}{suffix}\033[K\r\n") + suffix = T.RST + buf.append(f"{prefix}[{check_char}] {opt}{suffix}{T.EOL}\r\n") - buf.append(f"{C_LINE}" + "━" * 80 + f"{C_RST}\033[K\r\n") + buf.append(T.LINE + "━" * 80 + f"{T.RST}{T.EOL}\r\n") buf.append( - f"\033[1m{C_TEXT}❯ (Arrows=Move, Space=Toggle, Enter=Confirm, Esc=Go Back, Ctrl-C=Exit){C_RST}\033[J" + f"{T.BOLD}{T.TEXT}❯ (Arrows=Move, Space=Toggle, Enter=Confirm, Esc=Go Back, Ctrl-C=Exit){T.RST}{T.CLEAR_DOWN}" ) sys.stdout.write("".join(buf)) diff --git a/tests/test_terminal_codes.py b/tests/test_terminal_codes.py new file mode 100644 index 0000000..5f643db --- /dev/null +++ b/tests/test_terminal_codes.py @@ -0,0 +1,163 @@ +import io +import json +import re +import sys +from pathlib import Path +from types import SimpleNamespace + +import pytest + +import helm.cli +from helm.core.settings import FIELDS +from helm.ui.ansi import CONTROLS, Terminal, sgr +from helm.ui.banner import LOGOS +from helm.ui.theme import PRESETS + +SRC = Path(__file__).resolve().parents[1] / "src" / "helm" +EMITTED = re.compile(r"\\033\[|\\x1b\[|\\u001b\[|\\e\[") + + +@pytest.fixture +def home(tmp_path, monkeypatch): + for key, name in (("HELM_CONFIG_DIR", "config"), ("HELM_STATE_DIR", "state"), ("HELM_DL_DIR", "downloads")): + monkeypatch.setenv(key, str(tmp_path / name)) + (tmp_path / "config").mkdir() + for key in {field.env for field in FIELDS if field.env} | {"NO_COLOR", "FORCE_COLOR"}: + monkeypatch.delenv(key, raising=False) + helm.cli.T.reset() + yield tmp_path + helm.cli.T.reset() + + +class Tty(io.StringIO): + def isatty(self): + return True + + +def test_no_escape_codes_are_written_outside_the_renderer(): + allowed = { + # Regular expressions that read escapes in command output; they write none. + ("ui/banner.py", "SGR = re.compile"), + ("ui/banner.py", "UNSAFE = re.compile"), + } + offenders = [] + for path in sorted(SRC.rglob("*.py")): + relative = path.relative_to(SRC).as_posix() + if relative == "ui/ansi.py": + continue + for number, line in enumerate(path.read_text(encoding="utf-8").splitlines(), 1): + if EMITTED.search(line) and not any(relative == name and marker in line for name, marker in allowed): + offenders.append(f"{relative}:{number}: {line.strip()}") + assert offenders == [] + + +def test_old_colour_module_is_gone(): + assert not (SRC / "ui" / "colors.py").exists() + + +def test_terminal_codes_follow_the_theme_on_a_terminal(home, monkeypatch): + (home / "config" / "config.toml").write_text('[theme]\npreset = "nord"\naccent = "#010203"\n') + monkeypatch.setattr(sys, "stdout", Tty()) + codes = Terminal() + assert codes.LOGO == sgr(PRESETS["nord"]["logo"]) + assert codes.ACCENT == "\033[38;2;1;2;3m" + assert codes.SUCCESS == sgr(PRESETS["nord"]["success"]) + assert codes.BOLD == "\033[1m" + assert codes.RST == "\033[0m" + assert codes.EOL == CONTROLS["EOL"] + + +def test_colours_are_off_when_piped_or_no_color(home, monkeypatch): + monkeypatch.setattr(sys, "stdout", io.StringIO()) + piped = Terminal() + assert piped.LOGO == piped.BOLD == piped.RST == "" + assert piped.HOME == "\033[H" and piped.CLEAR == "\033[2J" + monkeypatch.setattr(sys, "stdout", Tty()) + monkeypatch.setenv("NO_COLOR", "1") + assert Terminal().LOGO == "" + + +def test_helm_preset_keeps_basic_terminal_colours(home, monkeypatch): + monkeypatch.setenv("FORCE_COLOR", "1") + codes = Terminal() + assert (codes.SUCCESS, codes.WARNING, codes.INFO) == ("\033[32m", "\033[33m", "\033[36m") + assert codes.LOGO == "\033[38;2;74;105;189m" + + +def test_broken_config_falls_back_to_the_default_theme(home, monkeypatch): + (home / "config" / "config.toml").write_text("[theme\n") + monkeypatch.setenv("FORCE_COLOR", "1") + assert Terminal().LOGO == sgr(PRESETS["helm"]["logo"]) + + +def test_terminal_reset_and_unknown_names(home, monkeypatch): + monkeypatch.setenv("FORCE_COLOR", "1") + codes = Terminal() + assert codes.LOGO == sgr(PRESETS["helm"]["logo"]) + monkeypatch.setenv("HELM_THEME", "tokyo-night") + assert codes.LOGO == sgr(PRESETS["helm"]["logo"]) + codes.reset() + assert codes.LOGO == sgr(PRESETS["tokyo-night"]["logo"]) + with pytest.raises(AttributeError): + _ = codes.PURPLE + with pytest.raises(AttributeError): + _ = codes._private + + +def items(): + from test_cli import _make_items + + return _make_items() + + +@pytest.mark.parametrize("found", [True, False]) +def test_json_stdout_stays_pure_with_colours_forced(home, monkeypatch, capsys, found): + monkeypatch.setenv("FORCE_COLOR", "1") + monkeypatch.setenv("JACKETT_API_KEY", "testkey") + monkeypatch.setattr(helm.cli, "ensure_config", lambda: None) + monkeypatch.setattr( + helm.cli, + "animated_search", + lambda query, content_type, lite_mode=False, show_spinner=True: (items() if found else [], True), + ) + monkeypatch.setattr(sys, "argv", ["helm-torrent", "search", "--json", "--lite", "ubuntu"]) + with pytest.raises(SystemExit): + helm.cli.main() + out, _err = capsys.readouterr() + assert "\033" not in out + assert LOGOS["helm"][0] not in out + if found: + assert len(json.loads(out)) == 2 + else: + assert out.strip() in ("", "[]") + + +def args(**values): + defaults = {"lite": False, "oneshot": False, "json": False} + defaults.update(values) + return SimpleNamespace(**defaults) + + +def test_ui_header_shows_banner_when_enabled(home, capsys): + (home / "config" / "config.toml").write_text('[banner]\nmodules = ["mode"]\n') + helm.cli._print_header(args(lite=True), "THE HELM - Torrent automation MVP") + out = capsys.readouterr().out + assert LOGOS["helm"][0] in out + assert re.search(r"Mode\s+lite", out) + assert "THE HELM - Torrent automation MVP" in out + assert "\033" not in out + + +def test_ui_header_shows_plain_wordmark_when_disabled(home, capsys): + (home / "config" / "config.toml").write_text("[banner]\nenabled = false\n") + helm.cli._print_header(args(oneshot=True), "subtitle") + out = capsys.readouterr().out + assert LOGOS["helm"][0] in out + assert "Mode" not in out + assert out.rstrip().endswith("subtitle") + + +def test_banner_mode_context(home): + assert helm.cli._banner_context(args(lite=True)) == {"mode": "lite"} + assert helm.cli._banner_context(args(oneshot=True)) == {"mode": "one-shot"} + assert helm.cli._banner_context(args()) == {} diff --git a/tests/test_theme_banner.py b/tests/test_theme_banner.py index c175a6c..14b2318 100644 --- a/tests/test_theme_banner.py +++ b/tests/test_theme_banner.py @@ -11,7 +11,6 @@ import pytest from helm.core.settings import BY_PATH, COLOR_NAMES, FIELDS, HEX_COLOR, THEMES, Settings, check -from helm.ui import colors from helm.ui.ansi import color_enabled, render_banner, sgr, visible_width from helm.ui.banner import ( LOGOS, @@ -93,20 +92,40 @@ def log_message(self, *args): def test_presets_match_settings_and_define_every_colour(): assert tuple(PRESETS) == THEMES - for preset in PRESETS.values(): + for name, preset in PRESETS.items(): assert tuple(preset) == COLOR_NAMES - assert all(HEX_COLOR.match(value) for value in preset.values()) + for value in preset.values(): + assert HEX_COLOR.match(value) or (name == "helm" and re.match(r"^ansi:\d+$", value)) + + +# The exact codes and wordmark the UI printed before themes existed. +OLD_CODES = { + "logo": "\033[38;2;74;105;189m", + "accent": "\033[38;2;179;57;57m", + "text": "\033[38;2;234;218;201m", + "line": "\033[38;2;205;97;51m", + "error": "\033[38;2;255;82;82m", + "success": "\033[32m", + "warning": "\033[33m", + "info": "\033[36m", +} +OLD_WORDMARK = """ +▗▖ ▗▖▗▄▄▄▖▗▖ ▗▖ ▗▖ +▐▌ ▐▌▐▌ ▐▌ ▐▛▚▞▜▌ +▐▛▀▜▌▐▛▀▀▘▐▌ ▐▌ ▐▌ +▐▌ ▐▌▐▙▄▄▖▐▙▄▄▖▐▌ ▐▌ +""" def test_helm_preset_keeps_the_current_look(): + from helm.ui.banner import WORDMARK + theme = load_theme(make_settings()) assert theme.name == "helm" - assert sgr(theme.get("logo")) == colors.C_LOGO - assert sgr(theme.get("accent")) == colors.C_SUB - assert sgr(theme.get("text")) == colors.C_TEXT - assert sgr(theme.get("line")) == colors.C_LINE - assert sgr(theme.get("error")) == colors.C_ERR - assert LOGOS["helm"] == colors.logo.strip("\n").split("\n") + for name, code in OLD_CODES.items(): + assert sgr(theme.get(name)) == code, name + assert WORDMARK == OLD_WORDMARK + assert LOGOS["helm"] == OLD_WORDMARK.strip("\n").split("\n") def test_single_colour_override_keeps_the_rest_of_the_preset(): From cd5a4fe2b1ff173da4f3178c735e5d2ad24379c0 Mon Sep 17 00:00:00 2001 From: Piratebird <141295458+Piratebird@users.noreply.github.com> Date: Mon, 2 Nov 2026 23:40:04 +0200 Subject: [PATCH 06/18] :shipit: chore(setup): rebuild setup.sh from functions on one compose template - Split setup.sh into small functions with a short main and a source guard - Render one compose template, shared with helm-torrent init, and remove docker-compose.yml.example - Detect existing Jackett or Prowlarr before writing the compose and env files - Mount the config directory into the CLI container instead of an unread config.json - Use the published Helm image on Podman instead of a mini-helm image nothing built - Fix the gluetun port, QB_WEBUI with a VPN, the systemd ExecStart and the launcher's oneshot check - Write .env.docker with mode 0600 and INDEXER_MANAGER, and keep an existing qBittorrent.conf - Test the real script against fake Docker, Podman and systemctl, and both renderers against each other --- .gitignore | 2 +- CHANGELOG.md | 6 + README.md | 2 + docker-compose.yml.example | 115 -- pyproject.toml | 4 + setup.sh | 1635 +++++++++++++--------------- src/helm/core/compose.py | 67 ++ src/helm/core/compose.template.yml | 188 ++++ src/helm/core/init_env.py | 182 +--- tests/test_setup.sh | 4 - tests/test_setup_script.py | 465 ++++++++ 11 files changed, 1515 insertions(+), 1155 deletions(-) delete mode 100644 docker-compose.yml.example create mode 100644 src/helm/core/compose.py create mode 100644 src/helm/core/compose.template.yml delete mode 100644 tests/test_setup.sh create mode 100644 tests/test_setup_script.py diff --git a/.gitignore b/.gitignore index 63c0d90..85f137c 100644 --- a/.gitignore +++ b/.gitignore @@ -34,7 +34,7 @@ testing/ bugs_notes.txt # Docker / App Data -# docker-compose.yml is generated by setup.sh from docker-compose.yml.example +# docker-compose.yml is generated by setup.sh from src/helm/core/compose.template.yml docker-compose.yml docker_data/ config/ diff --git a/CHANGELOG.md b/CHANGELOG.md index 15d5f4b..707cf75 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ All notable changes to this project will be documented in this file. ## [Unreleased] ### Changed +- Rewrite `setup.sh` as small functions with a short `main`, tested against fake Docker, Podman and systemctl binaries. `setup.sh` and `helm-torrent init` now render one compose template, `src/helm/core/compose.template.yml`, and `docker-compose.yml.example` is removed. Setup no longer edits `config.json`; the indexer choice goes into `.env.docker` as `INDEXER_MANAGER`. The container name prefix is `helm` (or `COMPOSE_PROJECT_NAME`) everywhere, instead of the directory name in `.env.docker`. An existing `qBittorrent.conf` is kept instead of overwritten. - Use the theme everywhere the UI, wizard, one-shot mode and Lite downloader print colour, and show the banner when the UI starts. Colours are now off when output is piped or `NO_COLOR` is set. Red messages that used the terminal's basic red now use the theme's error colour. - Use one set of service defaults: Jackett `19117`, Prowlarr `19696`, qBittorrent `18080`. Set `[services]` for a native Jackett on `9117`. - Report invalid config files clearly instead of resetting them. Runtime choices are stored in `settings.json` in the state directory, below the user's file. @@ -28,6 +29,11 @@ All notable changes to this project will be documented in this file. - Standalone `uninstall.sh` for raw GitHub execution, with preview-by-default, selective removal and unit tests. ### Fixed +- Setup: detect an existing Jackett or Prowlarr container before writing the compose and env files, so the detected one is used instead of a second copy. +- Setup: mount the config directory into the CLI container and set `HELM_CONFIG_DIR`; the old `/app/config.json` mount was never read. +- Setup: use the published `ghcr.io/piratebird/helm` image on Podman instead of a `mini-helm` image nothing built. +- Setup: with a VPN, map gluetun `18080:18080` (qBittorrent listens on 18080) and point `QB_WEBUI` at `gluetun`. +- Setup: fix the systemd unit's empty `ExecStart`, the launcher adding `--oneshot` when any argument contained `-o`, the summary ignoring `--*-dir`, and `sed -i` failing on macOS. `.env.docker` is now written with mode `0600`. - Log in to qBittorrent again after a session expires, and follow URL or credential changes in long-running services. - Remove a cancelled job's torrent from qBittorrent, and map container paths to host paths when cataloging its files. - Allow failed or cancelled sources to be resubmitted, and keep the queue worker alive after unexpected errors. diff --git a/README.md b/README.md index 455c8ba..61b1dbd 100644 --- a/README.md +++ b/README.md @@ -127,6 +127,8 @@ The script will guide you through: 2. Choosing your run mode (Ephemeral vs Permanent) 3. Setting up a VPN (optional) +It writes `docker-compose.yml` in the current directory from `src/helm/core/compose.template.yml`, the same template `helm-torrent init` uses. From a checkout the local template is used; the curl one-liner downloads it from the same branch (set `HELM_REF` to pick another). It also writes `state/.env.docker` with mode `0600`, including `INDEXER_MANAGER` for the containers, and mounts your config directory into the CLI container, so `config.toml` and `config.jsonc` work there too. Set `COMPOSE_PROJECT_NAME` before running it to change the container name prefix (default `helm`). +
## Why this exists diff --git a/docker-compose.yml.example b/docker-compose.yml.example deleted file mode 100644 index 13cfcf1..0000000 --- a/docker-compose.yml.example +++ /dev/null @@ -1,115 +0,0 @@ -# Template docker-compose.yml. -# -# This is NOT used directly by docker/podman compose: `./setup.sh` copies it, -# substitutes your real HELM_CONFIG / HELM_STATE / HELM_DL paths, and writes the -# result to `./docker-compose.yml`. The generated file is gitignored. -# -# If you want a VPN (gluetun) or Podman, run `./setup.sh` again and pick the -# appropriate options rather than editing the generated file. -# -# The ${HELM_*} variables below are interpolated by `docker compose` itself when -# those variables are exported, so this template is also directly usable. - -services: - jackett: - container_name: "${COMPOSE_PROJECT_NAME:-helm}-jackett" - image: lscr.io/linuxserver/jackett:latest - deploy: - resources: - limits: - cpus: "0.50" - memory: 256M - labels: - - "com.docker.compose.project=${COMPOSE_PROJECT_NAME:-helm}" - - "com.docker.compose.service=jackett" - - "com.docker.compose.oneoff=False" - dns: - - 8.8.8.8 - - 1.1.1.1 - environment: - - PUID=1000 - - PGID=1000 - - TZ=Etc/UTC - security_opt: - - label=disable - volumes: - - ${HELM_STATE}/jackett:/config - - ${HELM_DL}:/downloads - ports: - - 19117:9117 - restart: unless-stopped - - flaresolverr: - container_name: "${COMPOSE_PROJECT_NAME:-helm}-flaresolverr" - image: ghcr.io/flaresolverr/flaresolverr:latest - deploy: - resources: - limits: - cpus: "0.50" - memory: 512M - labels: - - "com.docker.compose.project=${COMPOSE_PROJECT_NAME:-helm}" - - "com.docker.compose.service=flaresolverr" - - "com.docker.compose.oneoff=False" - dns: - - 8.8.8.8 - - 1.1.1.1 - environment: - - LOG_LEVEL=info - - TZ=Etc/UTC - security_opt: - - label=disable - ports: - - 18191:8191 - restart: unless-stopped - - cli: - container_name: "${COMPOSE_PROJECT_NAME:-helm}-cli" - image: ghcr.io/piratebird/helm:latest - dns: - - 8.8.8.8 - - 1.1.1.1 - stdin_open: true - tty: true - env_file: - - ${HELM_STATE}/.env.docker - security_opt: - - label=disable - volumes: - - ${HELM_CONFIG}/config.json:/app/config.json - - ${HOST_PWD:-.}/src:/app/src - - ${HOST_PWD:-.}/docker-compose.yml:/app/docker-compose.yml - - /var/run/docker.sock:/var/run/docker.sock - profiles: - - cli - - qbittorrent: - container_name: "${COMPOSE_PROJECT_NAME:-helm}-qbittorrent" - image: lscr.io/linuxserver/qbittorrent:latest - deploy: - resources: - limits: - cpus: "0.50" - memory: 256M - labels: - - "com.docker.compose.project=${COMPOSE_PROJECT_NAME:-helm}" - - "com.docker.compose.service=qbittorrent" - - "com.docker.compose.oneoff=False" - dns: - - 8.8.8.8 - - 1.1.1.1 - environment: - - PUID=1000 - - PGID=1000 - - TZ=Etc/UTC - - WEBUI_PORT=18080 - security_opt: - - label=disable - volumes: - - ${HELM_STATE}/qbittorrent:/config - - ${HELM_DL}:/downloads - ports: - - 18080:18080 - - 6881:6881 - - 6881:6881/udp - restart: unless-stopped \ No newline at end of file diff --git a/pyproject.toml b/pyproject.toml index 262ac2c..a6c707e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -28,6 +28,7 @@ download = ["libtorrent>=2.0.0,<2.1.0"] dev = [ "pytest", "pytest-cov", + "pyyaml", "responses", "types-requests" ] @@ -41,6 +42,9 @@ helm-torrent = "helm.cli:main" [tool.setuptools.packages.find] where = ["src"] +[tool.setuptools.package-data] +"helm.core" = ["compose.template.yml"] + [tool.pytest.ini_options] pythonpath = ["src"] diff --git a/setup.sh b/setup.sh index 3fd40ca..b61347d 100755 --- a/setup.sh +++ b/setup.sh @@ -1,309 +1,384 @@ #!/usr/bin/env bash +# +# Helm setup: installs the services Helm uses (Jackett and/or Prowlarr, +# qBittorrent, FlareSolverr) with Docker, Podman, or natively. +# +# ./setup.sh [--skip-prompts] [--config-dir DIR] [--state-dir DIR] [--downloads-dir DIR] +# bash <(curl -sL https://raw.githubusercontent.com/Piratebird/helm/main/setup.sh) +# +# The compose file comes from src/helm/core/compose.template.yml, the same +# template `helm-torrent init` uses. From a checkout the local copy is used; +# otherwise it is downloaded from the same branch. + +set -eo pipefail + +HELM_IMAGE="ghcr.io/piratebird/helm:latest" +HELM_RAW_BASE="${HELM_RAW_BASE:-https://raw.githubusercontent.com/Piratebird/helm/${HELM_REF:-main}}" +TEMPLATE_PATH_IN_REPO="src/helm/core/compose.template.yml" +SETUP_TIMEOUT="${HELM_SETUP_TIMEOUT:-45}" +SETUP_POLL="${HELM_SETUP_POLL:-5}" +KEY_TRIES="${HELM_SETUP_KEY_TRIES:-15}" +KEY_POLL="${HELM_SETUP_KEY_POLL:-3}" + +# Answers, set by ask() through printf -v. +install_mode="" indexer_mode="" run_mode="" qb_user="" use_vpn="" +vpn_provider="" vpn_type="" vpn_extra="" + +# ---------------------------------------------------------------- output + +setup_colours() { + C_RED="" C_GREEN="" C_YELLOW="" C_CYAN="" C_BOLD="" C_RST="" + if [ -t 1 ] && [ -z "${NO_COLOR:-}" ]; then + C_RED=$'\033[31m' C_GREEN=$'\033[32m' C_YELLOW=$'\033[33m' + C_CYAN=$'\033[36m' C_BOLD=$'\033[1m' C_RST=$'\033[0m' + fi +} -# Exit immediately if a command exits with a non-zero status -set -e -# Catch errors in piped commands (e.g., command1 | command2) -set -o pipefail - -OS="$(uname -s)" -case "${OS}" in - Darwin*) - DEFAULT_CONFIG="$HOME/Library/Application Support/helm" - DEFAULT_STATE="$HOME/Library/Application Support/helm/state" - ;; - MINGW*|CYGWIN*|MSYS*) - DEFAULT_CONFIG="${APPDATA:-$HOME/AppData/Roaming}/helm" - DEFAULT_STATE="${LOCALAPPDATA:-$HOME/AppData/Local}/helm" - ;; - *) - DEFAULT_CONFIG="$HOME/.config/helm" - DEFAULT_STATE="$HOME/.local/state/helm" - ;; -esac - -HELM_CONFIG="${DEFAULT_CONFIG}" -HELM_STATE="${DEFAULT_STATE}" -HELM_DL="$HOME/Downloads/helm" - -while [[ $# -gt 0 ]]; do - case $1 in - --config-dir) - HELM_CONFIG="$2" - shift 2 - ;; - --state-dir) - HELM_STATE="$2" - shift 2 - ;; - --downloads-dir) - HELM_DL="$2" - shift 2 - ;; - --skip-prompts) - SKIP_PROMPTS=1 - shift - ;; - --help) - echo "Usage: ./setup.sh [OPTIONS]" - echo "Options:" - echo " --config-dir Set configuration directory (default: OS native config path)" - echo " --state-dir Set state directory (default: OS native state path)" - echo " --downloads-dir Set downloads directory (default: ~/Downloads/helm)" - echo " --skip-prompts Run silently with default values" - exit 0 - ;; - *) - echo "Unknown option: $1" - exit 1 - ;; - esac -done +say() { printf '%s\n' "$*"; } +info() { printf '%s[INFO]%s %s\n' "$C_CYAN" "$C_RST" "$*"; } +ok() { printf '%s[OK]%s %s\n' "$C_GREEN" "$C_RST" "$*"; } +warn() { printf '%s[WARN]%s %s\n' "$C_YELLOW" "$C_RST" "$*" >&2; } +error() { printf '%s[ERROR]%s %s\n' "$C_RED" "$C_RST" "$*" >&2; } +die() { error "$@"; exit 1; } +rule() { say "==========================================="; } + +# ask VAR PROMPT DEFAULT [DEFAULT_WITH_SKIP_PROMPTS] +ask() { + local __var=$1 __prompt=$2 __default=$3 __reply="" + if [ -n "$SKIP_PROMPTS" ]; then + __reply="${4-$__default}" + else + read -r -p "$__prompt" __reply || true + __reply="${__reply:-$__default}" + fi + printf -v "$__var" '%s' "$__reply" +} -echo "Using paths:" -echo " Config: $HELM_CONFIG" -echo " State: $HELM_STATE" -echo " Downloads: $HELM_DL" -echo "" - -echo "===========================================" -echo " Helm Application Setup Script " -echo "===========================================" -echo "" - -if [ -n "$SKIP_PROMPTS" ]; then - install_mode=1 -else - echo "How would you like to install the required services (Jackett/Prowlarr & qBittorrent)?" - echo " [1] Docker (Recommended) - Uses standard docker-compose, isolates dependencies." - echo " [2] Podman - Daemonless, rootless containers for lower memory overhead." - echo " [3] Native - Installs directly to your OS (/opt/Jackett & /usr/bin/qbittorrent). Highest performance but clutters OS." - read -r -p "Choose your installation method (1/2/3, default 1): " install_mode - install_mode=${install_mode:-1} - echo "" -fi +ask_secret() { + local __var=$1 __prompt=$2 __reply="" + if [ -z "$SKIP_PROMPTS" ]; then + read -r -s -p "$__prompt" __reply || true + say "" + fi + printf -v "$__var" '%s' "$__reply" +} -if [ -n "$SKIP_PROMPTS" ]; then - indexer_mode=3 -else - echo "Which indexer manager would you like to use?" - echo " [1] Jackett (Default) - Stable, battle-tested." - echo " [2] Prowlarr (BETA) - Modern UI, becoming the standard." - echo " [3] Both - Run both Jackett and Prowlarr simultaneously." - read -r -p "Choose your indexer manager (1/2/3, default 1): " indexer_mode - indexer_mode=${indexer_mode:-1} - echo "" -fi +is_yes() { [[ "$1" =~ ^[Yy]$ ]]; } + +# ---------------------------------------------------------------- arguments + +default_paths() { + case "$(uname -s)" in + Darwin*) + HELM_CONFIG="$HOME/Library/Application Support/helm" + HELM_STATE="$HOME/Library/Application Support/helm/state" + ;; + MINGW*|CYGWIN*|MSYS*) + HELM_CONFIG="${APPDATA:-$HOME/AppData/Roaming}/helm" + HELM_STATE="${LOCALAPPDATA:-$HOME/AppData/Local}/helm" + ;; + *) + HELM_CONFIG="$HOME/.config/helm" + HELM_STATE="$HOME/.local/state/helm" + ;; + esac + HELM_DL="$HOME/Downloads/helm" +} +usage() { + cat <<'EOF' +Usage: ./setup.sh [OPTIONS] +Options: + --config-dir Set configuration directory (default: OS native config path) + --state-dir Set state directory (default: OS native state path) + --downloads-dir Set downloads directory (default: ~/Downloads/helm) + --skip-prompts Run silently with default values +EOF +} -check_docker() { - if ! command -v docker &> /dev/null; then - echo "[-] Error: Docker is not installed or not in your PATH." - echo "" - if [ "$(uname)" == "Darwin" ]; then - echo "To install Docker on macOS, run:" - echo " brew install --cask docker" - elif [ -f /etc/os-release ]; then - # shellcheck disable=SC1091 - . /etc/os-release - case "$ID" in - ubuntu|debian|pop|linuxmint) - echo "To install Docker on $NAME, run:" - echo " sudo apt update && sudo apt install -y docker.io docker-compose" - ;; - fedora|centos|rhel|almalinux|rocky) - echo "To install Docker on $NAME, run:" - echo " sudo dnf install -y docker docker-compose" - ;; - arch|manjaro) - echo "To install Docker on $NAME, run:" - echo " sudo pacman -S docker docker-compose" - ;; - *) - echo "Please install Docker manually for your OS ($NAME)." +parse_args() { + SKIP_PROMPTS="" + while [[ $# -gt 0 ]]; do + case $1 in + --config-dir|--state-dir|--downloads-dir) + [[ $# -ge 2 ]] || die "$1 needs a path" + case $1 in + --config-dir) HELM_CONFIG="$2" ;; + --state-dir) HELM_STATE="$2" ;; + --downloads-dir) HELM_DL="$2" ;; + esac + shift 2 ;; - esac + --skip-prompts) SKIP_PROMPTS=1; shift ;; + --help|-h) usage; exit 0 ;; + *) usage >&2; die "Unknown option: $1" ;; + esac + done + local name value + for name in HELM_CONFIG HELM_STATE HELM_DL; do + value="${!name}" + if [[ "$value" == *'"'* || "$value" == *$'\n'* ]]; then + die "$name cannot contain quotes or line breaks: $value" fi - echo "" - echo "--- Unix Shenanigans Reminder ---" - echo "1. Start the Docker daemon: sudo systemctl enable --now docker" - echo "2. Add user to docker group: sudo usermod -aG docker \$USER" - echo "3. Apply group changes: newgrp docker (or just log out and log back in)" - echo "" - exit 1 + done +} + +# ---------------------------------------------------------------- choices + +choose_install() { + if [ -z "$SKIP_PROMPTS" ]; then + say "How would you like to install the required services (Jackett/Prowlarr & qBittorrent)?" + say " [1] Docker (Recommended) - Uses standard docker-compose, isolates dependencies." + say " [2] Podman - Daemonless, rootless containers for lower memory overhead." + say " [3] Native - Installs directly to your OS (/opt/Jackett & /usr/bin/qbittorrent). Highest performance but clutters OS." fi - - # Ensure docker compose is available - if ! docker compose version &> /dev/null; then - echo "[-] Error: 'docker compose' is not available." - echo "Please ensure you have the docker-compose-plugin installed." - exit 1 + ask install_mode "Choose your installation method (1/2/3, default 1): " 1 + [ -n "$SKIP_PROMPTS" ] || say "" + + if [ -z "$SKIP_PROMPTS" ]; then + say "Which indexer manager would you like to use?" + say " [1] Jackett (Default) - Stable, battle-tested." + say " [2] Prowlarr (BETA) - Modern UI, becoming the standard." + say " [3] Both - Run both Jackett and Prowlarr simultaneously." fi - - if ! docker info > /dev/null 2>&1; then - echo "[ERROR] Cannot connect to the Docker daemon." - echo "Resolution: Ensure the Docker service is running and your user is in the 'docker' group." - exit 1 + ask indexer_mode "Choose your indexer manager (1/2/3, default 1): " 1 3 + [ -n "$SKIP_PROMPTS" ] || say "" + + case "$indexer_mode" in + 2) INDEXER_MANAGER="prowlarr" ;; + 3) INDEXER_MANAGER="both" ;; + *) indexer_mode=1; INDEXER_MANAGER="jackett" ;; + esac +} + +wants_jackett() { [ "$indexer_mode" == "1" ] || [ "$indexer_mode" == "3" ]; } +wants_prowlarr() { [ "$indexer_mode" == "2" ] || [ "$indexer_mode" == "3" ]; } +local_jackett() { wants_jackett && [ -z "$EXTERNAL_JACKETT_API" ]; } +local_prowlarr() { wants_prowlarr && [ -z "$EXTERNAL_PROWLARR_API" ]; } + +choose_stack() { + if [ -z "$SKIP_PROMPTS" ]; then + say "How would you like to run Helm?" + say " [1] Permanent (Always-On) - Containers run 24/7 in the background." + say " [2] Ephemeral (One-Shot) - Containers spin up only when downloading, then tear down." + fi + ask run_mode "Choose your mode (1/2, default 2): " 2 + [ -n "$SKIP_PROMPTS" ] || say "" + + JACKETT_API="" PROWLARR_API="" + if wants_jackett && [ -z "$EXTERNAL_JACKETT_API" ]; then + ask JACKETT_API "Enter Jackett API Key (press Enter to auto-extract later): " "" + fi + if wants_prowlarr && [ -z "$EXTERNAL_PROWLARR_API" ]; then + ask PROWLARR_API "Enter Prowlarr API Key (press Enter to auto-extract later): " "" + fi + ask qb_user "Enter qBittorrent Username (default: admin): " admin + [ -n "$SKIP_PROMPTS" ] || say "" + ask use_vpn "Do you want to route qBittorrent through a VPN using Gluetun? (y/N): " n + if is_yes "$use_vpn"; then + choose_vpn fi - - DOCKER_CMD="docker" - COMPOSE_CMD="docker compose" } -check_podman() { - if ! command -v podman &> /dev/null; then - echo "[-] Podman is not installed." - if [ -n "$SKIP_PROMPTS" ]; then - auto_install="Y" +choose_vpn() { + vpn_provider="" vpn_type="" vpn_extra="" + say "" + say "--- VPN Configuration ---" + ask vpn_provider "Enter VPN Provider (e.g. nordvpn, custom): " "" + if [ "$vpn_provider" = "protonvpn" ]; then + warn "ProtonVPN blocks P2P/torrent traffic on its Free tier, so qBittorrent would stay stalled." + warn "Make sure you are using a paid ProtonVPN account." + fi + ask vpn_type "Enter VPN Type (wireguard/openvpn) (default: wireguard): " wireguard + + if [ -z "$vpn_provider" ]; then + error "VPN Provider cannot be empty. Disabling VPN." + use_vpn="n" + elif [ "$vpn_type" = "wireguard" ]; then + local wg_key + ask wg_key "Enter WireGuard Private Key: " "" + if [ -z "$wg_key" ]; then + error "WireGuard key cannot be empty. Disabling VPN." + use_vpn="n" else - read -r -p "Would you like this script to install Podman automatically? [Y/n]: " auto_install - auto_install=${auto_install:-Y} - fi - - if [[ ! "$auto_install" =~ ^[Yy]$ ]]; then - echo "Please install Podman manually and re-run the script." - exit 1 + vpn_extra="WIREGUARD_PRIVATE_KEY=$wg_key" fi - - echo "Installing Podman..." - if [ "$(uname)" == "Darwin" ]; then - if command -v brew &> /dev/null; then - brew install podman podman-desktop podman-compose + elif [ "$vpn_type" = "openvpn" ]; then + if [ "$vpn_provider" != "custom" ]; then + local ovpn_user ovpn_pass + ask ovpn_user "Enter OpenVPN Username (or token): " "" + ask_secret ovpn_pass "Enter OpenVPN Password (leave blank if using token): " + if [ -z "$ovpn_user" ]; then + error "OpenVPN user cannot be empty. Disabling VPN." + use_vpn="n" else - echo "Please install Homebrew (https://brew.sh/) first, then re-run this script." - exit 1 + vpn_extra="OPENVPN_USER=$ovpn_user"$'\n'"OPENVPN_PASSWORD=$ovpn_pass" fi - elif [ -f /etc/os-release ]; then - # shellcheck disable=SC1091 - . /etc/os-release - case "$ID" in - ubuntu|debian|pop|linuxmint) - sudo apt update && sudo apt install -y podman podman-compose - ;; - fedora|centos|rhel|almalinux|rocky) - sudo dnf install -y podman podman-compose - ;; - arch|manjaro) - sudo pacman -S --noconfirm podman podman-compose - ;; - *) - echo "Automatic installation is not supported for your OS ($NAME)." - echo "Please install Podman manually from https://podman.io/docs/installation" - exit 1 - ;; - esac else - echo "Cannot determine OS. Please install Podman manually." - exit 1 - fi - - if ! command -v podman &> /dev/null; then - echo "[-] Error: Automatic installation failed. Please install Podman manually." - exit 1 + info "For 'custom' OpenVPN, place custom.conf (and auth.conf if needed) in $HELM_STATE/gluetun" fi fi - - # Check if podman compose is available - if podman compose version &> /dev/null; then - COMPOSE_CMD="podman compose" - elif command -v podman-compose &> /dev/null; then - COMPOSE_CMD="podman-compose" - else - echo "[-] Error: Neither 'podman-compose' nor 'podman compose' is available." - echo "Please install podman-compose (e.g., sudo apt install podman-compose)." +} + +# ---------------------------------------------------------------- engines + +# NAME and ID come from /etc/os-release. +# shellcheck disable=SC2153 +print_docker_install_help() { + if [ "$(uname)" == "Darwin" ]; then + say "To install Docker on macOS, run:" + say " brew install --cask docker" + elif [ -f /etc/os-release ]; then + # shellcheck disable=SC1091 + . /etc/os-release + case "$ID" in + ubuntu|debian|pop|linuxmint) + say "To install Docker on $NAME, run:" + say " sudo apt update && sudo apt install -y docker.io docker-compose" ;; + fedora|centos|rhel|almalinux|rocky) + say "To install Docker on $NAME, run:" + say " sudo dnf install -y docker docker-compose" ;; + arch|manjaro) + say "To install Docker on $NAME, run:" + say " sudo pacman -S docker docker-compose" ;; + *) + say "Please install Docker manually for your OS ($NAME)." ;; + esac + fi + say "" + say "--- Unix Shenanigans Reminder ---" + say "1. Start the Docker daemon: sudo systemctl enable --now docker" + say "2. Add user to docker group: sudo usermod -aG docker \$USER" + say "3. Apply group changes: newgrp docker (or just log out and log back in)" + say "" +} + +check_docker() { + if ! command -v docker &> /dev/null; then + error "Docker is not installed or not in your PATH." + say "" + print_docker_install_help exit 1 fi - - DOCKER_CMD="podman" + docker compose version &> /dev/null \ + || die "'docker compose' is not available. Please install the docker-compose-plugin." + docker info > /dev/null 2>&1 \ + || die "Cannot connect to the Docker daemon. Make sure it is running and your user is in the 'docker' group." + ENGINE="docker" + COMPOSE_CMD=(docker compose) + ENGINE_SOCKET="/var/run/docker.sock" } -install_native() { - echo "--- Native Installation ---" - - if [ "$indexer_mode" == "2" ] || [ "$indexer_mode" == "3" ]; then - echo -e " -[WARNING] Prowlarr integration is currently in BETA." - echo -e "Installing Prowlarr natively involves complex .NET dependencies that might clutter your system." - echo -e "It is HIGHLY RECOMMENDED to use Docker (Option 1) or Podman (Option 2) for Prowlarr instead. -" - read -r -p "Are you sure you want to continue with Native Installation? [y/N]: " confirm_native - confirm_native=${confirm_native:-N} - if [[ ! "$confirm_native" =~ ^[Yy]$ ]]; then - echo "Aborting native installation. Please run the script again and select Docker." - exit 1 - fi +# shellcheck disable=SC2153 +install_podman() { + say "Installing Podman..." + if [ "$(uname)" == "Darwin" ]; then + command -v brew &> /dev/null || die "Please install Homebrew (https://brew.sh/) first, then re-run this script." + brew install podman podman-desktop podman-compose + elif [ -f /etc/os-release ]; then + # shellcheck disable=SC1091 + . /etc/os-release + case "$ID" in + ubuntu|debian|pop|linuxmint) sudo apt update && sudo apt install -y podman podman-compose ;; + fedora|centos|rhel|almalinux|rocky) sudo dnf install -y podman podman-compose ;; + arch|manjaro) sudo pacman -S --noconfirm podman podman-compose ;; + *) die "Automatic installation is not supported for your OS ($NAME). See https://podman.io/docs/installation" ;; + esac + else + die "Cannot determine OS. Please install Podman manually." + fi + command -v podman &> /dev/null || die "Automatic installation failed. Please install Podman manually." +} + +check_podman() { + if ! command -v podman &> /dev/null; then + warn "Podman is not installed." + local auto_install + ask auto_install "Would you like this script to install Podman automatically? [Y/n]: " Y + is_yes "$auto_install" || die "Please install Podman manually and re-run the script." + install_podman + fi + if podman compose version &> /dev/null; then + COMPOSE_CMD=(podman compose) + elif command -v podman-compose &> /dev/null; then + COMPOSE_CMD=(podman-compose) + else + die "Neither 'podman-compose' nor 'podman compose' is available. Please install podman-compose." fi + ENGINE="podman" + info "Enabling the Podman rootless socket for container orchestration..." + systemctl --user enable --now podman.socket 2>/dev/null || true + ENGINE_SOCKET=$(podman info --format '{{.Host.RemoteSocket.Path}}' 2>/dev/null || true) + ENGINE_SOCKET="${ENGINE_SOCKET:-/run/user/$(id -u)/podman/podman.sock}" +} + +# ---------------------------------------------------------------- native + +native_confirm() { if [ "$(uname)" == "Darwin" ]; then - echo -e "\n\033[31m[ERROR] Native mode on macOS is blocked.\033[0m" - echo "i aint messing with yall system" - echo "Please re-run the script and select Docker (Option 1) or Podman (Option 2)." - exit 1 + error "Native mode on macOS is blocked." + say "i aint messing with yall system" + die "Please re-run the script and select Docker (Option 1) or Podman (Option 2)." fi - - needs_install=0 - if ! command -v qbittorrent-nox &> /dev/null || ! command -v wget &> /dev/null || ! command -v tar &> /dev/null; then - needs_install=1 + if wants_prowlarr; then + say "" + warn "Prowlarr integration is currently in BETA." + say "Installing Prowlarr natively involves complex .NET dependencies that might clutter your system." + say "It is ${C_BOLD}HIGHLY RECOMMENDED${C_RST} to use Docker (Option 1) or Podman (Option 2) for Prowlarr instead." + say "" + local confirm_native + ask confirm_native "Are you sure you want to continue with Native Installation? [y/N]: " N + is_yes "$confirm_native" || die "Aborting native installation. Please run the script again and select Docker." fi - - if [ "$needs_install" -eq 1 ]; then - echo "[-] Some native dependencies (qbittorrent-nox, wget, libicu, etc.) are missing." - if [ -n "$SKIP_PROMPTS" ]; then - auto_install="Y" - else - read -r -p "Would you like this script to install them automatically? [Y/n]: " auto_install - auto_install=${auto_install:-Y} - fi - - if [[ ! "$auto_install" =~ ^[Yy]$ ]]; then - echo "Please install them manually and re-run the script." - exit 1 - fi - - echo "Installing native dependencies..." - if [ -f /etc/os-release ]; then - # shellcheck disable=SC1091 - . /etc/os-release - if [[ "$ID" == "ubuntu" || "$ID" == "debian" || "$ID" == "pop" || "$ID" == "linuxmint" ]]; then - sudo apt update && sudo apt install -y qbittorrent-nox wget tar curl libicu-dev libssl-dev zlib1g - elif [[ "$ID" == "fedora" || "$ID" == "centos" || "$ID" == "rhel" || "$ID" == "almalinux" || "$ID" == "rocky" ]]; then - sudo dnf install -y qbittorrent-nox wget tar curl icu openssl zlib - elif [[ "$ID" == "arch" || "$ID" == "manjaro" ]]; then - sudo pacman -S --noconfirm qbittorrent-nox wget tar curl icu openssl zlib - else - echo "Please ensure you have qbittorrent-nox and .NET dependencies (ICU, OpenSSL, zlib) installed manually." - fi - fi +} + +native_dependencies() { + if command -v qbittorrent-nox &> /dev/null && command -v wget &> /dev/null && command -v tar &> /dev/null; then + return 0 fi - - if ! command -v qbittorrent-nox &> /dev/null; then - echo "[-] Error: qbittorrent-nox failed to install or is not in PATH." - else - echo "[OK] qBittorrent-nox is installed." - fi - - if [ "$indexer_mode" == "1" ] || [ "$indexer_mode" == "3" ]; then - if [ ! -d "/opt/Jackett" ]; then - echo "Installing Jackett to /opt/Jackett..." - cd /opt - wget -O - -o /dev/null https://github.com/Jackett/Jackett/releases/latest/download/Jackett.Binaries.LinuxAMDx64.tar.gz | sudo tar -xz - sudo chown "$(whoami)":"$(id -g)" -R "/opt/Jackett" - cd Jackett - sudo ./install_service_systemd.sh - cd - - else - echo "Jackett already installed at /opt/Jackett" - fi - fi - - - if [ "$indexer_mode" == "2" ] || [ "$indexer_mode" == "3" ]; then - if [ ! -d "/opt/Prowlarr" ]; then - echo "Installing Prowlarr to /opt/Prowlarr..." - cd /opt - wget -O - -o /dev/null https://github.com/Prowlarr/Prowlarr/releases/latest/download/Prowlarr.master.linux-core-x64.tar.gz | sudo tar -xz - sudo chown "$(whoami)":"$(id -g)" -R "/opt/Prowlarr" - - # Create a simple systemd service for Prowlarr - cat << SVC | sudo tee /etc/systemd/system/prowlarr.service > /dev/null + warn "Some native dependencies (qbittorrent-nox, wget, libicu, etc.) are missing." + local auto_install + ask auto_install "Would you like this script to install them automatically? [Y/n]: " Y + is_yes "$auto_install" || die "Please install them manually and re-run the script." + + say "Installing native dependencies..." + [ -f /etc/os-release ] || return 0 + # shellcheck disable=SC1091 + . /etc/os-release + case "$ID" in + ubuntu|debian|pop|linuxmint) + sudo apt update && sudo apt install -y qbittorrent-nox wget tar curl libicu-dev libssl-dev zlib1g ;; + fedora|centos|rhel|almalinux|rocky) + sudo dnf install -y qbittorrent-nox wget tar curl icu openssl zlib ;; + arch|manjaro) + sudo pacman -S --noconfirm qbittorrent-nox wget tar curl icu openssl zlib ;; + *) + say "Please ensure you have qbittorrent-nox and .NET dependencies (ICU, OpenSSL, zlib) installed manually." ;; + esac +} + +native_jackett() { + if [ -d "/opt/Jackett" ]; then + say "Jackett already installed at /opt/Jackett" + return 0 + fi + say "Installing Jackett to /opt/Jackett..." + wget -O - -o /dev/null https://github.com/Jackett/Jackett/releases/latest/download/Jackett.Binaries.LinuxAMDx64.tar.gz \ + | sudo tar -xz -C /opt + sudo chown "$(whoami)":"$(id -g)" -R "/opt/Jackett" + (cd /opt/Jackett && sudo ./install_service_systemd.sh) +} + +native_prowlarr() { + if [ -d "/opt/Prowlarr" ]; then + say "Prowlarr already installed at /opt/Prowlarr" + return 0 + fi + say "Installing Prowlarr to /opt/Prowlarr..." + wget -O - -o /dev/null https://github.com/Prowlarr/Prowlarr/releases/latest/download/Prowlarr.master.linux-core-x64.tar.gz \ + | sudo tar -xz -C /opt + sudo chown "$(whoami)":"$(id -g)" -R "/opt/Prowlarr" + sudo tee /etc/systemd/system/prowlarr.service > /dev/null < /dev/null; then + ok "qBittorrent-nox is installed." + else + error "qbittorrent-nox failed to install or is not in PATH." + fi + if wants_jackett; then native_jackett; fi + if wants_prowlarr; then native_prowlarr; fi + say "Native installation completed! Ensure services are running using systemctl." +} -mkdir -p "$HELM_STATE/jackett" "$HELM_STATE/prowlarr" "$HELM_STATE/qbittorrent" "$HELM_STATE/gluetun" "$HELM_DL" -mkdir -p "$HELM_CONFIG" -touch "$HELM_CONFIG/config.json" +# ---------------------------------------------------------------- existing indexers -# Record the chosen indexer manager so the CLI knows which backend to query. -if [ "$indexer_mode" == "2" ]; then - INDEXER_MANAGER="prowlarr" -elif [ "$indexer_mode" == "3" ]; then - INDEXER_MANAGER="both" -else - INDEXER_MANAGER="jackett" -fi -python3 - "$HELM_CONFIG/config.json" "$INDEXER_MANAGER" <<'PY' || true -import json -import sys - -path, manager = sys.argv[1], sys.argv[2] -try: - with open(path) as f: - data = json.load(f) -except (OSError, json.JSONDecodeError): - data = {} -data["INDEXER_MANAGER"] = manager -with open(path, "w") as f: - json.dump(data, f, indent=4) -PY -if [ -f "$HELM_CONFIG/config.toml" ] || [ -f "$HELM_CONFIG/config.jsonc" ]; then - echo "[WARN] Your config file takes priority. Set search.indexer_manager = \"$INDEXER_MANAGER\" there if needed." -fi +# Print the API key found in a Jackett ServerConfig.json or Prowlarr config.xml on stdin. +parse_api_key() { + if [ "$1" == "prowlarr" ]; then + sed -n 's:.*\([^<]*\).*:\1:p' | head -n 1 + else + sed -n 's/.*"APIKey"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' | head -n 1 + fi +} -echo "" -if [ -n "$SKIP_PROMPTS" ]; then - run_mode=2 -else - echo "How would you like to run Helm?" - echo " [1] Permanent (Always-On) - Containers run 24/7 in the background." - echo " [2] Ephemeral (One-Shot) - Containers spin up only when downloading, then tear down." - read -r -p "Choose your mode (1/2, default 2): " run_mode - run_mode=${run_mode:-2} - echo "" -fi +read_api_key() { + local name=$1 container=$2 file="/config/Jackett/ServerConfig.json" + if [ "$name" == "prowlarr" ]; then file="/config/config.xml"; fi + "$ENGINE" exec "$container" cat "$file" 2>/dev/null | parse_api_key "$name" || true +} -if [ -n "$SKIP_PROMPTS" ]; then - JACKETT_API="" - PROWLARR_API="" - qb_user="admin" - use_vpn="n" -else - if [ "$indexer_mode" == "1" ] || [ "$indexer_mode" == "3" ]; then - read -r -p "Enter Jackett API Key (press Enter to auto-extract later): " JACKETT_API +detect_existing_indexer() { + local name=$1 container port key + container=$("$ENGINE" ps --format '{{.Names}}' 2>/dev/null | grep -i "$name" | grep -vx "$PROJECT-$name" | head -n 1 || true) + [ -n "$container" ] || return 0 + say "[+] Found existing external $name container: $container" + port=$("$ENGINE" port "$container" 2>/dev/null | head -n 1 | awk -F':' '{print $NF}' || true) + if [ -z "$port" ]; then + if [ "$name" == "prowlarr" ]; then port="9696"; else port="9117"; fi fi - if [ "$indexer_mode" == "2" ] || [ "$indexer_mode" == "3" ]; then - read -r -p "Enter Prowlarr API Key (press Enter to auto-extract later): " PROWLARR_API + key=$(read_api_key "$name" "$container") + [ -n "$key" ] || return 0 + say "[+] Successfully extracted API key from external $name!" + if [ "$name" == "prowlarr" ]; then + EXTERNAL_PROWLARR_PORT="$port" EXTERNAL_PROWLARR_API="$key" + else + EXTERNAL_JACKETT_PORT="$port" EXTERNAL_JACKETT_API="$key" fi - read -r -p "Enter qBittorrent Username (default: admin): " qb_user - qb_user=${qb_user:-admin} - - echo "" - read -r -p "Do you want to route qBittorrent through a VPN using Gluetun? (y/N): " use_vpn -fi - -# Write docker-compose.yml -cat << 'EOF' > docker-compose.yml -services: -EOF - -if [[ ( "$indexer_mode" == "1" || "$indexer_mode" == "3" ) && -z "$EXTERNAL_JACKETT_API" ]]; then -cat << 'EOF' >> docker-compose.yml - jackett: - container_name: "${COMPOSE_PROJECT_NAME:-helm}-jackett" - image: lscr.io/linuxserver/jackett:latest - deploy: - resources: - limits: - cpus: "0.50" - memory: 256M - labels: - - "com.docker.compose.project=${COMPOSE_PROJECT_NAME:-helm}" - - "com.docker.compose.service=jackett" - - "com.docker.compose.oneoff=False" - dns: - - 8.8.8.8 - - 1.1.1.1 - environment: - - PUID=1000 - - PGID=1000 - - TZ=Etc/UTC - security_opt: - - label=disable - volumes: - - "$HELM_STATE"/jackett:/config - - "$HELM_DL":/downloads - ports: - - 19117:9117 - restart: unless-stopped -EOF -fi - -if [[ ( "$indexer_mode" == "2" || "$indexer_mode" == "3" ) && -z "$EXTERNAL_PROWLARR_API" ]]; then -cat << 'EOF' >> docker-compose.yml - prowlarr: - container_name: "${COMPOSE_PROJECT_NAME:-helm}-prowlarr" - image: lscr.io/linuxserver/prowlarr:latest - deploy: - resources: - limits: - cpus: "0.50" - memory: 256M - labels: - - "com.docker.compose.project=${COMPOSE_PROJECT_NAME:-helm}" - - "com.docker.compose.service=prowlarr" - - "com.docker.compose.oneoff=False" - dns: - - 8.8.8.8 - - 1.1.1.1 - environment: - - PUID=1000 - - PGID=1000 - - TZ=Etc/UTC - security_opt: - - label=disable - volumes: - - "$HELM_STATE"/prowlarr:/config - ports: - - 19696:9696 - restart: unless-stopped -EOF -fi +} -cat << 'EOF' >> docker-compose.yml - flaresolverr: - container_name: "${COMPOSE_PROJECT_NAME:-helm}-flaresolverr" - image: ghcr.io/flaresolverr/flaresolverr:latest - deploy: - resources: - limits: - cpus: "0.50" - memory: 512M - labels: - - "com.docker.compose.project=${COMPOSE_PROJECT_NAME:-helm}" - - "com.docker.compose.service=flaresolverr" - - "com.docker.compose.oneoff=False" - dns: - - 8.8.8.8 - - 1.1.1.1 - environment: - - LOG_LEVEL=info - - TZ=Etc/UTC - security_opt: - - label=disable - ports: - - 18191:8191 - restart: unless-stopped - - cli: - container_name: "${COMPOSE_PROJECT_NAME:-helm}-cli" - extra_hosts: - - "host.docker.internal:host-gateway" - image: ghcr.io/piratebird/helm:latest - dns: - - 8.8.8.8 - - 1.1.1.1 - stdin_open: true - tty: true - env_file: - - "$HELM_STATE"/.env.docker - security_opt: - - label=disable - volumes: - - "$HELM_CONFIG"/config.json:/app/config.json - - ${HOST_PWD:-.}/src:/app/src - - ${HOST_PWD:-.}/docker-compose.yml:/app/docker-compose.yml -EOF +detect_existing_indexers() { + EXTERNAL_JACKETT_PORT="" EXTERNAL_JACKETT_API="" + EXTERNAL_PROWLARR_PORT="" EXTERNAL_PROWLARR_API="" + if wants_jackett; then detect_existing_indexer jackett; fi + if wants_prowlarr; then detect_existing_indexer prowlarr; fi +} -if [ "$DOCKER_CMD" == "docker" ]; then - cat << 'EOF' >> docker-compose.yml - - /var/run/docker.sock:/var/run/docker.sock -EOF - elif [ "$DOCKER_CMD" == "podman" ]; then - echo "[INFO] Enabling Podman rootless socket for container orchestration..." - systemctl --user enable --now podman.socket 2>/dev/null || true - # Get the podman socket path (usually /run/user/1000/podman/podman.sock) - PODMAN_SOCK=$(podman info --format '{{.Host.RemoteSocket.Path}}' 2>/dev/null || echo "/run/user/$(id -u)/podman/podman.sock") - cat << EOF >> docker-compose.yml - - $PODMAN_SOCK:/var/run/docker.sock -EOF -fi +# ---------------------------------------------------------------- files + +# render_compose TEMPLATE "BLOCK ..." prints the compose file. +# The rules match helm.core.compose.render; tests compare the two. +render_compose() { + R_STATE="$HELM_STATE" R_DL="$HELM_DL" R_CONFIG="$HELM_CONFIG" R_SOCKET="$ENGINE_SOCKET" \ + awk -v blocks=" $2 " ' + function put(s, key, val, i, out) { + out = "" + while ((i = index(s, key)) > 0) { + out = out substr(s, 1, i - 1) val + s = substr(s, i + length(key)) + } + return out s + } + { line = $0; marker = line; sub(/^[ \t]+/, "", marker) } + marker ~ /^#@ if / { split(marker, f, " "); depth++; on[depth] = index(blocks, " " f[3] " ") > 0; next } + marker ~ /^#@ end/ { if (depth == 0) { bad = 1; exit } depth--; next } + marker ~ /^#@/ { next } + { + for (i = 1; i <= depth; i++) if (!on[i]) next + line = put(line, "@HELM_STATE@", ENVIRON["R_STATE"]) + line = put(line, "@HELM_DL@", ENVIRON["R_DL"]) + line = put(line, "@HELM_CONFIG@", ENVIRON["R_CONFIG"]) + line = put(line, "@ENGINE_SOCKET@", ENVIRON["R_SOCKET"]) + print line + } + END { if (bad || depth != 0) { print "unbalanced #@ blocks in compose template" > "/dev/stderr"; exit 1 } } + ' "$1" +} -cat << 'EOF' >> docker-compose.yml - profiles: - - cli -EOF +compose_blocks() { + local blocks="cli" + if local_jackett; then blocks="$blocks jackett"; fi + if local_prowlarr; then blocks="$blocks prowlarr"; fi + if [ -d "$PWD/src/helm" ]; then blocks="$blocks source"; fi + if is_yes "$use_vpn"; then blocks="$blocks vpn"; else blocks="$blocks novpn"; fi + printf '%s\n' "$blocks" +} -if [[ "$use_vpn" =~ ^[Yy]$ ]]; then - echo "" - echo "--- VPN Configuration ---" - read -r -p "Enter VPN Provider (e.g. nordvpn, custom): " vpn_provider - - if [ "$vpn_provider" = "protonvpn" ]; then - echo "" - echo "[WARNING] ProtonVPN strictly blocks P2P/torrent traffic on their Free tier." - echo " If you are on the Free tier, qBittorrent will be permanently stalled." - echo " Please ensure you are using a Paid ProtonVPN account." - echo "" - fi - - read -r -p "Enter VPN Type (wireguard/openvpn) (default: wireguard): " vpn_type - vpn_type=${vpn_type:-wireguard} - - vpn_extra="" - if [ -z "$vpn_provider" ]; then - echo "[ERROR] VPN Provider cannot be empty. Disabling VPN." - use_vpn="n" - elif [ "$vpn_type" = "wireguard" ]; then - read -r -p "Enter WireGuard Private Key: " wg_key - if [ -z "$wg_key" ]; then - echo "[ERROR] WireGuard key cannot be empty. Disabling VPN." - use_vpn="n" - else - vpn_extra="WIREGUARD_PRIVATE_KEY=$wg_key" - fi - elif [ "$vpn_type" = "openvpn" ]; then - if [ "$vpn_provider" != "custom" ]; then - read -r -p "Enter OpenVPN Username (or token): " ovpn_user - read -r -s -p "Enter OpenVPN Password (leave blank if using token): " ovpn_pass - echo "" - if [ -z "$ovpn_user" ]; then - echo "[ERROR] OpenVPN user cannot be empty. Disabling VPN." - use_vpn="n" - else - vpn_extra="OPENVPN_USER=$ovpn_user"$'\n'"OPENVPN_PASSWORD=$ovpn_pass" - fi +fetch_template() { + local local_file="$SCRIPT_DIR/$TEMPLATE_PATH_IN_REPO" url="$HELM_RAW_BASE/$TEMPLATE_PATH_IN_REPO" + if [ -n "${HELM_COMPOSE_TEMPLATE:-}" ]; then + TEMPLATE_FILE="$HELM_COMPOSE_TEMPLATE" + elif [ -f "$local_file" ]; then + TEMPLATE_FILE="$local_file" + else + TEMPLATE_FILE=$(mktemp) + TEMPLATE_TEMP=1 + info "Downloading the compose template from $url" + if command -v curl &> /dev/null; then + curl -fsSL "$url" -o "$TEMPLATE_FILE" || die "Could not download $url" else - echo "[INFO] For 'custom' OpenVPN, ensure you place custom.conf (and auth.conf if needed) in ${HELM_STATE}/gluetun" + wget -q -O "$TEMPLATE_FILE" "$url" || die "Could not download $url" fi fi -fi - -if [[ "$use_vpn" =~ ^[Yy]$ ]]; then - echo "Configuring with VPN (Gluetun)..." - cat << 'EOF' >> docker-compose.yml - - gluetun: - container_name: "${COMPOSE_PROJECT_NAME:-helm}-gluetun" - image: qmcgaw/gluetun:latest - deploy: - resources: - limits: - cpus: "0.25" - memory: 128M - labels: - - "com.docker.compose.project=${COMPOSE_PROJECT_NAME:-helm}" - - "com.docker.compose.service=gluetun" - - "com.docker.compose.oneoff=False" - cap_add: - - NET_ADMIN - devices: - - /dev/net/tun:/dev/net/tun - env_file: - - "$HELM_STATE"/.env.docker - volumes: - - "$HELM_STATE"/gluetun:/gluetun - ports: - - 18080:8080 - - 6881:6881 - - 6881:6881/udp - restart: unless-stopped - - qbittorrent: - container_name: "${COMPOSE_PROJECT_NAME:-helm}-qbittorrent" - image: lscr.io/linuxserver/qbittorrent:latest - deploy: - resources: - limits: - cpus: "0.50" - memory: 256M - labels: - - "com.docker.compose.project=${COMPOSE_PROJECT_NAME:-helm}" - - "com.docker.compose.service=qbittorrent" - - "com.docker.compose.oneoff=False" - network_mode: "service:gluetun" - environment: - - PUID=1000 - - PGID=1000 - - TZ=Etc/UTC - - WEBUI_PORT=18080 - security_opt: - - label=disable - volumes: - - "$HELM_STATE"/qbittorrent:/config - - "$HELM_DL":/downloads - depends_on: - - gluetun - restart: unless-stopped -EOF -else - echo "Configuring WITHOUT VPN..." - cat << 'EOF' >> docker-compose.yml - - qbittorrent: - container_name: "${COMPOSE_PROJECT_NAME:-helm}-qbittorrent" - image: lscr.io/linuxserver/qbittorrent:latest - deploy: - resources: - limits: - cpus: "0.50" - memory: 256M - labels: - - "com.docker.compose.project=${COMPOSE_PROJECT_NAME:-helm}" - - "com.docker.compose.service=qbittorrent" - - "com.docker.compose.oneoff=False" - dns: - - 8.8.8.8 - - 1.1.1.1 - environment: - - PUID=1000 - - PGID=1000 - - TZ=Etc/UTC - - WEBUI_PORT=18080 - security_opt: - - label=disable - volumes: - - "$HELM_STATE"/qbittorrent:/config - - "$HELM_DL":/downloads - ports: - - 18080:18080 - - 6881:6881 - - 6881:6881/udp - restart: unless-stopped -EOF -fi - -sed -i "s|\"\$HELM_STATE\"|$HELM_STATE|g" docker-compose.yml -sed -i "s|\"\$HELM_CONFIG\"|$HELM_CONFIG|g" docker-compose.yml -sed -i "s|\"\$HELM_DL\"|$HELM_DL|g" docker-compose.yml - -cat << EOF > "$HELM_STATE"/.env.docker -# --- Helm Container Isolated Configuration --- -JACKETT_URL=http://${EXTERNAL_JACKETT_PORT:+host.docker.internal:$EXTERNAL_JACKETT_PORT}${EXTERNAL_JACKETT_PORT:-jackett:9117} -JACKETT_API_KEY=\${JACKETT_API:-placeholder} -PROWLARR_URL=http://${EXTERNAL_PROWLARR_PORT:+host.docker.internal:$EXTERNAL_PROWLARR_PORT}${EXTERNAL_PROWLARR_PORT:-prowlarr:9696} -PROWLARR_API_KEY=\${PROWLARR_API:-placeholder} -QB_WEBUI=http://qbittorrent:18080 -QB_USERNAME=$qb_user -QB_PASSWORD=adminadmin -COMPOSE_PROJECT_NAME=${PWD##*/} -HOST_PWD=$PWD -EOF - -if [[ "$use_vpn" =~ ^[Yy]$ ]]; then - cat << EOF >> "$HELM_STATE"/.env.docker + [ -s "$TEMPLATE_FILE" ] || die "Compose template is missing or empty: $TEMPLATE_FILE" +} -# --- VPN (Gluetun) Configuration --- -VPN_SERVICE_PROVIDER=$vpn_provider -VPN_TYPE=$vpn_type -$vpn_extra -EOF -fi +write_compose() { + fetch_template + local blocks + blocks=$(compose_blocks) + if is_yes "$use_vpn"; then say "Configuring with VPN (Gluetun)..."; else say "Configuring WITHOUT VPN..."; fi + render_compose "$TEMPLATE_FILE" "$blocks" > "$COMPOSE_FILE.tmp" + mv "$COMPOSE_FILE.tmp" "$COMPOSE_FILE" + if [ -n "${TEMPLATE_TEMP:-}" ]; then rm -f "$TEMPLATE_FILE"; fi +} +# set_env_value KEY VALUE replaces KEY's line in .env.docker. +set_env_value() { + local file="$ENV_FILE" + ( + umask 077 + K="$1" V="$2" awk 'index($0, ENVIRON["K"] "=") == 1 { print ENVIRON["K"] "=" ENVIRON["V"]; next } { print }' \ + "$file" > "$file.tmp" + ) + mv "$file.tmp" "$file" +} -# Orchestrate existing containers -detect_existing_indexer() { - local indexer_name=$1 - local existing_container - local bound_port - local ext_api - existing_container=$($DOCKER_CMD ps --format '{{.Names}}' | grep -i "$indexer_name" | grep -v "helm-$indexer_name" | head -n 1 || true) - if [ -n "$existing_container" ]; then - echo "[+] Found existing external $indexer_name container: $existing_container" - # Try to extract the port it's bound to - bound_port=$($DOCKER_CMD port "$existing_container" | head -n 1 | awk -F':' '{print $NF}') - if [ -z "$bound_port" ]; then - if [ "$indexer_name" == "prowlarr" ]; then bound_port="9696"; else bound_port="9117"; fi - fi - - # Try to extract API key - ext_api="" - if [ "$indexer_name" == "prowlarr" ]; then - ext_api=$($DOCKER_CMD exec "$existing_container" grep -oP '(?<=)[^<]+' /config/config.xml 2>/dev/null || true) - elif [ "$indexer_name" == "jackett" ]; then - ext_api=$($DOCKER_CMD exec "$existing_container" grep -o '"APIKey": "[^"]*"' /config/Jackett/ServerConfig.json 2>/dev/null | cut -d'"' -f4 || true) - fi - - if [ -n "$ext_api" ]; then - echo "[+] Successfully extracted API key from external $indexer_name!" - if [ "$indexer_name" == "prowlarr" ]; then - EXTERNAL_PROWLARR_PORT="$bound_port" - EXTERNAL_PROWLARR_API="$ext_api" - else - EXTERNAL_JACKETT_PORT="$bound_port" - EXTERNAL_JACKETT_API="$ext_api" +write_env_file() { + local jackett_url="http://jackett:9117" prowlarr_url="http://prowlarr:9696" qb_host="qbittorrent" + if [ -n "$EXTERNAL_JACKETT_PORT" ]; then jackett_url="http://host.docker.internal:$EXTERNAL_JACKETT_PORT"; fi + if [ -n "$EXTERNAL_PROWLARR_PORT" ]; then prowlarr_url="http://host.docker.internal:$EXTERNAL_PROWLARR_PORT"; fi + # With a VPN, qBittorrent shares gluetun's network, so only that name resolves. + if is_yes "$use_vpn"; then qb_host="gluetun"; fi + ( + umask 077 + { + say "# --- Helm Container Isolated Configuration ---" + say "JACKETT_URL=$jackett_url" + say "JACKETT_API_KEY=${EXTERNAL_JACKETT_API:-${JACKETT_API:-placeholder}}" + say "PROWLARR_URL=$prowlarr_url" + say "PROWLARR_API_KEY=${EXTERNAL_PROWLARR_API:-${PROWLARR_API:-placeholder}}" + say "QB_WEBUI=http://$qb_host:18080" + say "QB_USERNAME=$qb_user" + say "QB_PASSWORD=adminadmin" + say "INDEXER_MANAGER=$INDEXER_MANAGER" + say "COMPOSE_PROJECT_NAME=$PROJECT" + say "HOST_PWD=$PWD" + if is_yes "$use_vpn"; then + say "" + say "# --- VPN (Gluetun) Configuration ---" + say "VPN_SERVICE_PROVIDER=$vpn_provider" + say "VPN_TYPE=$vpn_type" + if [ -n "$vpn_extra" ]; then say "$vpn_extra"; fi fi - return 0 - fi - fi - return 1 + } > "$ENV_FILE" + ) + chmod 600 "$ENV_FILE" } -EXTERNAL_PROWLARR_PORT="" -EXTERNAL_PROWLARR_API="" -EXTERNAL_JACKETT_PORT="" -EXTERNAL_JACKETT_API="" - -if [ "$indexer_mode" == "1" ] || [ "$indexer_mode" == "3" ]; then - detect_existing_indexer "jackett" || true -fi -if [ "$indexer_mode" == "2" ] || [ "$indexer_mode" == "3" ]; then - detect_existing_indexer "prowlarr" || true -fi - -echo "Pulling the latest helm image..." -$COMPOSE_CMD --profile cli pull cli - -run_compose() { - if [ "$DOCKER_CMD" == "podman" ]; then - podman run --rm --entrypoint="" --security-opt label=disable -v "$PWD:/app" -v "$PODMAN_SOCK:/var/run/docker.sock" --env-file "$HELM_STATE"/.env.docker mini-helm docker compose "$@" 2> >(grep -v "rootless netns" >&2) - else - $COMPOSE_CMD "$@" - fi +seed_jackett() { + local dir="$HELM_STATE/jackett/Jackett/Indexers" name site + say "Seeding default Jackett indexers..." + mkdir -p "$dir" + for name in 1337x yts nyaasi thepiratebay; do + case $name in + 1337x) site="https://1337x.to/" ;; + yts) site="https://yts.mx/" ;; + nyaasi) site="https://nyaa.si/" ;; + thepiratebay) site="https://thepiratebay.org/" ;; + esac + printf '[{"id": "sitelink","type": "inputstring","name": "Site Link","value": "%s"}]\n' "$site" > "$dir/$name.json" + done } -echo "Seeding default Jackett indexers..." -mkdir -p "$HELM_STATE"/jackett/Jackett/Indexers - -cat << 'EOF' > "$HELM_STATE"/jackett/Jackett/Indexers/1337x.json -[{"id": "sitelink","type": "inputstring","name": "Site Link","value": "https://1337x.to/"}] -EOF -cat << 'EOF' > "$HELM_STATE"/jackett/Jackett/Indexers/yts.json -[{"id": "sitelink","type": "inputstring","name": "Site Link","value": "https://yts.mx/"}] -EOF -cat << 'EOF' > "$HELM_STATE"/jackett/Jackett/Indexers/nyaasi.json -[{"id": "sitelink","type": "inputstring","name": "Site Link","value": "https://nyaa.si/"}] -EOF -cat << 'EOF' > "$HELM_STATE"/jackett/Jackett/Indexers/thepiratebay.json -[{"id": "sitelink","type": "inputstring","name": "Site Link","value": "https://thepiratebay.org/"}] -EOF - -echo "Pre-seeding qBittorrent configuration..." -mkdir -p "$HELM_STATE"/qbittorrent/qBittorrent/ -cat << 'EOF' > "$HELM_STATE"/qbittorrent/qBittorrent/qBittorrent.conf +seed_qbittorrent() { + local dir="$HELM_STATE/qbittorrent/qBittorrent" + mkdir -p "$dir" + if [ -f "$dir/qBittorrent.conf" ]; then + info "Keeping the existing qBittorrent configuration." + return 0 + fi + say "Pre-seeding qBittorrent configuration..." + cat > "$dir/qBittorrent.conf" <<'EOF' [Preferences] WebUI\Password_PBKDF2="@ByteArray(ARQ77eY1NUZaQsuDHbIMCA==:0WMRkYTUWVT9wVvdDtHAjU9b3b7uB8NR1Gur2hmQCvCDpm39Q+PsIfSYvgkvpe7L5yL8YQv8EaV7t8mP308QWg==)" WebUI\Username=admin @@ -789,171 +599,156 @@ WebUI\AuthSubnetWhitelist=10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16 WebUI\AuthSubnetWhitelistEnabled=true WebUI\LocalHostAuth=false EOF +} -echo "" -echo "Starting containers in the background to initialize configurations..." +# ---------------------------------------------------------------- stack -SERVICES_TO_START=(qbittorrent flaresolverr) -if [[ ( "$indexer_mode" == "1" || "$indexer_mode" == "3" ) && -z "$EXTERNAL_JACKETT_API" ]]; then - SERVICES_TO_START+=("jackett") -fi -if [[ ( "$indexer_mode" == "2" || "$indexer_mode" == "3" ) && -z "$EXTERNAL_PROWLARR_API" ]]; then - SERVICES_TO_START+=("prowlarr") -fi +compose() { "${COMPOSE_CMD[@]}" -f "$COMPOSE_FILE" "$@"; } -run_compose up -d --remove-orphans "${SERVICES_TO_START[@]}" +# Podman runs compose from inside the Helm image, against the Podman socket. +run_compose() { + if [ "$ENGINE" == "podman" ]; then + podman run --rm --entrypoint="" --security-opt label=disable \ + -v "$PWD:/app" -v "$ENGINE_SOCKET:/var/run/docker.sock" --env-file "$ENV_FILE" \ + "$HELM_IMAGE" docker compose -f /app/docker-compose.yml "$@" 2> >(grep -v "rootless netns" >&2) + else + compose "$@" + fi +} -echo "[INFO] Waiting for services to initialize..." +container_id() { + "$ENGINE" ps -q -f "name=$PROJECT-$1" 2>/dev/null | head -n 1 || true +} -TIMEOUT=45 -ELAPSED=0 +start_services() { + local services=(qbittorrent flaresolverr) + if local_jackett; then services+=(jackett); fi + if local_prowlarr; then services+=(prowlarr); fi + say "" + say "Starting containers in the background to initialize configurations..." + run_compose up -d --remove-orphans "${services[@]}" +} -while [ "$ELAPSED" -lt "$TIMEOUT" ]; do - if [ "$indexer_mode" == "2" ]; then - CRITICAL_CONTAINER=$($DOCKER_CMD ps -q -f "name=${COMPOSE_PROJECT_NAME:-helm}-prowlarr" | head -n 1 || true) - CRITICAL_NAME="prowlarr" - else - CRITICAL_CONTAINER=$($DOCKER_CMD ps -q -f "name=${COMPOSE_PROJECT_NAME:-helm}-jackett" | head -n 1 || true) - CRITICAL_NAME="jackett" - fi - - if [ -n "$CRITICAL_CONTAINER" ]; then - IS_RUNNING=$($DOCKER_CMD inspect -f '{{.State.Running}}' "$CRITICAL_CONTAINER" 2>/dev/null || true) - - if [ "$IS_RUNNING" == "true" ]; then - echo "[OK] Services are initialized and running!" - break - fi - - IS_EXITED=$($DOCKER_CMD inspect -f '{{.State.Status}}' "$CRITICAL_CONTAINER" 2>/dev/null || true) - if [ "$IS_EXITED" == "exited" ]; then - echo "[ERROR] Container $CRITICAL_NAME started but crashed immediately." - echo "Resolution: Run 'run_compose logs $CRITICAL_NAME' to inspect the failure." - exit 1 +wait_for_services() { + local name="qbittorrent" elapsed=0 container state + if local_jackett; then name="jackett"; elif local_prowlarr; then name="prowlarr"; fi + info "Waiting for services to initialize..." + while [ "$elapsed" -lt "$SETUP_TIMEOUT" ]; do + container=$(container_id "$name") + if [ -n "$container" ]; then + state=$("$ENGINE" inspect -f '{{.State.Status}}' "$container" 2>/dev/null || true) + if [ "$state" == "running" ]; then + ok "Services are initialized and running!" + return 0 + fi + if [ "$state" == "exited" ]; then + die "Container $name started but crashed immediately. Run '$ENGINE logs $PROJECT-$name' to see why." + fi fi - fi - - sleep 5 - ELAPSED=$((ELAPSED + 5)) - echo "Polling status... ($ELAPSED/$TIMEOUT seconds)" -done - -if [ "$ELAPSED" -ge "$TIMEOUT" ]; then - echo "[WARNING] Timeout reached while waiting for configurations." - echo "Services may be experiencing slow startup times or are hanging." -fi + sleep "$SETUP_POLL" + elapsed=$((elapsed + SETUP_POLL)) + if [ "$SETUP_POLL" -eq 0 ]; then elapsed=$((elapsed + 1)); fi + say "Polling status... ($elapsed/$SETUP_TIMEOUT seconds)" + done + warn "Timeout reached while waiting for configurations." + warn "Services may be experiencing slow startup times or are hanging." +} -JACKETT_CONTAINER="" - -if [ "$indexer_mode" == "1" ] || [ "$indexer_mode" == "3" ]; then - if [ -n "$EXTERNAL_JACKETT_API" ]; then JACKETT_API="$EXTERNAL_JACKETT_API"; fi - if [ -z "$JACKETT_API" ]; then - for _ in {1..15}; do - JACKETT_CONTAINER=$($DOCKER_CMD ps -q -f "name=${COMPOSE_PROJECT_NAME:-helm}-jackett" | head -n 1 || true) - if [ -n "$JACKETT_CONTAINER" ]; then - extracted_api=$($DOCKER_CMD exec "$JACKETT_CONTAINER" cat /config/Jackett/ServerConfig.json 2>/dev/null | python3 -c "import sys,json; print(json.load(sys.stdin).get('APIKey',''))" 2>/dev/null || true) - if [ ! -z "$extracted_api" ]; then - JACKETT_API="$extracted_api" - echo "[+] Successfully grabbed Jackett API Key." - - $DOCKER_CMD exec "$JACKETT_CONTAINER" sed -i 's|"FlareSolverrUrl":.*|"FlareSolverrUrl": "http://flaresolverr:8191",|' /config/Jackett/ServerConfig.json 2>/dev/null || true - run_compose restart jackett - echo "[+] Jackett configured with FlareSolverr." - break - fi +# grab_api_key NAME prints the key read from Helm's own container, or nothing. +grab_api_key() { + local name=$1 container key try + for ((try = 0; try < KEY_TRIES; try++)); do + container=$(container_id "$name") + if [ -n "$container" ]; then + key=$(read_api_key "$name" "$container") + if [ -n "$key" ]; then + printf '%s\n' "$key" + return 0 fi - sleep 3 - done - - if [ -z "$JACKETT_API" ]; then - echo "[-] Could not find APIKey in Jackett configuration. Using placeholder." - JACKETT_API="your_jackett_api_key_here" fi - fi - # Re-write .env.docker with the true JACKETT_API_KEY - sed -i "s|JACKETT_API_KEY=.*|JACKETT_API_KEY=$JACKETT_API|" "$HELM_STATE"/.env.docker -fi + sleep "$KEY_POLL" + done +} -if [ "$indexer_mode" == "2" ] || [ "$indexer_mode" == "3" ]; then - if [ -n "$EXTERNAL_PROWLARR_API" ]; then PROWLARR_API="$EXTERNAL_PROWLARR_API"; fi - if [ -z "$PROWLARR_API" ]; then - for _ in {1..15}; do - PROWLARR_CONTAINER=$($DOCKER_CMD ps -q -f "name=${COMPOSE_PROJECT_NAME:-helm}-prowlarr" | head -n 1 || true) - if [ -n "$PROWLARR_CONTAINER" ]; then - extracted_api=$($DOCKER_CMD exec "$PROWLARR_CONTAINER" grep -oP '(?<=)[^<]+' /config/config.xml 2>/dev/null || true) - if [ ! -z "$extracted_api" ]; then - PROWLARR_API="$extracted_api" - echo "[+] Successfully grabbed Prowlarr API Key." - break - fi +configure_api_keys() { + if wants_jackett; then + JACKETT_API="${EXTERNAL_JACKETT_API:-$JACKETT_API}" + if [ -z "$JACKETT_API" ]; then + JACKETT_API=$(grab_api_key jackett) + if [ -n "$JACKETT_API" ]; then + say "[+] Successfully grabbed Jackett API Key." + "$ENGINE" exec "$(container_id jackett)" \ + sed -i 's|"FlareSolverrUrl":.*|"FlareSolverrUrl": "http://flaresolverr:8191",|' \ + /config/Jackett/ServerConfig.json 2>/dev/null || true + run_compose restart jackett + say "[+] Jackett configured with FlareSolverr." + else + warn "Could not find APIKey in Jackett configuration. Using placeholder." + JACKETT_API="your_jackett_api_key_here" fi - sleep 3 - done - + fi + set_env_value JACKETT_API_KEY "$JACKETT_API" + fi + if wants_prowlarr; then + PROWLARR_API="${EXTERNAL_PROWLARR_API:-$PROWLARR_API}" if [ -z "$PROWLARR_API" ]; then - echo "[-] Could not find APIKey in Prowlarr configuration. Using placeholder." - PROWLARR_API="your_prowlarr_api_key_here" + PROWLARR_API=$(grab_api_key prowlarr) + if [ -n "$PROWLARR_API" ]; then + say "[+] Successfully grabbed Prowlarr API Key." + else + warn "Could not find APIKey in Prowlarr configuration. Using placeholder." + PROWLARR_API="your_prowlarr_api_key_here" + fi fi + set_env_value PROWLARR_API_KEY "$PROWLARR_API" fi - # Re-write .env.docker with the true PROWLARR_API_KEY - sed -i "s|PROWLARR_API_KEY=.*|PROWLARR_API_KEY=$PROWLARR_API|" "$HELM_STATE"/.env.docker -fi +} + +# ---------------------------------------------------------------- finish + +quote_words() { + local word out="" + for word in "$@"; do out="$out $(printf '%q' "$word")"; done + printf '%s' "${out# }" +} -echo "" -echo "Setup is 100% complete! Everything is configured." -echo "Your native .env and config.json secrets were left completely untouched." -echo "helm's own config.json gained an INDEXER_MANAGER setting only." -echo "---" -echo "Security Summary & Data Locations:" -echo " - Settings: ~/.config/helm/" -echo " - Databases: ~/.local/state/helm/" -echo " - Secrets: ~/.local/state/helm/.env.docker" -echo " - Downloads: ~/Downloads/helm/" -echo "---" -echo "" - -if [ "$run_mode" == "2" ]; then - echo "Tearing down containers for Ephemeral (One-Shot) mode..." - if [ "$DOCKER_CMD" == "podman" ]; then - # Use podman stop directly - avoids docker compose's network namespace destruction - # which triggers the "rootless netns: kill network process: permission denied" bug - podman stop "${COMPOSE_PROJECT_NAME:-helm}"-prowlarr "${COMPOSE_PROJECT_NAME:-helm}"-jackett "${COMPOSE_PROJECT_NAME:-helm}"-qbittorrent "${COMPOSE_PROJECT_NAME:-helm}"-flaresolverr "${COMPOSE_PROJECT_NAME:-helm}"-gluetun 2>/dev/null || true +write_launcher() { + local file="$PWD/helm-torrent.sh" run + if [ "$ENGINE" == "podman" ]; then + run=$(quote_words podman run -it --rm --entrypoint= --security-opt label=disable \ + --network "${PROJECT}_default" -v "$PWD:/app" -v "$HELM_CONFIG:/config/helm" \ + -e HELM_CONFIG_DIR=/config/helm -v "$ENGINE_SOCKET:/var/run/docker.sock" \ + --env-file "$ENV_FILE" "$HELM_IMAGE" python -m helm.cli) + run="$run \"\$@\" 2> >(grep -v \"rootless netns\" >&2)" else - run_compose stop || true + run="exec $(quote_words "${COMPOSE_CMD[@]}" -f "$COMPOSE_FILE" --profile cli run --rm cli) \"\$@\"" fi - echo "Generating helm-torrent launcher script..." - cat << EOF > helm-torrent.sh + say "Generating helm-torrent launcher script..." + cat > "$file" < >(grep -v "rootless netns" >&2) -else - $COMPOSE_CMD --profile cli run --rm cli \$ARGS +# Generated by setup.sh for $ENGINE. Re-run setup.sh to change it. +set -e +export COMPOSE_PROJECT_NAME=$(printf '%q' "$PROJECT") +oneshot=0 +for arg in "\$@"; do + case "\$arg" in + -o|--oneshot) oneshot=1 ;; + esac +done +if [ "\$oneshot" -eq 0 ]; then + set -- --oneshot "\$@" fi +$run EOF - chmod +x helm-torrent.sh - - echo "Containers stopped. Helm will spin them up automatically when you trigger a download." - echo "" - echo "To start using the app in its isolated CLI container, run:" - echo " ./helm-torrent.sh --oneshot" - echo "===========================================" -else - echo "Containers are left running 24/7 in the background." - echo "" - if [ -n "$SKIP_PROMPTS" ]; then - install_systemd="n" - else - read -r -p "Do you want to create a systemd service to start Helm automatically on boot? (y/N): " install_systemd - fi - if [[ "$install_systemd" =~ ^[Yy]$ ]]; then - echo "Creating systemd service..." - cat << EOF | sudo tee /etc/systemd/system/helm-app.service > /dev/null + chmod +x "$file" +} + +install_systemd_unit() { + local compose_bin + compose_bin=$(command -v "${COMPOSE_CMD[0]}") + compose_bin=$(quote_words "$compose_bin" "${COMPOSE_CMD[@]:1}" -f "$COMPOSE_FILE") + say "Creating systemd service..." + sudo tee /etc/systemd/system/helm-app.service > /dev/null </dev/null || true' +Environment=COMPOSE_PROJECT_NAME=$PROJECT +ExecStart=$compose_bin up -d +ExecStop=$compose_bin stop TimeoutStartSec=0 [Install] WantedBy=multi-user.target EOF - sudo systemctl daemon-reload - sudo systemctl enable helm-app.service - echo "Systemd service 'helm-app.service' created and enabled." - fi - echo "" - echo "To start using the app in its isolated CLI container, run:" - echo " $COMPOSE_CMD --profile cli run --rm cli" - echo "===========================================" + sudo systemctl daemon-reload + sudo systemctl enable helm-app.service + say "Systemd service 'helm-app.service' created and enabled." +} + +print_summary() { + say "" + say "Setup is 100% complete! Everything is configured." + say "Your config files and secrets.env were not changed." + say "---" + say "Security Summary & Data Locations:" + say " - Settings: $HELM_CONFIG/" + say " - Databases: $HELM_STATE/" + say " - Secrets: $ENV_FILE (mode 600)" + say " - Downloads: $HELM_DL/" + say "---" + if [ -f "$HELM_CONFIG/config.toml" ] || [ -f "$HELM_CONFIG/config.jsonc" ]; then + info "The containers use INDEXER_MANAGER=$INDEXER_MANAGER from $ENV_FILE." + info "For a helm-torrent on this machine, set search.indexer_manager = \"$INDEXER_MANAGER\" in your config file." + fi + say "" +} + +stop_stack() { + say "Tearing down containers for Ephemeral (One-Shot) mode..." + if [ "$ENGINE" == "podman" ]; then + # podman stop avoids compose tearing down the network namespace, which hits + # "rootless netns: kill network process: permission denied". + local service names=() + for service in prowlarr jackett qbittorrent flaresolverr gluetun; do names+=("$PROJECT-$service"); done + podman stop "${names[@]}" 2>/dev/null || true + else + run_compose stop || true + fi +} + +finish() { + if [ "$run_mode" == "2" ]; then + stop_stack + write_launcher + say "Containers stopped. Helm will spin them up automatically when you trigger a download." + say "" + say "To start using the app in its isolated CLI container, run:" + say " ./helm-torrent.sh" + else + say "Containers are left running 24/7 in the background." + say "" + local install_systemd + ask install_systemd "Do you want to create a systemd service to start Helm automatically on boot? (y/N): " n + if is_yes "$install_systemd"; then install_systemd_unit; fi + say "" + say "To start using the app in its isolated CLI container, run:" + say " $(quote_words "${COMPOSE_CMD[@]}" --profile cli run --rm cli)" + fi + rule +} + +main() { + setup_colours + SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" 2>/dev/null && pwd || true)" + PROJECT="${COMPOSE_PROJECT_NAME:-helm}" + export COMPOSE_PROJECT_NAME="$PROJECT" + default_paths + parse_args "$@" + + say "Using paths:" + say " Config: $HELM_CONFIG" + say " State: $HELM_STATE" + say " Downloads: $HELM_DL" + say "" + rule + say " Helm Application Setup Script " + rule + say "" + + choose_install + case "$install_mode" in + 3) install_native; exit 0 ;; + 2) check_podman ;; + *) check_docker ;; + esac + ok "Container engine and compose are functional." + + COMPOSE_FILE="$PWD/docker-compose.yml" + ENV_FILE="$HELM_STATE/.env.docker" + mkdir -p "$HELM_STATE/jackett" "$HELM_STATE/prowlarr" "$HELM_STATE/qbittorrent" "$HELM_STATE/gluetun" "$HELM_DL" "$HELM_CONFIG" + + detect_existing_indexers + say "" + choose_stack + write_compose + write_env_file + + say "Pulling the latest helm image..." + compose --profile cli pull cli + + if local_jackett; then seed_jackett; fi + seed_qbittorrent + start_services + wait_for_services + configure_api_keys + print_summary + finish +} + +if [[ "${BASH_SOURCE[0]}" == "$0" ]]; then + main "$@" fi diff --git a/src/helm/core/compose.py b/src/helm/core/compose.py new file mode 100644 index 0000000..c5cffd5 --- /dev/null +++ b/src/helm/core/compose.py @@ -0,0 +1,67 @@ +"""Render the one compose template that setup.sh and ``helm-torrent init`` share. + +The rules match ``render_compose`` in setup.sh exactly, and a test checks that +both give the same output for every block combination: + +- ``#@ if NAME`` ... ``#@ end`` keeps the lines between only when NAME is on. + Blocks can nest. +- Any other line starting with ``#@`` is dropped. +- Each placeholder in ``PLACEHOLDERS`` is replaced literally. +""" + +from pathlib import Path + +TEMPLATE = Path(__file__).with_name("compose.template.yml") +BLOCKS = frozenset(["jackett", "prowlarr", "cli", "source", "vpn", "novpn"]) +PLACEHOLDERS = ("HELM_STATE", "HELM_DL", "HELM_CONFIG", "ENGINE_SOCKET") + + +class TemplateError(ValueError): + pass + + +def check_blocks(blocks): + unknown = set(blocks) - BLOCKS + if unknown: + raise TemplateError(f"Unknown compose block(s): {', '.join(sorted(unknown))}") + if ("vpn" in blocks) == ("novpn" in blocks): + raise TemplateError("Choose exactly one of the vpn and novpn blocks") + + +def check_value(name, value): + if any(char in value for char in '"\n\r'): + raise TemplateError(f"{name} cannot contain quotes or line breaks: {value!r}") + + +def render(blocks, values, template=None): + """Return the compose file for ``blocks`` with ``values`` filled in.""" + blocks = set(blocks) + check_blocks(blocks) + missing = [name for name in PLACEHOLDERS if name not in values] + if missing: + raise TemplateError(f"Missing compose value(s): {', '.join(missing)}") + for name in PLACEHOLDERS: + check_value(name, values[name]) + + text = TEMPLATE.read_text(encoding="utf-8") if template is None else template + stack = [] + out = [] + for number, line in enumerate(text.splitlines(keepends=True), 1): + marker = line.strip() + if marker.startswith("#@ if "): + stack.append(marker.split()[2] in blocks) + continue + if marker.startswith("#@ end"): + if not stack: + raise TemplateError(f"Unmatched '#@ end' on line {number}") + stack.pop() + continue + if marker.startswith("#@"): + continue + if all(stack): + for name in PLACEHOLDERS: + line = line.replace(f"@{name}@", values[name]) + out.append(line) + if stack: + raise TemplateError("Unclosed '#@ if' block in the compose template") + return "".join(out) diff --git a/src/helm/core/compose.template.yml b/src/helm/core/compose.template.yml new file mode 100644 index 0000000..3901fc8 --- /dev/null +++ b/src/helm/core/compose.template.yml @@ -0,0 +1,188 @@ +#@ Template rules, shared by setup.sh (render_compose) and helm.core.compose: +#@ "if NAME" ... "end" marker lines keep what is between them only when +#@ block NAME is on. Blocks nest. Lines starting with these markers never +#@ reach the output. The four placeholders (state, downloads, config and +#@ engine socket, each written between at-signs) become real paths, and +#@ ${...} values are left for compose to fill in. +# Generated by Helm from src/helm/core/compose.template.yml. +# Re-run ./setup.sh (or helm-torrent init) to change it instead of editing it. + +services: +#@ if jackett + jackett: + container_name: "${COMPOSE_PROJECT_NAME:-helm}-jackett" + image: lscr.io/linuxserver/jackett:latest + deploy: + resources: + limits: + cpus: "0.50" + memory: 256M + labels: + - "com.docker.compose.project=${COMPOSE_PROJECT_NAME:-helm}" + - "com.docker.compose.service=jackett" + - "com.docker.compose.oneoff=False" + dns: + - 8.8.8.8 + - 1.1.1.1 + environment: + - PUID=1000 + - PGID=1000 + - TZ=Etc/UTC + security_opt: + - label=disable + volumes: + - "@HELM_STATE@/jackett:/config" + - "@HELM_DL@:/downloads" + ports: + - 19117:9117 + restart: unless-stopped + +#@ end +#@ if prowlarr + prowlarr: + container_name: "${COMPOSE_PROJECT_NAME:-helm}-prowlarr" + image: lscr.io/linuxserver/prowlarr:latest + deploy: + resources: + limits: + cpus: "0.50" + memory: 256M + labels: + - "com.docker.compose.project=${COMPOSE_PROJECT_NAME:-helm}" + - "com.docker.compose.service=prowlarr" + - "com.docker.compose.oneoff=False" + dns: + - 8.8.8.8 + - 1.1.1.1 + environment: + - PUID=1000 + - PGID=1000 + - TZ=Etc/UTC + security_opt: + - label=disable + volumes: + - "@HELM_STATE@/prowlarr:/config" + ports: + - 19696:9696 + restart: unless-stopped + +#@ end + flaresolverr: + container_name: "${COMPOSE_PROJECT_NAME:-helm}-flaresolverr" + image: ghcr.io/flaresolverr/flaresolverr:latest + deploy: + resources: + limits: + cpus: "0.50" + memory: 512M + labels: + - "com.docker.compose.project=${COMPOSE_PROJECT_NAME:-helm}" + - "com.docker.compose.service=flaresolverr" + - "com.docker.compose.oneoff=False" + dns: + - 8.8.8.8 + - 1.1.1.1 + environment: + - LOG_LEVEL=info + - TZ=Etc/UTC + security_opt: + - label=disable + ports: + - 18191:8191 + restart: unless-stopped + +#@ if cli + cli: + container_name: "${COMPOSE_PROJECT_NAME:-helm}-cli" + extra_hosts: + - "host.docker.internal:host-gateway" + image: ghcr.io/piratebird/helm:latest + dns: + - 8.8.8.8 + - 1.1.1.1 + stdin_open: true + tty: true + env_file: + - "@HELM_STATE@/.env.docker" + environment: + - HELM_CONFIG_DIR=/config/helm + security_opt: + - label=disable + volumes: + - "@HELM_CONFIG@:/config/helm" +#@ if source + - "${HOST_PWD:-.}/src:/app/src" +#@ end + - "${HOST_PWD:-.}/docker-compose.yml:/app/docker-compose.yml" + - "@ENGINE_SOCKET@:/var/run/docker.sock" + profiles: + - cli + +#@ end +#@ if vpn + gluetun: + container_name: "${COMPOSE_PROJECT_NAME:-helm}-gluetun" + image: qmcgaw/gluetun:latest + deploy: + resources: + limits: + cpus: "0.25" + memory: 128M + labels: + - "com.docker.compose.project=${COMPOSE_PROJECT_NAME:-helm}" + - "com.docker.compose.service=gluetun" + - "com.docker.compose.oneoff=False" + cap_add: + - NET_ADMIN + devices: + - /dev/net/tun:/dev/net/tun + env_file: + - "@HELM_STATE@/.env.docker" + volumes: + - "@HELM_STATE@/gluetun:/gluetun" + ports: + - 18080:18080 + - 6881:6881 + - 6881:6881/udp + restart: unless-stopped + +#@ end + qbittorrent: + container_name: "${COMPOSE_PROJECT_NAME:-helm}-qbittorrent" + image: lscr.io/linuxserver/qbittorrent:latest + deploy: + resources: + limits: + cpus: "0.50" + memory: 256M + labels: + - "com.docker.compose.project=${COMPOSE_PROJECT_NAME:-helm}" + - "com.docker.compose.service=qbittorrent" + - "com.docker.compose.oneoff=False" +#@ if vpn + network_mode: "service:gluetun" + depends_on: + - gluetun +#@ end +#@ if novpn + dns: + - 8.8.8.8 + - 1.1.1.1 +#@ end + environment: + - PUID=1000 + - PGID=1000 + - TZ=Etc/UTC + - WEBUI_PORT=18080 + security_opt: + - label=disable + volumes: + - "@HELM_STATE@/qbittorrent:/config" + - "@HELM_DL@:/downloads" +#@ if novpn + ports: + - 18080:18080 + - 6881:6881 + - 6881:6881/udp +#@ end + restart: unless-stopped diff --git a/src/helm/core/init_env.py b/src/helm/core/init_env.py index 0eed37d..6ba1935 100644 --- a/src/helm/core/init_env.py +++ b/src/helm/core/init_env.py @@ -2,148 +2,23 @@ import subprocess import time +from helm.core import compose from helm.core.config_manager import get_config_dir, get_dl_dir, get_state_dir -DOCKER_COMPOSE_BASE = """ -services: - jackett: - container_name: "{project_name}-jackett" - image: lscr.io/linuxserver/jackett:latest - deploy: - resources: - limits: - cpus: "0.50" - memory: 256M - labels: - - "com.docker.compose.project={project_name}" - - "com.docker.compose.service=jackett" - - "com.docker.compose.oneoff=False" - dns: - - 8.8.8.8 - - 1.1.1.1 - environment: - - PUID=1000 - - PGID=1000 - - TZ=Etc/UTC - security_opt: - - label=disable - volumes: - - "{state_dir}/jackett:/config" - - "{dl_dir}:/downloads" - ports: - - 19117:9117 - restart: unless-stopped - - flaresolverr: - container_name: "{project_name}-flaresolverr" - image: ghcr.io/flaresolverr/flaresolverr:latest - deploy: - resources: - limits: - cpus: "0.50" - memory: 512M - labels: - - "com.docker.compose.project={project_name}" - - "com.docker.compose.service=flaresolverr" - - "com.docker.compose.oneoff=False" - dns: - - 8.8.8.8 - - 1.1.1.1 - environment: - - LOG_LEVEL=info - - TZ=Etc/UTC - security_opt: - - label=disable - ports: - - 18191:8191 - restart: unless-stopped -""" -QBITTORRENT_BASE = """ - qbittorrent: - container_name: "{project_name}-qbittorrent" - image: lscr.io/linuxserver/qbittorrent:latest - deploy: - resources: - limits: - cpus: "0.50" - memory: 256M - labels: - - "com.docker.compose.project={project_name}" - - "com.docker.compose.service=qbittorrent" - - "com.docker.compose.oneoff=False" - {network_settings} - environment: - - PUID=1000 - - PGID=1000 - - TZ=Etc/UTC - - WEBUI_PORT=18080 - security_opt: - - label=disable - volumes: - - "{state_dir}/qbittorrent:/config" - - "{dl_dir}:/downloads" - {depends_on} - {ports} - restart: unless-stopped -""" +def build_compose(state_dir, dl_dir, config_dir, use_vpn): + """Render the shared compose template without the setup.sh-only cli service.""" + blocks = {"jackett", "prowlarr", "vpn" if use_vpn else "novpn"} + values = {"HELM_STATE": state_dir, "HELM_DL": dl_dir, "HELM_CONFIG": config_dir, "ENGINE_SOCKET": ""} + return compose.render(blocks, values) -GLUETUN_BASE = """ - gluetun: - container_name: "{project_name}-gluetun" - image: qmcgaw/gluetun:latest - deploy: - resources: - limits: - cpus: "0.25" - memory: 128M - labels: - - "com.docker.compose.project={project_name}" - - "com.docker.compose.service=gluetun" - - "com.docker.compose.oneoff=False" - cap_add: - - NET_ADMIN - devices: - - /dev/net/tun:/dev/net/tun - env_file: - - "{state_dir}/.env.docker" - volumes: - - "{state_dir}/gluetun:/gluetun" - ports: - - 18080:8080 - - 6881:6881 - - 6881:6881/udp - restart: unless-stopped -""" -PROWLARR_BASE = """ - prowlarr: - container_name: "{project_name}-prowlarr" - image: lscr.io/linuxserver/prowlarr:latest - deploy: - resources: - limits: - cpus: "0.50" - memory: 256M - labels: - - "com.docker.compose.project={project_name}" - - "com.docker.compose.service=prowlarr" - - "com.docker.compose.oneoff=False" - dns: - - 8.8.8.8 - - 1.1.1.1 - environment: - - PUID=1000 - - PGID=1000 - - TZ=Etc/UTC - security_opt: - - label=disable - volumes: - - "{state_dir}/prowlarr:/config" - ports: - - 19696:9696 - restart: unless-stopped -""" +def write_private(path, text): + """Write a file only the user can read; .env.docker holds passwords.""" + descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) + with os.fdopen(descriptor, "w") as handle: + handle.write(text) + os.chmod(path, 0o600) def bootstrap_env(): @@ -195,27 +70,7 @@ def bootstrap_env(): ovpn_pass = input("Enter OpenVPN Password (leave blank if using token): ").strip() vpn_extra = f"OPENVPN_USER={ovpn_user}\nOPENVPN_PASSWORD={ovpn_pass}" - compose_yaml = DOCKER_COMPOSE_BASE.format(project_name=project_name, state_dir=state_dir, dl_dir=dl_dir) - compose_yaml += PROWLARR_BASE.format(project_name=project_name, state_dir=state_dir) - - if use_vpn == "y": - compose_yaml += GLUETUN_BASE.format(project_name=project_name, state_dir=state_dir) - qb_network = 'network_mode: "service:gluetun"' - qb_depends = "depends_on:\n - gluetun" - qb_ports = "" - else: - qb_network = "" - qb_depends = "" - qb_ports = "ports:\n - 18080:18080\n - 6881:6881\n - 6881:6881/udp" - - compose_yaml += QBITTORRENT_BASE.format( - project_name=project_name, - state_dir=state_dir, - dl_dir=dl_dir, - network_settings=qb_network, - depends_on=qb_depends, - ports=qb_ports, - ) + compose_yaml = build_compose(state_dir, dl_dir, config_dir, use_vpn == "y") compose_path = os.path.join(state_dir, "docker-compose.yml") with open(compose_path, "w") as f: @@ -226,7 +81,7 @@ def bootstrap_env(): JACKETT_API_KEY=placeholder PROWLARR_URL=http://prowlarr:9696 PROWLARR_API_KEY=placeholder -QB_WEBUI=http://qbittorrent:18080 +QB_WEBUI=http://{"gluetun" if use_vpn == "y" else "qbittorrent"}:18080 QB_USERNAME=admin QB_PASSWORD=adminadmin COMPOSE_PROJECT_NAME={project_name} @@ -239,8 +94,7 @@ def bootstrap_env(): VPN_TYPE={vpn_type} {vpn_extra} """ - with open(os.path.join(state_dir, ".env.docker"), "w") as f: - f.write(env_docker_content) + write_private(os.path.join(state_dir, ".env.docker"), env_docker_content) print("\nPre-seeding qBittorrent configuration...") qb_conf = """[Preferences] @@ -278,8 +132,7 @@ def bootstrap_env(): if jackett_api: env_docker_content = env_docker_content.replace("JACKETT_API_KEY=placeholder", f"JACKETT_API_KEY={jackett_api}") - with open(os.path.join(state_dir, ".env.docker"), "w") as f: - f.write(env_docker_content) + write_private(os.path.join(state_dir, ".env.docker"), env_docker_content) print("[+] Successfully grabbed Jackett API Key.") prowlarr_api = "" @@ -298,8 +151,7 @@ def bootstrap_env(): env_docker_content = env_docker_content.replace( "PROWLARR_API_KEY=placeholder", f"PROWLARR_API_KEY={prowlarr_api}" ) - with open(os.path.join(state_dir, ".env.docker"), "w") as f: - f.write(env_docker_content) + write_private(os.path.join(state_dir, ".env.docker"), env_docker_content) print("[+] Successfully grabbed Prowlarr API Key.") print("\n[INFO] Auto-configuring default Prowlarr indexers...") diff --git a/tests/test_setup.sh b/tests/test_setup.sh deleted file mode 100644 index cd78de0..0000000 --- a/tests/test_setup.sh +++ /dev/null @@ -1,4 +0,0 @@ -#!/bin/bash -export COMPOSE_PROJECT_NAME=helm -export DOCKER_CMD=docker -export COMPOSE_CMD="docker compose" diff --git a/tests/test_setup_script.py b/tests/test_setup_script.py new file mode 100644 index 0000000..569a545 --- /dev/null +++ b/tests/test_setup_script.py @@ -0,0 +1,465 @@ +"""Run the real setup.sh against fake docker, podman and systemctl binaries.""" + +import itertools +import os +import shutil +import stat +import subprocess +from pathlib import Path + +import pytest +import yaml + +from helm.core import compose, init_env + +ROOT = Path(__file__).resolve().parents[1] +SETUP = ROOT / "setup.sh" +REAL_DOCKER = shutil.which("docker") +BASH = shutil.which("bash") + +pytestmark = pytest.mark.skipif(BASH is None, reason="bash is required") + +FAKE_ENGINE = r"""#!/usr/bin/env bash +name=$(basename "$0") +printf '%s %s\n' "$name" "$*" >> "$FAKE_LOG" +case "$1" in + compose) exit 0 ;; + info) + if [ "$2" == "--format" ]; then echo "/run/fake/podman.sock"; fi + exit 0 ;; + ps) + if [ "$2" == "--format" ]; then + [ -n "$FAKE_EXTERNAL" ] && echo "$FAKE_EXTERNAL" + exit 0 + fi + filter="$4" + echo "id-${filter##*-}" + exit 0 ;; + inspect) echo "${FAKE_STATE:-running}"; exit 0 ;; + port) echo "9117/tcp -> 0.0.0.0:29117"; exit 0 ;; + exec) + container="$2" + if [ "$3" == "cat" ] && [ "$4" == "/config/Jackett/ServerConfig.json" ]; then + printf '{\n "APIKey": "jkey-%s",\n "FlareSolverrUrl": ""\n}\n' "$container" + elif [ "$3" == "cat" ] && [ "$4" == "/config/config.xml" ]; then + printf '\n pkey-%s\n\n' "$container" + fi + exit 0 ;; + *) exit 0 ;; +esac +""" + + +def make_bin(directory, name, body): + path = directory / name + path.write_text(body) + path.chmod(path.stat().st_mode | stat.S_IEXEC) + + +@pytest.fixture +def box(tmp_path): + bin_dir = tmp_path / "bin" + bin_dir.mkdir() + for name in ("docker", "podman"): + make_bin(bin_dir, name, FAKE_ENGINE) + make_bin(bin_dir, "systemctl", '#!/bin/sh\necho "systemctl $*" >> "$FAKE_LOG"\n') + make_bin(bin_dir, "sudo", '#!/bin/sh\necho "sudo $*" >> "$FAKE_LOG"\nexit 97\n') + work = tmp_path / "work dir" + work.mkdir() + home = tmp_path / "home" + home.mkdir() + env = { + "PATH": f"{bin_dir}:{os.environ['PATH']}", + "HOME": str(home), + "FAKE_LOG": str(tmp_path / "calls.log"), + "FAKE_EXTERNAL": "", + "NO_COLOR": "1", + "HELM_SETUP_POLL": "0", + "HELM_SETUP_KEY_POLL": "0", + "HELM_SETUP_KEY_TRIES": "2", + } + + class Box: + pass + + b = Box() + b.tmp, b.work, b.home, b.env, b.log = tmp_path, work, home, env, Path(env["FAKE_LOG"]) + b.state = tmp_path / "state dir" + b.config = tmp_path / "config" + b.dl = tmp_path / "dl" + + def run(*args, script=SETUP, stdin="", extra=None, dirs=True): + argv = [BASH, str(script)] + if dirs: + argv += ["--state-dir", str(b.state), "--config-dir", str(b.config), "--downloads-dir", str(b.dl)] + argv += list(args) + return subprocess.run( + argv, + cwd=b.work, + env={**b.env, **(extra or {})}, + input=stdin, + capture_output=True, + text=True, + timeout=60, + ) + + def calls(): + return b.log.read_text().splitlines() if b.log.exists() else [] + + def env_file(): + lines = (b.state / ".env.docker").read_text().splitlines() + return dict(line.split("=", 1) for line in lines if "=" in line and not line.startswith("#")) + + b.run, b.calls, b.env_file = run, calls, env_file + return b + + +def values(box, socket="/var/run/docker.sock"): + return { + "HELM_STATE": str(box.state), + "HELM_DL": str(box.dl), + "HELM_CONFIG": str(box.config), + "ENGINE_SOCKET": socket, + } + + +def bash_render(blocks, vals, template=compose.TEMPLATE): + return subprocess.run( + [ + BASH, + "-c", + 'source "$1"; render_compose "$2" "$3"', + "render", + str(SETUP), + str(template), + " ".join(sorted(blocks)), + ], + env={**os.environ, **vals}, + capture_output=True, + text=True, + check=False, + ) + + +def all_block_sets(): + for cli, jackett, prowlarr, source, vpn in itertools.product([0, 1], repeat=5): + blocks = {"vpn" if vpn else "novpn"} + for on, name in ((cli, "cli"), (jackett, "jackett"), (prowlarr, "prowlarr"), (source, "source")): + if on: + blocks.add(name) + yield blocks + + +# ---------------------------------------------------------------- template + + +def test_bash_and_python_render_identically_for_every_block_set(): + vals = { + "HELM_STATE": "/tmp/state & co/x\\y", + "HELM_DL": "/dl with space", + "HELM_CONFIG": "/cfg/@HELM_DL@", + "ENGINE_SOCKET": "/run/user/1000/podman/podman.sock", + } + for blocks in all_block_sets(): + result = bash_render(blocks, vals) + assert result.returncode == 0, result.stderr + assert result.stdout == compose.render(blocks, vals), sorted(blocks) + + +def test_rendered_files_have_the_expected_services(): + vals = {"HELM_STATE": "/s", "HELM_DL": "/d", "HELM_CONFIG": "/c", "ENGINE_SOCKET": "/sock"} + for blocks in all_block_sets(): + data = yaml.safe_load(compose.render(blocks, vals)) + services = set(data["services"]) + expected = {"flaresolverr", "qbittorrent"} | (blocks & {"jackett", "prowlarr", "cli"}) + if "vpn" in blocks: + expected.add("gluetun") + assert services == expected + qb = data["services"]["qbittorrent"] + if "vpn" in blocks: + assert qb["network_mode"] == "service:gluetun" and "ports" not in qb + assert "18080:18080" in data["services"]["gluetun"]["ports"] + else: + assert "network_mode" not in qb and "18080:18080" in qb["ports"] + if "cli" in blocks: + cli = data["services"]["cli"] + assert "/c:/config/helm" in cli["volumes"] + assert "HELM_CONFIG_DIR=/config/helm" in cli["environment"] + assert "/sock:/var/run/docker.sock" in cli["volumes"] + assert any(v.endswith("/src:/app/src") for v in cli["volumes"]) == ("source" in blocks) + assert "#@" not in compose.render(blocks, vals) + + +@pytest.mark.parametrize( + "template", + ["a\n#@ end\n", "a\n#@ if cli\nb\n"], +) +def test_unbalanced_templates_fail_in_both_renderers(tmp_path, template): + path = tmp_path / "bad.yml" + path.write_text(template) + vals = {name: "/x" for name in compose.PLACEHOLDERS} + with pytest.raises(compose.TemplateError): + compose.render({"novpn"}, vals, template=template) + assert bash_render({"novpn"}, vals, template=path).returncode != 0 + + +def test_nested_blocks_need_every_parent_on(): + template = "#@ if cli\nA\n#@ if source\nB\n#@ end\nC\n#@ end\n#@ comment\nD\n" + vals = {name: "" for name in compose.PLACEHOLDERS} + assert compose.render({"novpn", "source"}, vals, template=template) == "D\n" + assert compose.render({"novpn", "cli"}, vals, template=template) == "A\nC\nD\n" + assert compose.render({"novpn", "cli", "source"}, vals, template=template) == "A\nB\nC\nD\n" + + +@pytest.mark.parametrize( + "blocks, vals, message", + [ + ({"novpn", "bogus"}, {}, "Unknown"), + ({"vpn", "novpn"}, {}, "exactly one"), + (set(), {}, "exactly one"), + ({"novpn"}, {"HELM_STATE": "/s"}, "Missing"), + ({"novpn"}, {"HELM_STATE": 'a"b', "HELM_DL": "", "HELM_CONFIG": "", "ENGINE_SOCKET": ""}, "quotes"), + ], +) +def test_render_rejects_bad_input(blocks, vals, message): + with pytest.raises(compose.TemplateError, match=message): + compose.render(blocks, vals) + + +@pytest.mark.skipif(REAL_DOCKER is None, reason="docker compose is not installed") +def test_docker_compose_accepts_every_rendered_file(tmp_path): + (tmp_path / ".env.docker").write_text("A=1\n") + vals = {"HELM_STATE": str(tmp_path), "HELM_DL": "/d", "HELM_CONFIG": "/c", "ENGINE_SOCKET": "/sock"} + for index, blocks in enumerate(all_block_sets()): + path = tmp_path / f"compose-{index}.yml" + path.write_text(compose.render(blocks, vals)) + result = subprocess.run( + [REAL_DOCKER, "compose", "-f", str(path), "--profile", "cli", "config", "-q"], + capture_output=True, + text=True, + check=False, + ) + if result.returncode and "is not a docker command" in result.stderr: + pytest.skip("the compose plugin is not installed") + assert result.returncode == 0, (sorted(blocks), result.stderr) + + +def test_template_ships_as_package_data(): + pyproject = (ROOT / "pyproject.toml").read_text() + assert '"helm.core" = ["compose.template.yml"]' in pyproject + assert compose.TEMPLATE.is_file() + + +def test_init_env_uses_the_template_without_the_cli_service(tmp_path): + text = init_env.build_compose("/s", "/d", "/c", use_vpn=True) + assert text == compose.render( + {"jackett", "prowlarr", "vpn"}, {"HELM_STATE": "/s", "HELM_DL": "/d", "HELM_CONFIG": "/c", "ENGINE_SOCKET": ""} + ) + assert "cli" not in yaml.safe_load(text)["services"] + + path = tmp_path / ".env.docker" + path.write_text("old") + path.chmod(0o644) + init_env.write_private(str(path), "QB_PASSWORD=x\n") + assert path.read_text() == "QB_PASSWORD=x\n" + assert stat.S_IMODE(path.stat().st_mode) == 0o600 + + +# ---------------------------------------------------------------- setup.sh runs + + +def test_help_and_unknown_option(box): + result = box.run("--help", dirs=False) + assert result.returncode == 0 and "--skip-prompts" in result.stdout + result = box.run("--bogus", dirs=False) + assert result.returncode == 1 and "Unknown option: --bogus" in result.stderr + result = box.run("--state-dir", dirs=False) + assert result.returncode == 1 and "needs a path" in result.stderr + result = box.run("--skip-prompts", "--state-dir", '/tmp/a"b', dirs=False) + assert result.returncode == 1 and "cannot contain quotes" in result.stderr + assert box.calls() == [] + + +def test_skip_prompts_with_docker(box): + result = box.run("--skip-prompts") + assert result.returncode == 0, result.stderr + + compose_file = box.work / "docker-compose.yml" + assert compose_file.read_text() == compose.render({"cli", "jackett", "prowlarr", "novpn"}, values(box)) + + env = box.env_file() + assert env["JACKETT_API_KEY"] == "jkey-id-jackett" + assert env["PROWLARR_API_KEY"] == "pkey-id-prowlarr" + assert env["JACKETT_URL"] == "http://jackett:9117" + assert env["QB_WEBUI"] == "http://qbittorrent:18080" + assert env["INDEXER_MANAGER"] == "both" + assert env["COMPOSE_PROJECT_NAME"] == "helm" + assert env["HOST_PWD"] == str(box.work) + assert stat.S_IMODE((box.state / ".env.docker").stat().st_mode) == 0o600 + + calls = box.calls() + file_arg = f"-f {compose_file}" + assert f"docker compose {file_arg} --profile cli pull cli" in calls + assert f"docker compose {file_arg} up -d --remove-orphans qbittorrent flaresolverr jackett prowlarr" in calls + assert f"docker compose {file_arg} restart jackett" in calls + assert f"docker compose {file_arg} stop" in calls + assert not any(call.startswith("sudo") for call in calls) + + assert (box.state / "jackett/Jackett/Indexers/yts.json").is_file() + assert "WebUI\\Username=admin" in (box.state / "qbittorrent/qBittorrent/qBittorrent.conf").read_text() + assert not (box.config / "config.json").exists() + + for path in (box.config, box.state, box.dl): + assert f"{path}/" in result.stdout + assert "./helm-torrent.sh" in result.stdout + + +def test_docker_launcher_adds_oneshot_once(box): + assert box.run("--skip-prompts").returncode == 0 + launcher = box.work / "helm-torrent.sh" + assert subprocess.run([BASH, "-n", str(launcher)], check=False).returncode == 0 + if shutil.which("shellcheck"): + result = subprocess.run(["shellcheck", str(launcher)], capture_output=True, text=True, check=False) + assert result.returncode == 0, result.stdout + + base = f"docker compose -f {box.work}/docker-compose.yml --profile cli run --rm cli" + for args, expected in ( + (["search", "two words"], "--oneshot search two words"), + (["-o", "x"], "-o x"), + (["--oneshot"], "--oneshot"), + (["--output", "x"], "--oneshot --output x"), + ): + box.log.write_text("") + result = subprocess.run([str(launcher), *args], env=box.env, capture_output=True, text=True, check=False) + assert result.returncode == 0, result.stderr + assert box.calls() == [f"{base} {expected}"] + + +def test_existing_qbittorrent_config_is_kept(box): + conf = box.state / "qbittorrent/qBittorrent/qBittorrent.conf" + conf.parent.mkdir(parents=True) + conf.write_text("[Preferences]\nmine=1\n") + assert box.run("--skip-prompts").returncode == 0 + assert conf.read_text() == "[Preferences]\nmine=1\n" + + +def test_external_jackett_is_detected_before_files_are_written(box): + result = box.run(stdin="1\n1\n2\n\n\n", extra={"FAKE_EXTERNAL": "my-jackett"}) + assert result.returncode == 0, result.stderr + assert "Found existing external jackett container: my-jackett" in result.stdout + + data = yaml.safe_load((box.work / "docker-compose.yml").read_text()) + assert "jackett" not in data["services"] + env = box.env_file() + assert env["JACKETT_URL"] == "http://host.docker.internal:29117" + assert env["JACKETT_API_KEY"] == "jkey-my-jackett" + assert env["INDEXER_MANAGER"] == "jackett" + assert not any("restart jackett" in call for call in box.calls()) + assert not (box.state / "jackett/Jackett/Indexers").exists() + + +def test_interactive_vpn_and_systemd_prompt(box): + answers = "1\n1\n1\nmy-key\nbob\ny\nmullvad\nwireguard\nwg-secret\nn\n" + result = box.run(stdin=answers) + assert result.returncode == 0, result.stderr + + expected = compose.render({"cli", "jackett", "vpn"}, values(box)) + assert (box.work / "docker-compose.yml").read_text() == expected + env = box.env_file() + assert env["QB_WEBUI"] == "http://gluetun:18080" + assert env["QB_USERNAME"] == "bob" + assert env["JACKETT_API_KEY"] == "my-key" + assert env["VPN_SERVICE_PROVIDER"] == "mullvad" + assert env["VPN_TYPE"] == "wireguard" + assert env["WIREGUARD_PRIVATE_KEY"] == "wg-secret" + assert "PROWLARR_URL" in env and env["PROWLARR_API_KEY"] == "placeholder" + assert "left running 24/7" in result.stdout + assert not (box.work / "helm-torrent.sh").exists() + assert not any(call.endswith(" stop") for call in box.calls()) + + +def test_empty_vpn_key_disables_the_vpn(box): + result = box.run(stdin="1\n1\n2\n\n\ny\nmullvad\nwireguard\n\n") + assert result.returncode == 0, result.stderr + assert "WireGuard key cannot be empty" in result.stderr + assert "gluetun" not in yaml.safe_load((box.work / "docker-compose.yml").read_text())["services"] + + +def test_crashed_container_stops_setup(box): + result = box.run("--skip-prompts", extra={"FAKE_STATE": "exited"}) + assert result.returncode == 1 + assert "crashed immediately" in result.stderr and "docker logs helm-jackett" in result.stderr + + +def test_podman_uses_the_real_image_and_socket(box): + result = box.run(stdin="2\n2\n2\n\n\n\n") + assert result.returncode == 0, result.stderr + + sock = "/run/fake/podman.sock" + compose_file = box.work / "docker-compose.yml" + assert compose_file.read_text() == compose.render({"cli", "prowlarr", "novpn"}, values(box, sock)) + env = box.env_file() + assert env["PROWLARR_API_KEY"] == "pkey-id-prowlarr" and env["INDEXER_MANAGER"] == "prowlarr" + + calls = box.calls() + assert "systemctl --user enable --now podman.socket" in calls + assert f"podman compose -f {compose_file} --profile cli pull cli" in calls + up = [call for call in calls if call.startswith("podman run") and " up -d " in call] + assert len(up) == 1 and compose.TEMPLATE.name not in up[0] + assert "ghcr.io/piratebird/helm:latest docker compose -f /app/docker-compose.yml up -d" in up[0] + assert "mini-helm" not in " ".join(calls) + assert any(call.startswith("podman stop helm-prowlarr helm-jackett") for call in calls) + + launcher = box.work / "helm-torrent.sh" + box.log.write_text("") + result = subprocess.run([str(launcher), "search", "x"], env=box.env, capture_output=True, text=True, check=False) + assert result.returncode == 0, result.stderr + (call,) = box.calls() + assert call.startswith("podman run -it --rm --entrypoint= --security-opt label=disable --network helm_default") + assert f"-v {box.config}:/config/helm -e HELM_CONFIG_DIR=/config/helm" in call + assert f"{sock}:/var/run/docker.sock" in call + assert call.endswith("ghcr.io/piratebird/helm:latest python -m helm.cli --oneshot search x") + + +def test_project_name_comes_from_the_environment(box): + result = box.run("--skip-prompts", extra={"COMPOSE_PROJECT_NAME": "media"}) + assert result.returncode == 0, result.stderr + assert box.env_file()["COMPOSE_PROJECT_NAME"] == "media" + assert box.env_file()["JACKETT_API_KEY"] == "jkey-id-jackett" + assert "export COMPOSE_PROJECT_NAME=media" in (box.work / "helm-torrent.sh").read_text() + + +def test_curl_one_liner_downloads_the_template(box): + script = box.tmp / "fd" / "setup.sh" + script.parent.mkdir() + shutil.copy(SETUP, script) + if shutil.which("curl") is None: + pytest.skip("curl is not installed") + result = box.run("--skip-prompts", script=script, extra={"HELM_RAW_BASE": f"file://{ROOT}"}) + assert result.returncode == 0, result.stderr + assert "Downloading the compose template" in result.stdout + expected = compose.render({"cli", "jackett", "prowlarr", "novpn"}, values(box)) + assert (box.work / "docker-compose.yml").read_text() == expected + + result = box.run("--skip-prompts", script=script, extra={"HELM_RAW_BASE": f"file://{box.tmp}/missing"}) + assert result.returncode == 1 and "Could not download" in result.stderr + + +def test_checkout_mounts_local_source(box): + (box.work / "src" / "helm").mkdir(parents=True) + assert box.run("--skip-prompts").returncode == 0 + expected = compose.render({"cli", "jackett", "prowlarr", "source", "novpn"}, values(box)) + assert (box.work / "docker-compose.yml").read_text() == expected + + +def test_missing_docker_prints_install_help(box, tmp_path): + empty = tmp_path / "empty-bin" + empty.mkdir() + for tool in ("uname", "dirname", "awk", "sed", "grep", "head", "mkdir", "cat"): + found = shutil.which(tool) + if found: + os.symlink(found, empty / tool) + result = box.run("--skip-prompts", extra={"PATH": str(empty)}) + assert result.returncode == 1 + assert "Docker is not installed" in result.stderr + assert "Unix Shenanigans Reminder" in result.stdout From 00e06b68e493ceab3bfb0c440c4b685e881e7d41 Mon Sep 17 00:00:00 2001 From: Piratebird <141295458+Piratebird@users.noreply.github.com> Date: Mon, 2 Nov 2026 23:57:45 +0200 Subject: [PATCH 07/18] :shipit: chore(setup): move stack setup into helm-torrent init - Keep only host work in setup.sh: arguments, engine checks and installs, native installs, systemd - Run helm-torrent init in the Helm image with the socket and directories mounted at the same paths - Run the init container as the user on rootful Docker so generated files stay theirs - Move the compose file, .env.docker, API keys and launcher into tested Python - Add --engine, --indexers, --run-mode, --workdir, --socket, --project, --mount-source and --skip-prompts to init - Let init run on a broken config file, and fall back to a local image when the pull fails - Replace init_env.py; Prowlarr still seeds its default indexers on first search --- CHANGELOG.md | 1 + README.md | 6 +- setup.sh | 684 +++++++---------------------------- src/helm/cli.py | 23 +- src/helm/core/init_env.py | 203 ----------- src/helm/core/stack_setup.py | 593 ++++++++++++++++++++++++++++++ tests/test_setup_script.py | 506 +++++++++++++++++--------- 7 files changed, 1089 insertions(+), 927 deletions(-) delete mode 100644 src/helm/core/init_env.py create mode 100644 src/helm/core/stack_setup.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 707cf75..a7b8eac 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ All notable changes to this project will be documented in this file. ## [Unreleased] ### Changed +- Split setup: `setup.sh` now only checks the host (engine, native installs, systemd) and runs `helm-torrent init` inside the Helm image as the current user. `init` writes the compose file, `.env.docker`, API keys and the launcher, and takes `--engine`, `--indexers`, `--run-mode`, `--workdir`, `--socket`, `--project`, `--mount-source` and `--skip-prompts`; it asks for whatever is missing and runs even when the config file is broken. It no longer activates Jackett and Prowlarr indexers through their APIs: Jackett gets the seeded indexer files, and Prowlarr seeds its defaults on first search. If the image cannot be pulled, setup uses a local copy. - Rewrite `setup.sh` as small functions with a short `main`, tested against fake Docker, Podman and systemctl binaries. `setup.sh` and `helm-torrent init` now render one compose template, `src/helm/core/compose.template.yml`, and `docker-compose.yml.example` is removed. Setup no longer edits `config.json`; the indexer choice goes into `.env.docker` as `INDEXER_MANAGER`. The container name prefix is `helm` (or `COMPOSE_PROJECT_NAME`) everywhere, instead of the directory name in `.env.docker`. An existing `qBittorrent.conf` is kept instead of overwritten. - Use the theme everywhere the UI, wizard, one-shot mode and Lite downloader print colour, and show the banner when the UI starts. Colours are now off when output is piped or `NO_COLOR` is set. Red messages that used the terminal's basic red now use the theme's error colour. - Use one set of service defaults: Jackett `19117`, Prowlarr `19696`, qBittorrent `18080`. Set `[services]` for a native Jackett on `9117`. diff --git a/README.md b/README.md index 61b1dbd..e8b30cb 100644 --- a/README.md +++ b/README.md @@ -127,7 +127,7 @@ The script will guide you through: 2. Choosing your run mode (Ephemeral vs Permanent) 3. Setting up a VPN (optional) -It writes `docker-compose.yml` in the current directory from `src/helm/core/compose.template.yml`, the same template `helm-torrent init` uses. From a checkout the local template is used; the curl one-liner downloads it from the same branch (set `HELM_REF` to pick another). It also writes `state/.env.docker` with mode `0600`, including `INDEXER_MANAGER` for the containers, and mounts your config directory into the CLI container, so `config.toml` and `config.jsonc` work there too. Set `COMPOSE_PROJECT_NAME` before running it to change the container name prefix (default `helm`). +`setup.sh` only handles the host: the container engine, native installs and the optional systemd unit. It then pulls `ghcr.io/piratebird/helm` and runs `helm-torrent init` inside it, with the engine socket and your directories mounted at the same paths, so the files it writes are owned by you. `init` writes `docker-compose.yml` in the current directory from `src/helm/core/compose.template.yml`, writes `state/.env.docker` with mode `0600` (including `INDEXER_MANAGER` for the containers), reads the Jackett and Prowlarr API keys, and creates the `helm-torrent.sh` launcher in one-shot mode. The CLI container gets your config directory, so `config.toml` and `config.jsonc` work there too. Set `COMPOSE_PROJECT_NAME` to change the container name prefix (default `helm`), `HELM_IMAGE` to use another image, or `HELM_SETUP_RUNNER=helm-torrent` to run `init` on the host instead of in the image.
@@ -231,8 +231,8 @@ Run `helm-torrent` for the interactive CLI. Use subcommands for scripted searche # Search without containers and emit JSON (no download) helm-torrent search "Ubuntu" --type software --lite --json -# Configure the full container environment -helm-torrent init +# Configure the full container environment (asks for anything not given) +helm-torrent init --engine docker --indexers both --run-mode oneshot # Start the configured stack, select a download, then stop it helm-torrent search "Ubuntu" --type software --oneshot diff --git a/setup.sh b/setup.sh index b61347d..8c3417e 100755 --- a/setup.sh +++ b/setup.sh @@ -1,28 +1,24 @@ #!/usr/bin/env bash # -# Helm setup: installs the services Helm uses (Jackett and/or Prowlarr, -# qBittorrent, FlareSolverr) with Docker, Podman, or natively. +# Helm setup: checks the host, then sets up the services Helm uses (Jackett +# and/or Prowlarr, qBittorrent, FlareSolverr) with Docker or Podman, or +# installs them natively. # # ./setup.sh [--skip-prompts] [--config-dir DIR] [--state-dir DIR] [--downloads-dir DIR] # bash <(curl -sL https://raw.githubusercontent.com/Piratebird/helm/main/setup.sh) # -# The compose file comes from src/helm/core/compose.template.yml, the same -# template `helm-torrent init` uses. From a checkout the local copy is used; -# otherwise it is downloaded from the same branch. +# This script only handles the host: arguments, the container engine, native +# installs and the optional systemd unit. Everything else (compose file, +# .env.docker, API keys, launcher) is `helm-torrent init`, which runs inside +# the Helm image with your directories mounted at the same paths. +# Set HELM_SETUP_RUNNER (for example "helm-torrent") to run init on the host instead. set -eo pipefail -HELM_IMAGE="ghcr.io/piratebird/helm:latest" -HELM_RAW_BASE="${HELM_RAW_BASE:-https://raw.githubusercontent.com/Piratebird/helm/${HELM_REF:-main}}" -TEMPLATE_PATH_IN_REPO="src/helm/core/compose.template.yml" -SETUP_TIMEOUT="${HELM_SETUP_TIMEOUT:-45}" -SETUP_POLL="${HELM_SETUP_POLL:-5}" -KEY_TRIES="${HELM_SETUP_KEY_TRIES:-15}" -KEY_POLL="${HELM_SETUP_KEY_POLL:-3}" +HELM_IMAGE="${HELM_IMAGE:-ghcr.io/piratebird/helm:latest}" # Answers, set by ask() through printf -v. -install_mode="" indexer_mode="" run_mode="" qb_user="" use_vpn="" -vpn_provider="" vpn_type="" vpn_extra="" +install_mode="" indexer_mode="" run_mode="" # ---------------------------------------------------------------- output @@ -54,15 +50,6 @@ ask() { printf -v "$__var" '%s' "$__reply" } -ask_secret() { - local __var=$1 __prompt=$2 __reply="" - if [ -z "$SKIP_PROMPTS" ]; then - read -r -s -p "$__prompt" __reply || true - say "" - fi - printf -v "$__var" '%s' "$__reply" -} - is_yes() { [[ "$1" =~ ^[Yy]$ ]]; } # ---------------------------------------------------------------- arguments @@ -153,10 +140,8 @@ choose_install() { wants_jackett() { [ "$indexer_mode" == "1" ] || [ "$indexer_mode" == "3" ]; } wants_prowlarr() { [ "$indexer_mode" == "2" ] || [ "$indexer_mode" == "3" ]; } -local_jackett() { wants_jackett && [ -z "$EXTERNAL_JACKETT_API" ]; } -local_prowlarr() { wants_prowlarr && [ -z "$EXTERNAL_PROWLARR_API" ]; } -choose_stack() { +choose_run_mode() { if [ -z "$SKIP_PROMPTS" ]; then say "How would you like to run Helm?" say " [1] Permanent (Always-On) - Containers run 24/7 in the background." @@ -164,100 +149,51 @@ choose_stack() { fi ask run_mode "Choose your mode (1/2, default 2): " 2 [ -n "$SKIP_PROMPTS" ] || say "" - - JACKETT_API="" PROWLARR_API="" - if wants_jackett && [ -z "$EXTERNAL_JACKETT_API" ]; then - ask JACKETT_API "Enter Jackett API Key (press Enter to auto-extract later): " "" - fi - if wants_prowlarr && [ -z "$EXTERNAL_PROWLARR_API" ]; then - ask PROWLARR_API "Enter Prowlarr API Key (press Enter to auto-extract later): " "" - fi - ask qb_user "Enter qBittorrent Username (default: admin): " admin - [ -n "$SKIP_PROMPTS" ] || say "" - ask use_vpn "Do you want to route qBittorrent through a VPN using Gluetun? (y/N): " n - if is_yes "$use_vpn"; then - choose_vpn - fi -} - -choose_vpn() { - vpn_provider="" vpn_type="" vpn_extra="" - say "" - say "--- VPN Configuration ---" - ask vpn_provider "Enter VPN Provider (e.g. nordvpn, custom): " "" - if [ "$vpn_provider" = "protonvpn" ]; then - warn "ProtonVPN blocks P2P/torrent traffic on its Free tier, so qBittorrent would stay stalled." - warn "Make sure you are using a paid ProtonVPN account." - fi - ask vpn_type "Enter VPN Type (wireguard/openvpn) (default: wireguard): " wireguard - - if [ -z "$vpn_provider" ]; then - error "VPN Provider cannot be empty. Disabling VPN." - use_vpn="n" - elif [ "$vpn_type" = "wireguard" ]; then - local wg_key - ask wg_key "Enter WireGuard Private Key: " "" - if [ -z "$wg_key" ]; then - error "WireGuard key cannot be empty. Disabling VPN." - use_vpn="n" - else - vpn_extra="WIREGUARD_PRIVATE_KEY=$wg_key" - fi - elif [ "$vpn_type" = "openvpn" ]; then - if [ "$vpn_provider" != "custom" ]; then - local ovpn_user ovpn_pass - ask ovpn_user "Enter OpenVPN Username (or token): " "" - ask_secret ovpn_pass "Enter OpenVPN Password (leave blank if using token): " - if [ -z "$ovpn_user" ]; then - error "OpenVPN user cannot be empty. Disabling VPN." - use_vpn="n" - else - vpn_extra="OPENVPN_USER=$ovpn_user"$'\n'"OPENVPN_PASSWORD=$ovpn_pass" - fi - else - info "For 'custom' OpenVPN, place custom.conf (and auth.conf if needed) in $HELM_STATE/gluetun" - fi - fi } # ---------------------------------------------------------------- engines -# NAME and ID come from /etc/os-release. -# shellcheck disable=SC2153 -print_docker_install_help() { - if [ "$(uname)" == "Darwin" ]; then - say "To install Docker on macOS, run:" - say " brew install --cask docker" - elif [ -f /etc/os-release ]; then - # shellcheck disable=SC1091 - . /etc/os-release - case "$ID" in - ubuntu|debian|pop|linuxmint) - say "To install Docker on $NAME, run:" - say " sudo apt update && sudo apt install -y docker.io docker-compose" ;; - fedora|centos|rhel|almalinux|rocky) - say "To install Docker on $NAME, run:" - say " sudo dnf install -y docker docker-compose" ;; - arch|manjaro) - say "To install Docker on $NAME, run:" - say " sudo pacman -S docker docker-compose" ;; - *) - say "Please install Docker manually for your OS ($NAME)." ;; - esac - fi - say "" - say "--- Unix Shenanigans Reminder ---" - say "1. Start the Docker daemon: sudo systemctl enable --now docker" - say "2. Add user to docker group: sudo usermod -aG docker \$USER" - say "3. Apply group changes: newgrp docker (or just log out and log back in)" - say "" +# Print the package manager command for this OS: apt, dnf, pacman, brew or nothing. +package_manager() { + if [ "$(uname)" == "Darwin" ]; then echo brew; return; fi + [ -f /etc/os-release ] || return 0 + # shellcheck disable=SC1091 + . /etc/os-release + case "$ID" in + ubuntu|debian|pop|linuxmint) echo apt ;; + fedora|centos|rhel|almalinux|rocky) echo dnf ;; + arch|manjaro) echo pacman ;; + esac +} + +# install_command MANAGER PACKAGE... prints the install command for MANAGER. +install_command() { + local manager=$1; shift + case "$manager" in + apt) echo "sudo apt update && sudo apt install -y $*" ;; + dnf) echo "sudo dnf install -y $*" ;; + pacman) echo "sudo pacman -S --noconfirm $*" ;; + brew) echo "brew install $*" ;; + esac } check_docker() { if ! command -v docker &> /dev/null; then error "Docker is not installed or not in your PATH." + local manager docker_pkg="docker" + manager=$(package_manager) + if [ "$manager" == "apt" ]; then docker_pkg="docker.io"; fi + say "" + case "$manager" in + brew) say "To install Docker on macOS, run:"; say " brew install --cask docker" ;; + "") say "Please install Docker manually for your OS." ;; + *) say "To install Docker, run:"; say " $(install_command "$manager" "$docker_pkg" docker-compose)" ;; + esac say "" - print_docker_install_help + say "--- Unix Shenanigans Reminder ---" + say "1. Start the Docker daemon: sudo systemctl enable --now docker" + say "2. Add user to docker group: sudo usermod -aG docker \$USER" + say "3. Apply group changes: newgrp docker (or just log out and log back in)" exit 1 fi docker compose version &> /dev/null \ @@ -269,34 +205,20 @@ check_docker() { ENGINE_SOCKET="/var/run/docker.sock" } -# shellcheck disable=SC2153 -install_podman() { - say "Installing Podman..." - if [ "$(uname)" == "Darwin" ]; then - command -v brew &> /dev/null || die "Please install Homebrew (https://brew.sh/) first, then re-run this script." - brew install podman podman-desktop podman-compose - elif [ -f /etc/os-release ]; then - # shellcheck disable=SC1091 - . /etc/os-release - case "$ID" in - ubuntu|debian|pop|linuxmint) sudo apt update && sudo apt install -y podman podman-compose ;; - fedora|centos|rhel|almalinux|rocky) sudo dnf install -y podman podman-compose ;; - arch|manjaro) sudo pacman -S --noconfirm podman podman-compose ;; - *) die "Automatic installation is not supported for your OS ($NAME). See https://podman.io/docs/installation" ;; - esac - else - die "Cannot determine OS. Please install Podman manually." - fi - command -v podman &> /dev/null || die "Automatic installation failed. Please install Podman manually." -} - check_podman() { if ! command -v podman &> /dev/null; then warn "Podman is not installed." - local auto_install + local auto_install manager ask auto_install "Would you like this script to install Podman automatically? [Y/n]: " Y is_yes "$auto_install" || die "Please install Podman manually and re-run the script." - install_podman + manager=$(package_manager) + [ -n "$manager" ] || die "Automatic installation is not supported here. See https://podman.io/docs/installation" + if [ "$manager" == "brew" ] && ! command -v brew &> /dev/null; then + die "Please install Homebrew (https://brew.sh/) first, then re-run this script." + fi + say "Installing Podman..." + eval "$(install_command "$manager" podman podman-compose)" + command -v podman &> /dev/null || die "Automatic installation failed. Please install Podman manually." fi if podman compose version &> /dev/null; then COMPOSE_CMD=(podman compose) @@ -341,43 +263,36 @@ native_dependencies() { ask auto_install "Would you like this script to install them automatically? [Y/n]: " Y is_yes "$auto_install" || die "Please install them manually and re-run the script." + local manager + manager=$(package_manager) say "Installing native dependencies..." - [ -f /etc/os-release ] || return 0 - # shellcheck disable=SC1091 - . /etc/os-release - case "$ID" in - ubuntu|debian|pop|linuxmint) - sudo apt update && sudo apt install -y qbittorrent-nox wget tar curl libicu-dev libssl-dev zlib1g ;; - fedora|centos|rhel|almalinux|rocky) - sudo dnf install -y qbittorrent-nox wget tar curl icu openssl zlib ;; - arch|manjaro) - sudo pacman -S --noconfirm qbittorrent-nox wget tar curl icu openssl zlib ;; - *) - say "Please ensure you have qbittorrent-nox and .NET dependencies (ICU, OpenSSL, zlib) installed manually." ;; + case "$manager" in + apt) eval "$(install_command apt qbittorrent-nox wget tar curl libicu-dev libssl-dev zlib1g)" ;; + dnf|pacman) eval "$(install_command "$manager" qbittorrent-nox wget tar curl icu openssl zlib)" ;; + *) say "Please ensure you have qbittorrent-nox and .NET dependencies (ICU, OpenSSL, zlib) installed manually." ;; esac } -native_jackett() { - if [ -d "/opt/Jackett" ]; then - say "Jackett already installed at /opt/Jackett" - return 0 +# native_download NAME URL extracts a release tarball to /opt/NAME; it fails when already there. +native_download() { + if [ -d "/opt/$1" ]; then + say "$1 already installed at /opt/$1" + return 1 fi - say "Installing Jackett to /opt/Jackett..." - wget -O - -o /dev/null https://github.com/Jackett/Jackett/releases/latest/download/Jackett.Binaries.LinuxAMDx64.tar.gz \ - | sudo tar -xz -C /opt - sudo chown "$(whoami)":"$(id -g)" -R "/opt/Jackett" + say "Installing $1 to /opt/$1..." + wget -O - -o /dev/null "$2" | sudo tar -xz -C /opt + sudo chown "$(whoami)":"$(id -g)" -R "/opt/$1" +} + +native_jackett() { + native_download Jackett https://github.com/Jackett/Jackett/releases/latest/download/Jackett.Binaries.LinuxAMDx64.tar.gz \ + || return 0 (cd /opt/Jackett && sudo ./install_service_systemd.sh) } native_prowlarr() { - if [ -d "/opt/Prowlarr" ]; then - say "Prowlarr already installed at /opt/Prowlarr" - return 0 - fi - say "Installing Prowlarr to /opt/Prowlarr..." - wget -O - -o /dev/null https://github.com/Prowlarr/Prowlarr/releases/latest/download/Prowlarr.master.linux-core-x64.tar.gz \ - | sudo tar -xz -C /opt - sudo chown "$(whoami)":"$(id -g)" -R "/opt/Prowlarr" + native_download Prowlarr https://github.com/Prowlarr/Prowlarr/releases/latest/download/Prowlarr.master.linux-core-x64.tar.gz \ + || return 0 sudo tee /etc/systemd/system/prowlarr.service > /dev/null <\([^<]*\)
.*:\1:p' | head -n 1 - else - sed -n 's/.*"APIKey"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' | head -n 1 - fi -} - -read_api_key() { - local name=$1 container=$2 file="/config/Jackett/ServerConfig.json" - if [ "$name" == "prowlarr" ]; then file="/config/config.xml"; fi - "$ENGINE" exec "$container" cat "$file" 2>/dev/null | parse_api_key "$name" || true -} - -detect_existing_indexer() { - local name=$1 container port key - container=$("$ENGINE" ps --format '{{.Names}}' 2>/dev/null | grep -i "$name" | grep -vx "$PROJECT-$name" | head -n 1 || true) - [ -n "$container" ] || return 0 - say "[+] Found existing external $name container: $container" - port=$("$ENGINE" port "$container" 2>/dev/null | head -n 1 | awk -F':' '{print $NF}' || true) - if [ -z "$port" ]; then - if [ "$name" == "prowlarr" ]; then port="9696"; else port="9117"; fi - fi - key=$(read_api_key "$name" "$container") - [ -n "$key" ] || return 0 - say "[+] Successfully extracted API key from external $name!" - if [ "$name" == "prowlarr" ]; then - EXTERNAL_PROWLARR_PORT="$port" EXTERNAL_PROWLARR_API="$key" - else - EXTERNAL_JACKETT_PORT="$port" EXTERNAL_JACKETT_API="$key" - fi -} - -detect_existing_indexers() { - EXTERNAL_JACKETT_PORT="" EXTERNAL_JACKETT_API="" - EXTERNAL_PROWLARR_PORT="" EXTERNAL_PROWLARR_API="" - if wants_jackett; then detect_existing_indexer jackett; fi - if wants_prowlarr; then detect_existing_indexer prowlarr; fi -} - -# ---------------------------------------------------------------- files - -# render_compose TEMPLATE "BLOCK ..." prints the compose file. -# The rules match helm.core.compose.render; tests compare the two. -render_compose() { - R_STATE="$HELM_STATE" R_DL="$HELM_DL" R_CONFIG="$HELM_CONFIG" R_SOCKET="$ENGINE_SOCKET" \ - awk -v blocks=" $2 " ' - function put(s, key, val, i, out) { - out = "" - while ((i = index(s, key)) > 0) { - out = out substr(s, 1, i - 1) val - s = substr(s, i + length(key)) - } - return out s - } - { line = $0; marker = line; sub(/^[ \t]+/, "", marker) } - marker ~ /^#@ if / { split(marker, f, " "); depth++; on[depth] = index(blocks, " " f[3] " ") > 0; next } - marker ~ /^#@ end/ { if (depth == 0) { bad = 1; exit } depth--; next } - marker ~ /^#@/ { next } - { - for (i = 1; i <= depth; i++) if (!on[i]) next - line = put(line, "@HELM_STATE@", ENVIRON["R_STATE"]) - line = put(line, "@HELM_DL@", ENVIRON["R_DL"]) - line = put(line, "@HELM_CONFIG@", ENVIRON["R_CONFIG"]) - line = put(line, "@ENGINE_SOCKET@", ENVIRON["R_SOCKET"]) - print line - } - END { if (bad || depth != 0) { print "unbalanced #@ blocks in compose template" > "/dev/stderr"; exit 1 } } - ' "$1" -} - -compose_blocks() { - local blocks="cli" - if local_jackett; then blocks="$blocks jackett"; fi - if local_prowlarr; then blocks="$blocks prowlarr"; fi - if [ -d "$PWD/src/helm" ]; then blocks="$blocks source"; fi - if is_yes "$use_vpn"; then blocks="$blocks vpn"; else blocks="$blocks novpn"; fi - printf '%s\n' "$blocks" -} - -fetch_template() { - local local_file="$SCRIPT_DIR/$TEMPLATE_PATH_IN_REPO" url="$HELM_RAW_BASE/$TEMPLATE_PATH_IN_REPO" - if [ -n "${HELM_COMPOSE_TEMPLATE:-}" ]; then - TEMPLATE_FILE="$HELM_COMPOSE_TEMPLATE" - elif [ -f "$local_file" ]; then - TEMPLATE_FILE="$local_file" - else - TEMPLATE_FILE=$(mktemp) - TEMPLATE_TEMP=1 - info "Downloading the compose template from $url" - if command -v curl &> /dev/null; then - curl -fsSL "$url" -o "$TEMPLATE_FILE" || die "Could not download $url" - else - wget -q -O "$TEMPLATE_FILE" "$url" || die "Could not download $url" - fi - fi - [ -s "$TEMPLATE_FILE" ] || die "Compose template is missing or empty: $TEMPLATE_FILE" -} - -write_compose() { - fetch_template - local blocks - blocks=$(compose_blocks) - if is_yes "$use_vpn"; then say "Configuring with VPN (Gluetun)..."; else say "Configuring WITHOUT VPN..."; fi - render_compose "$TEMPLATE_FILE" "$blocks" > "$COMPOSE_FILE.tmp" - mv "$COMPOSE_FILE.tmp" "$COMPOSE_FILE" - if [ -n "${TEMPLATE_TEMP:-}" ]; then rm -f "$TEMPLATE_FILE"; fi -} - -# set_env_value KEY VALUE replaces KEY's line in .env.docker. -set_env_value() { - local file="$ENV_FILE" - ( - umask 077 - K="$1" V="$2" awk 'index($0, ENVIRON["K"] "=") == 1 { print ENVIRON["K"] "=" ENVIRON["V"]; next } { print }' \ - "$file" > "$file.tmp" - ) - mv "$file.tmp" "$file" -} - -write_env_file() { - local jackett_url="http://jackett:9117" prowlarr_url="http://prowlarr:9696" qb_host="qbittorrent" - if [ -n "$EXTERNAL_JACKETT_PORT" ]; then jackett_url="http://host.docker.internal:$EXTERNAL_JACKETT_PORT"; fi - if [ -n "$EXTERNAL_PROWLARR_PORT" ]; then prowlarr_url="http://host.docker.internal:$EXTERNAL_PROWLARR_PORT"; fi - # With a VPN, qBittorrent shares gluetun's network, so only that name resolves. - if is_yes "$use_vpn"; then qb_host="gluetun"; fi - ( - umask 077 - { - say "# --- Helm Container Isolated Configuration ---" - say "JACKETT_URL=$jackett_url" - say "JACKETT_API_KEY=${EXTERNAL_JACKETT_API:-${JACKETT_API:-placeholder}}" - say "PROWLARR_URL=$prowlarr_url" - say "PROWLARR_API_KEY=${EXTERNAL_PROWLARR_API:-${PROWLARR_API:-placeholder}}" - say "QB_WEBUI=http://$qb_host:18080" - say "QB_USERNAME=$qb_user" - say "QB_PASSWORD=adminadmin" - say "INDEXER_MANAGER=$INDEXER_MANAGER" - say "COMPOSE_PROJECT_NAME=$PROJECT" - say "HOST_PWD=$PWD" - if is_yes "$use_vpn"; then - say "" - say "# --- VPN (Gluetun) Configuration ---" - say "VPN_SERVICE_PROVIDER=$vpn_provider" - say "VPN_TYPE=$vpn_type" - if [ -n "$vpn_extra" ]; then say "$vpn_extra"; fi - fi - } > "$ENV_FILE" - ) - chmod 600 "$ENV_FILE" -} - -seed_jackett() { - local dir="$HELM_STATE/jackett/Jackett/Indexers" name site - say "Seeding default Jackett indexers..." - mkdir -p "$dir" - for name in 1337x yts nyaasi thepiratebay; do - case $name in - 1337x) site="https://1337x.to/" ;; - yts) site="https://yts.mx/" ;; - nyaasi) site="https://nyaa.si/" ;; - thepiratebay) site="https://thepiratebay.org/" ;; - esac - printf '[{"id": "sitelink","type": "inputstring","name": "Site Link","value": "%s"}]\n' "$site" > "$dir/$name.json" - done -} - -seed_qbittorrent() { - local dir="$HELM_STATE/qbittorrent/qBittorrent" - mkdir -p "$dir" - if [ -f "$dir/qBittorrent.conf" ]; then - info "Keeping the existing qBittorrent configuration." - return 0 - fi - say "Pre-seeding qBittorrent configuration..." - cat > "$dir/qBittorrent.conf" <<'EOF' -[Preferences] -WebUI\Password_PBKDF2="@ByteArray(ARQ77eY1NUZaQsuDHbIMCA==:0WMRkYTUWVT9wVvdDtHAjU9b3b7uB8NR1Gur2hmQCvCDpm39Q+PsIfSYvgkvpe7L5yL8YQv8EaV7t8mP308QWg==)" -WebUI\Username=admin -WebUI\AuthSubnetWhitelist=10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16 -WebUI\AuthSubnetWhitelistEnabled=true -WebUI\LocalHostAuth=false -EOF -} - -# ---------------------------------------------------------------- stack - -compose() { "${COMPOSE_CMD[@]}" -f "$COMPOSE_FILE" "$@"; } - -# Podman runs compose from inside the Helm image, against the Podman socket. -run_compose() { - if [ "$ENGINE" == "podman" ]; then - podman run --rm --entrypoint="" --security-opt label=disable \ - -v "$PWD:/app" -v "$ENGINE_SOCKET:/var/run/docker.sock" --env-file "$ENV_FILE" \ - "$HELM_IMAGE" docker compose -f /app/docker-compose.yml "$@" 2> >(grep -v "rootless netns" >&2) - else - compose "$@" - fi -} - -container_id() { - "$ENGINE" ps -q -f "name=$PROJECT-$1" 2>/dev/null | head -n 1 || true -} - -start_services() { - local services=(qbittorrent flaresolverr) - if local_jackett; then services+=(jackett); fi - if local_prowlarr; then services+=(prowlarr); fi - say "" - say "Starting containers in the background to initialize configurations..." - run_compose up -d --remove-orphans "${services[@]}" -} - -wait_for_services() { - local name="qbittorrent" elapsed=0 container state - if local_jackett; then name="jackett"; elif local_prowlarr; then name="prowlarr"; fi - info "Waiting for services to initialize..." - while [ "$elapsed" -lt "$SETUP_TIMEOUT" ]; do - container=$(container_id "$name") - if [ -n "$container" ]; then - state=$("$ENGINE" inspect -f '{{.State.Status}}' "$container" 2>/dev/null || true) - if [ "$state" == "running" ]; then - ok "Services are initialized and running!" - return 0 - fi - if [ "$state" == "exited" ]; then - die "Container $name started but crashed immediately. Run '$ENGINE logs $PROJECT-$name' to see why." - fi - fi - sleep "$SETUP_POLL" - elapsed=$((elapsed + SETUP_POLL)) - if [ "$SETUP_POLL" -eq 0 ]; then elapsed=$((elapsed + 1)); fi - say "Polling status... ($elapsed/$SETUP_TIMEOUT seconds)" - done - warn "Timeout reached while waiting for configurations." - warn "Services may be experiencing slow startup times or are hanging." -} - -# grab_api_key NAME prints the key read from Helm's own container, or nothing. -grab_api_key() { - local name=$1 container key try - for ((try = 0; try < KEY_TRIES; try++)); do - container=$(container_id "$name") - if [ -n "$container" ]; then - key=$(read_api_key "$name" "$container") - if [ -n "$key" ]; then - printf '%s\n' "$key" - return 0 - fi - fi - sleep "$KEY_POLL" - done -} - -configure_api_keys() { - if wants_jackett; then - JACKETT_API="${EXTERNAL_JACKETT_API:-$JACKETT_API}" - if [ -z "$JACKETT_API" ]; then - JACKETT_API=$(grab_api_key jackett) - if [ -n "$JACKETT_API" ]; then - say "[+] Successfully grabbed Jackett API Key." - "$ENGINE" exec "$(container_id jackett)" \ - sed -i 's|"FlareSolverrUrl":.*|"FlareSolverrUrl": "http://flaresolverr:8191",|' \ - /config/Jackett/ServerConfig.json 2>/dev/null || true - run_compose restart jackett - say "[+] Jackett configured with FlareSolverr." - else - warn "Could not find APIKey in Jackett configuration. Using placeholder." - JACKETT_API="your_jackett_api_key_here" - fi - fi - set_env_value JACKETT_API_KEY "$JACKETT_API" - fi - if wants_prowlarr; then - PROWLARR_API="${EXTERNAL_PROWLARR_API:-$PROWLARR_API}" - if [ -z "$PROWLARR_API" ]; then - PROWLARR_API=$(grab_api_key prowlarr) - if [ -n "$PROWLARR_API" ]; then - say "[+] Successfully grabbed Prowlarr API Key." - else - warn "Could not find APIKey in Prowlarr configuration. Using placeholder." - PROWLARR_API="your_prowlarr_api_key_here" - fi - fi - set_env_value PROWLARR_API_KEY "$PROWLARR_API" - fi -} - -# ---------------------------------------------------------------- finish - quote_words() { local word out="" for word in "$@"; do out="$out $(printf '%q' "$word")"; done printf '%s' "${out# }" } -write_launcher() { - local file="$PWD/helm-torrent.sh" run - if [ "$ENGINE" == "podman" ]; then - run=$(quote_words podman run -it --rm --entrypoint= --security-opt label=disable \ - --network "${PROJECT}_default" -v "$PWD:/app" -v "$HELM_CONFIG:/config/helm" \ - -e HELM_CONFIG_DIR=/config/helm -v "$ENGINE_SOCKET:/var/run/docker.sock" \ - --env-file "$ENV_FILE" "$HELM_IMAGE" python -m helm.cli) - run="$run \"\$@\" 2> >(grep -v \"rootless netns\" >&2)" - else - run="exec $(quote_words "${COMPOSE_CMD[@]}" -f "$COMPOSE_FILE" --profile cli run --rm cli) \"\$@\"" - fi - say "Generating helm-torrent launcher script..." - cat > "$file" < /dev/null </dev/null || true - else - run_compose stop || true +# Arguments that let the init container use the engine socket and write +# files on the host as the user running setup. +container_user_args() { + USER_ARGS=() + if [ "$ENGINE" == "podman" ] || [ "$(uname)" == "Darwin" ]; then + return 0 # rootless Podman and Docker Desktop already map root to you fi + if "$ENGINE" info --format '{{.SecurityOptions}}' 2>/dev/null | grep -q rootless; then + return 0 + fi + local socket_group + socket_group=$(stat -c %g "$ENGINE_SOCKET" 2>/dev/null || echo 0) + USER_ARGS=(--user "$(id -u):$(id -g)" --group-add "$socket_group") } -finish() { - if [ "$run_mode" == "2" ]; then - stop_stack - write_launcher - say "Containers stopped. Helm will spin them up automatically when you trigger a download." - say "" - say "To start using the app in its isolated CLI container, run:" - say " ./helm-torrent.sh" - else - say "Containers are left running 24/7 in the background." - say "" - local install_systemd - ask install_systemd "Do you want to create a systemd service to start Helm automatically on boot? (y/N): " n - if is_yes "$install_systemd"; then install_systemd_unit; fi - say "" - say "To start using the app in its isolated CLI container, run:" - say " $(quote_words "${COMPOSE_CMD[@]}" --profile cli run --rm cli)" +run_init() { + init_arguments + if [ -n "${HELM_SETUP_RUNNER:-}" ]; then + # shellcheck disable=SC2086 # the runner may be several words + HELM_DOCKER_CMD="${HELM_DOCKER_CMD:-$ENGINE}" $HELM_SETUP_RUNNER "${INIT_ARGS[@]}" + return fi - rule + say "Pulling the latest helm image..." + if ! "$ENGINE" pull "$HELM_IMAGE"; then + "$ENGINE" image inspect "$HELM_IMAGE" > /dev/null 2>&1 \ + || die "Could not pull $HELM_IMAGE, and no local copy exists." + warn "Could not pull $HELM_IMAGE; using the local copy." + fi + container_user_args + local tty=() dir + if [ -t 0 ] && [ -t 1 ]; then tty=(-t); fi + local mounts=(-v "$ENGINE_SOCKET:/var/run/docker.sock") + for dir in "$PWD" "$HELM_STATE" "$HELM_CONFIG" "$HELM_DL"; do + mounts+=(-v "$dir:$dir") + done + "$ENGINE" run --rm -i "${tty[@]}" --security-opt label=disable \ + "${mounts[@]}" "${USER_ARGS[@]}" -w "$PWD" -e HOME=/tmp -e HELM_DOCKER_CMD=docker \ + -e COMPOSE_PROJECT_NAME="$PROJECT" -e NO_COLOR="${NO_COLOR:-}" \ + "$HELM_IMAGE" "${INIT_ARGS[@]}" } +# ---------------------------------------------------------------- main + main() { setup_colours - SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" 2>/dev/null && pwd || true)" PROJECT="${COMPOSE_PROJECT_NAME:-helm}" export COMPOSE_PROJECT_NAME="$PROJECT" default_paths @@ -847,27 +439,17 @@ main() { *) check_docker ;; esac ok "Container engine and compose are functional." + mkdir -p "$HELM_STATE" "$HELM_CONFIG" "$HELM_DL" - COMPOSE_FILE="$PWD/docker-compose.yml" - ENV_FILE="$HELM_STATE/.env.docker" - mkdir -p "$HELM_STATE/jackett" "$HELM_STATE/prowlarr" "$HELM_STATE/qbittorrent" "$HELM_STATE/gluetun" "$HELM_DL" "$HELM_CONFIG" - - detect_existing_indexers - say "" - choose_stack - write_compose - write_env_file - - say "Pulling the latest helm image..." - compose --profile cli pull cli - - if local_jackett; then seed_jackett; fi - seed_qbittorrent - start_services - wait_for_services - configure_api_keys - print_summary - finish + choose_run_mode + # Ask everything bash needs before init starts: init reads the rest of stdin. + local install_systemd="n" + if [ "$run_mode" == "1" ]; then + ask install_systemd "Do you want to create a systemd service to start Helm automatically on boot? (y/N): " n + fi + run_init + if is_yes "$install_systemd"; then install_systemd_unit; fi + rule } if [[ "${BASH_SOURCE[0]}" == "$0" ]]; then diff --git a/src/helm/cli.py b/src/helm/cli.py index a65a196..4b5a0ab 100644 --- a/src/helm/cli.py +++ b/src/helm/cli.py @@ -151,9 +151,12 @@ def build_parser(): # UI # Init - subparsers.add_parser( - "init", help="Bootstrap and initialize the container environment natively", parents=[base_parser] + init_parser = subparsers.add_parser( + "init", help="Set up the container stack: compose file, .env.docker, API keys", parents=[base_parser] ) + from helm.core.stack_setup import add_arguments as add_init_arguments + + add_init_arguments(init_parser) # UI subparsers.add_parser( @@ -261,9 +264,10 @@ def _parse_args(parser): if getattr(args, "dl_dir", None): os.environ["HELM_DL_DIR"] = os.path.abspath(args.dl_dir) - # Config commands must run on a broken file and report true origins, so they - # neither load settings early nor export the worker count. - if args.command != "config": + # Config commands must run on a broken file and report true origins, and setup + # must not stop on one, so they neither load settings early nor export the + # worker count. + if args.command not in ("config", "init"): requested = getattr(args, "lite_workers", None) if requested is None and "HELM_LITE_WORKERS" not in os.environ: requested = load_settings().get("search.lite_workers") @@ -480,13 +484,14 @@ def run(): return if args.command == "init": - from helm.core.init_env import bootstrap_env + from helm.core.stack_setup import main as setup_main try: - bootstrap_env() - except (KeyboardInterrupt, EOFError): + status = setup_main(args) + except KeyboardInterrupt: print(f"\n{T.ACCENT}later bozo!{T.RST}") - raise SystemExit(0) from None + status = 130 + raise SystemExit(status) from None if args.command in ("paths", "logs", "bug-report"): _run_utility(args.command) diff --git a/src/helm/core/init_env.py b/src/helm/core/init_env.py deleted file mode 100644 index 6ba1935..0000000 --- a/src/helm/core/init_env.py +++ /dev/null @@ -1,203 +0,0 @@ -import os -import subprocess -import time - -from helm.core import compose -from helm.core.config_manager import get_config_dir, get_dl_dir, get_state_dir - - -def build_compose(state_dir, dl_dir, config_dir, use_vpn): - """Render the shared compose template without the setup.sh-only cli service.""" - blocks = {"jackett", "prowlarr", "vpn" if use_vpn else "novpn"} - values = {"HELM_STATE": state_dir, "HELM_DL": dl_dir, "HELM_CONFIG": config_dir, "ENGINE_SOCKET": ""} - return compose.render(blocks, values) - - -def write_private(path, text): - """Write a file only the user can read; .env.docker holds passwords.""" - descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) - with os.fdopen(descriptor, "w") as handle: - handle.write(text) - os.chmod(path, 0o600) - - -def bootstrap_env(): - print("===========================================") - print(" Helm Zero-Touch Bootstrapping ") - print("===========================================") - - config_dir = get_config_dir() - state_dir = get_state_dir() - dl_dir = get_dl_dir() - project_name = "helm" - - print(f"Using paths:\n Config: {config_dir}\n State: {state_dir}\n Downloads: {dl_dir}\n") - - os.makedirs(os.path.join(state_dir, "jackett", "Jackett", "Indexers"), exist_ok=True) - os.makedirs(os.path.join(state_dir, "qbittorrent", "qBittorrent"), exist_ok=True) - os.makedirs(os.path.join(state_dir, "gluetun"), exist_ok=True) - os.makedirs(dl_dir, exist_ok=True) - os.makedirs(config_dir, exist_ok=True) - - config_file = os.path.join(config_dir, "config.json") - if not os.path.exists(config_file): - with open(config_file, "w") as f: - f.write("{}") - - install_mode = input( - "How would you like to install the required services?\n [1] Docker (Recommended)\n [2] Podman\nChoose (1/2, default 1): " - ).strip() - docker_cmd = "podman" if install_mode == "2" else "docker" - compose_cmd = [docker_cmd, "compose"] - - run_mode = input( - "\nHow would you like to run Helm?\n [1] Permanent (Always-On)\n [2] Ephemeral (One-Shot)\nChoose (1/2, default 2): " - ).strip() - - use_vpn = input("\nDo you want to route qBittorrent through a VPN using Gluetun? (y/N): ").strip().lower() - - vpn_provider = "" - vpn_type = "" - vpn_extra = "" - if use_vpn == "y": - vpn_provider = input("Enter VPN Provider (e.g. nordvpn, custom): ").strip() - vpn_type = input("Enter VPN Type (wireguard/openvpn) (default: wireguard): ").strip() or "wireguard" - if vpn_type == "wireguard": - wg_key = input("Enter WireGuard Private Key: ").strip() - vpn_extra = f"WIREGUARD_PRIVATE_KEY={wg_key}" - elif vpn_type == "openvpn" and vpn_provider != "custom": - ovpn_user = input("Enter OpenVPN Username (or token): ").strip() - ovpn_pass = input("Enter OpenVPN Password (leave blank if using token): ").strip() - vpn_extra = f"OPENVPN_USER={ovpn_user}\nOPENVPN_PASSWORD={ovpn_pass}" - - compose_yaml = build_compose(state_dir, dl_dir, config_dir, use_vpn == "y") - - compose_path = os.path.join(state_dir, "docker-compose.yml") - with open(compose_path, "w") as f: - f.write(compose_yaml) - - env_docker_content = f"""# --- Helm Container Isolated Configuration --- -JACKETT_URL=http://jackett:9117 -JACKETT_API_KEY=placeholder -PROWLARR_URL=http://prowlarr:9696 -PROWLARR_API_KEY=placeholder -QB_WEBUI=http://{"gluetun" if use_vpn == "y" else "qbittorrent"}:18080 -QB_USERNAME=admin -QB_PASSWORD=adminadmin -COMPOSE_PROJECT_NAME={project_name} -HOST_PWD={os.getcwd()} -""" - if use_vpn == "y": - env_docker_content += f""" -# --- VPN (Gluetun) Configuration --- -VPN_SERVICE_PROVIDER={vpn_provider} -VPN_TYPE={vpn_type} -{vpn_extra} -""" - write_private(os.path.join(state_dir, ".env.docker"), env_docker_content) - - print("\nPre-seeding qBittorrent configuration...") - qb_conf = """[Preferences] -WebUI\\Password_PBKDF2="@ByteArray(ARQ77eY1NUZaQsuDHbIMCA==:0WMRkYTUWVT9wVvdDtHAjU9b3b7uB8NR1Gur2hmQCvCDpm39Q+PsIfSYvgkvpe7L5yL8YQv8EaV7t8mP308QWg==)" -WebUI\\Username=admin -WebUI\\AuthSubnetWhitelist=10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16 -WebUI\\AuthSubnetWhitelistEnabled=true -WebUI\\LocalHostAuth=false -""" - with open(os.path.join(state_dir, "qbittorrent", "qBittorrent", "qBittorrent.conf"), "w") as f: - f.write(qb_conf) - - print("\nStarting containers to initialize Jackett...") - - subprocess.run( - compose_cmd - + ["-f", compose_path, "up", "-d", "--remove-orphans", "jackett", "prowlarr", "qbittorrent", "flaresolverr"], - check=False, - ) - - print("[INFO] Waiting for Jackett to initialize...") - time.sleep(10) - - jackett_api = "" - try: - j_config = os.path.join(state_dir, "jackett", "Jackett", "ServerConfig.json") - if os.path.exists(j_config): - import json - - with open(j_config, "r") as f: - j_data = json.load(f) - jackett_api = j_data.get("APIKey", "") - except Exception: - pass - - if jackett_api: - env_docker_content = env_docker_content.replace("JACKETT_API_KEY=placeholder", f"JACKETT_API_KEY={jackett_api}") - write_private(os.path.join(state_dir, ".env.docker"), env_docker_content) - print("[+] Successfully grabbed Jackett API Key.") - - prowlarr_api = "" - try: - p_config = os.path.join(state_dir, "prowlarr", "config.xml") - if os.path.exists(p_config): - with open(p_config, "r") as f: - for line in f: - if "" in line: - prowlarr_api = line.split("")[1].split("")[0].strip() - break - except Exception: - pass - - if prowlarr_api: - env_docker_content = env_docker_content.replace( - "PROWLARR_API_KEY=placeholder", f"PROWLARR_API_KEY={prowlarr_api}" - ) - write_private(os.path.join(state_dir, ".env.docker"), env_docker_content) - print("[+] Successfully grabbed Prowlarr API Key.") - - print("\n[INFO] Auto-configuring default Prowlarr indexers...") - os.environ["PROWLARR_URL"] = "http://localhost:19696" - os.environ["PROWLARR_API_KEY"] = prowlarr_api - if prowlarr_api: - try: - from helm.core.indexer_manager import ProwlarrManager - - manager = ProwlarrManager() - enabled = manager.seed_default_indexers() - print(f" [+] Activated {enabled} default Prowlarr indexer(s).") - except Exception as e: - print(f"[-] Could not auto-configure Prowlarr indexers: {e}") - - print("\n[INFO] Auto-configuring default Jackett indexers...") - # Override env vars temporarily so JackettManager targets the fresh container - os.environ["JACKETT_URL"] = "http://localhost:19117" - os.environ["JACKETT_API_KEY"] = jackett_api - os.environ["JACKETT_PASSWORD"] = "" - - try: - from helm.core.indexer_manager import JackettManager - - manager = JackettManager() - - # The most reliable and widely used public trackers - DEFAULT_INDEXERS = ["1337x", "yts", "torrentgalaxy", "nyaasi", "eztv"] - all_indexers = manager.get_all_indexers() - - configured_count = 0 - for idx in all_indexers: - if idx["id"] in DEFAULT_INDEXERS and not idx["configured"]: - try: - manager.add_indexer(idx["id"]) - print(f" [+] Activated tracker: {idx['title']}") - configured_count += 1 - except Exception as e: - print(f" [-] Failed to activate {idx['title']}: {e}") - if configured_count == 0: - print(" [+] Default trackers are already active.") - except Exception as e: - print(f"[-] Could not auto-configure indexers: {e}") - - if run_mode != "1": - print("\nTearing down containers for Ephemeral (One-Shot) mode...") - subprocess.run(compose_cmd + ["-f", compose_path, "stop"], check=False) - - print("\nSetup is complete! You can now use helm-torrent.") diff --git a/src/helm/core/stack_setup.py b/src/helm/core/stack_setup.py new file mode 100644 index 0000000..4b184a9 --- /dev/null +++ b/src/helm/core/stack_setup.py @@ -0,0 +1,593 @@ +"""Set up the container stack: compose file, .env.docker, API keys and launcher. + +``setup.sh`` checks the host (engine, native installs, systemd) and then runs +``helm-torrent init`` inside the Helm image with the engine socket and the +user's directories mounted at the same paths, so every path written here is a +host path. ``helm-torrent init`` can also run directly on a host that has the +docker CLI. + +Engine commands always go through the docker CLI (``HELM_DOCKER_CMD``), which +talks to Docker or to Podman's Docker-compatible socket. +""" + +import getpass +import os +import re +import shlex +import shutil +import subprocess +import sys +import time +from dataclasses import dataclass, field +from typing import Dict, List, Optional, Tuple + +from helm.core import compose + +IMAGE = "ghcr.io/piratebird/helm:latest" +SERVICES = ("prowlarr", "jackett", "qbittorrent", "flaresolverr", "gluetun") +JACKETT_SITES = ( + ("1337x", "https://1337x.to/"), + ("yts", "https://yts.mx/"), + ("nyaasi", "https://nyaa.si/"), + ("thepiratebay", "https://thepiratebay.org/"), +) +QBITTORRENT_CONF = """[Preferences] +WebUI\\Password_PBKDF2="@ByteArray(ARQ77eY1NUZaQsuDHbIMCA==:0WMRkYTUWVT9wVvdDtHAjU9b3b7uB8NR1Gur2hmQCvCDpm39Q+PsIfSYvgkvpe7L5yL8YQv8EaV7t8mP308QWg==)" +WebUI\\Username=admin +WebUI\\AuthSubnetWhitelist=10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16 +WebUI\\AuthSubnetWhitelistEnabled=true +WebUI\\LocalHostAuth=false +""" +KEY_FILES = {"jackett": "/config/Jackett/ServerConfig.json", "prowlarr": "/config/config.xml"} +KEY_PATTERNS = { + "jackett": re.compile(r'"APIKey"\s*:\s*"([^"]*)"'), + "prowlarr": re.compile(r"([^<]*)"), +} +DEFAULT_PORTS = {"jackett": "9117", "prowlarr": "9696"} + + +class SetupError(RuntimeError): + pass + + +@dataclass +class Vpn: + provider: str + kind: str + extra: List[str] = field(default_factory=list) + + +@dataclass +class Plan: + engine: str + indexers: str + run_mode: str + state: str + config: str + downloads: str + workdir: str + socket: str + project: str = "helm" + source: bool = False + skip_prompts: bool = False + jackett_api: str = "" + prowlarr_api: str = "" + qb_user: str = "admin" + vpn: Optional[Vpn] = None + external: Dict[str, Tuple[str, str]] = field(default_factory=dict) + + def wants(self, name): + return self.indexers in (name, "both") + + def local(self, name): + return self.wants(name) and name not in self.external + + @property + def compose_file(self): + return os.path.join(self.workdir, "docker-compose.yml") + + @property + def env_file(self): + return os.path.join(self.state, ".env.docker") + + +# ---------------------------------------------------------------- output and prompts + + +def say(text=""): + print(text, flush=True) + + +def info(text): + say(f"[INFO] {text}") + + +def warn(text): + print(f"[WARN] {text}", file=sys.stderr, flush=True) + + +def error(text): + print(f"[ERROR] {text}", file=sys.stderr, flush=True) + + +def ask(plan, prompt, default=""): + if plan.skip_prompts: + return default + try: + reply = input(prompt).strip() + except EOFError: + reply = "" + return reply or default + + +def ask_secret(plan, prompt): + if plan.skip_prompts: + return "" + if not sys.stdin.isatty(): + return ask(plan, prompt) + try: + return getpass.getpass(prompt) + except EOFError: + return "" + + +def is_yes(text): + return text in ("y", "Y") + + +# ---------------------------------------------------------------- engine + + +class Engine: + def __init__(self, command=None, poll=None): + self.command = shlex.split(command or os.environ.get("HELM_DOCKER_CMD", "docker")) + self.poll = float(os.environ.get("HELM_SETUP_POLL", "5") if poll is None else poll) + + def run(self, args, check=False): + return subprocess.run(self.command + list(args), capture_output=True, text=True, check=check) + + def output(self, args): + try: + result = self.run(args) + except OSError: + return "" + return result.stdout if result.returncode == 0 else "" + + def compose(self, plan, args): + """Run compose and let its output through, like a person would see it.""" + result = subprocess.run(self.command + ["compose", "-f", plan.compose_file] + list(args), check=False) + return result.returncode + + def container_id(self, plan, name): + lines = self.output(["ps", "-q", "-f", f"name={plan.project}-{name}"]).split() + return lines[0] if lines else "" + + def api_key(self, name, container): + match = KEY_PATTERNS[name].search(self.output(["exec", container, "cat", KEY_FILES[name]])) + return match.group(1) if match else "" + + +# ---------------------------------------------------------------- steps + + +def detect_existing(plan, engine): + """Find a Jackett or Prowlarr someone else runs, so Helm uses it instead of a second copy.""" + names = engine.output(["ps", "--format", "{{.Names}}"]).split() + for name in ("jackett", "prowlarr"): + if not plan.wants(name): + continue + found = [n for n in names if name in n.lower() and n != f"{plan.project}-{name}"] + if not found: + continue + container = found[0] + say(f"[+] Found existing external {name} container: {container}") + port_lines = engine.output(["port", container]).splitlines() + port = port_lines[0].rsplit(":", 1)[-1].strip() if port_lines else "" + key = engine.api_key(name, container) + if key: + say(f"[+] Successfully extracted API key from external {name}!") + plan.external[name] = (port or DEFAULT_PORTS[name], key) + + +def choose(plan): + if plan.local("jackett"): + plan.jackett_api = ask(plan, "Enter Jackett API Key (press Enter to auto-extract later): ") + if plan.local("prowlarr"): + plan.prowlarr_api = ask(plan, "Enter Prowlarr API Key (press Enter to auto-extract later): ") + plan.qb_user = ask(plan, "Enter qBittorrent Username (default: admin): ", "admin") + if not plan.skip_prompts: + say() + if is_yes(ask(plan, "Do you want to route qBittorrent through a VPN using Gluetun? (y/N): ", "n")): + plan.vpn = choose_vpn(plan) + + +def choose_vpn(plan): + say() + say("--- VPN Configuration ---") + provider = ask(plan, "Enter VPN Provider (e.g. nordvpn, custom): ") + if provider == "protonvpn": + warn("ProtonVPN blocks P2P/torrent traffic on its Free tier, so qBittorrent would stay stalled.") + warn("Make sure you are using a paid ProtonVPN account.") + kind = ask(plan, "Enter VPN Type (wireguard/openvpn) (default: wireguard): ", "wireguard") + if not provider: + error("VPN Provider cannot be empty. Disabling VPN.") + return None + vpn = Vpn(provider, kind) + if kind == "wireguard": + key = ask(plan, "Enter WireGuard Private Key: ") + if not key: + error("WireGuard key cannot be empty. Disabling VPN.") + return None + vpn.extra = [f"WIREGUARD_PRIVATE_KEY={key}"] + elif kind == "openvpn" and provider != "custom": + user = ask(plan, "Enter OpenVPN Username (or token): ") + password = ask_secret(plan, "Enter OpenVPN Password (leave blank if using token): ") + if not user: + error("OpenVPN user cannot be empty. Disabling VPN.") + return None + vpn.extra = [f"OPENVPN_USER={user}", f"OPENVPN_PASSWORD={password}"] + elif kind == "openvpn": + info(f"For 'custom' OpenVPN, place custom.conf (and auth.conf if needed) in {plan.state}/gluetun") + return vpn + + +def write_private(path, text): + """Write a file only the user can read; .env.docker holds passwords.""" + temporary = f"{path}.tmp" + descriptor = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) + with os.fdopen(descriptor, "w") as handle: + handle.write(text) + os.chmod(temporary, 0o600) + os.replace(temporary, path) + + +def compose_blocks(plan): + blocks = {"cli", "vpn" if plan.vpn else "novpn"} + blocks |= {name for name in ("jackett", "prowlarr") if plan.local(name)} + if plan.source: + blocks.add("source") + return blocks + + +def write_compose(plan): + say("Configuring with VPN (Gluetun)..." if plan.vpn else "Configuring WITHOUT VPN...") + values = { + "HELM_STATE": plan.state, + "HELM_DL": plan.downloads, + "HELM_CONFIG": plan.config, + "ENGINE_SOCKET": plan.socket, + } + text = compose.render(compose_blocks(plan), values) + temporary = plan.compose_file + ".tmp" + with open(temporary, "w", encoding="utf-8") as handle: + handle.write(text) + os.replace(temporary, plan.compose_file) + + +def env_values(plan): + def url(name, service): + if name in plan.external: + return f"http://host.docker.internal:{plan.external[name][0]}" + return f"http://{service}:{DEFAULT_PORTS[name]}" + + def key(name, typed): + return plan.external[name][1] if name in plan.external else (typed or "placeholder") + + # With a VPN, qBittorrent shares gluetun's network, so only that name resolves. + values = [ + ("JACKETT_URL", url("jackett", "jackett")), + ("JACKETT_API_KEY", key("jackett", plan.jackett_api)), + ("PROWLARR_URL", url("prowlarr", "prowlarr")), + ("PROWLARR_API_KEY", key("prowlarr", plan.prowlarr_api)), + ("QB_WEBUI", f"http://{'gluetun' if plan.vpn else 'qbittorrent'}:18080"), + ("QB_USERNAME", plan.qb_user), + ("QB_PASSWORD", "adminadmin"), + ("INDEXER_MANAGER", plan.indexers), + ("COMPOSE_PROJECT_NAME", plan.project), + ("HOST_PWD", plan.workdir), + ] + return values + + +def write_env(plan): + lines = ["# --- Helm Container Isolated Configuration ---"] + lines += [f"{name}={value}" for name, value in env_values(plan)] + if plan.vpn: + lines += ["", "# --- VPN (Gluetun) Configuration ---"] + lines += [f"VPN_SERVICE_PROVIDER={plan.vpn.provider}", f"VPN_TYPE={plan.vpn.kind}"] + plan.vpn.extra + write_private(plan.env_file, "\n".join(lines) + "\n") + + +def set_env_value(plan, name, value): + with open(plan.env_file, encoding="utf-8") as handle: + lines = handle.read().splitlines() + lines = [f"{name}={value}" if line.startswith(f"{name}=") else line for line in lines] + write_private(plan.env_file, "\n".join(lines) + "\n") + + +def seed_jackett(plan): + say("Seeding default Jackett indexers...") + directory = os.path.join(plan.state, "jackett", "Jackett", "Indexers") + os.makedirs(directory, exist_ok=True) + for name, site in JACKETT_SITES: + with open(os.path.join(directory, f"{name}.json"), "w", encoding="utf-8") as handle: + handle.write(f'[{{"id": "sitelink","type": "inputstring","name": "Site Link","value": "{site}"}}]\n') + + +def seed_qbittorrent(plan): + directory = os.path.join(plan.state, "qbittorrent", "qBittorrent") + os.makedirs(directory, exist_ok=True) + path = os.path.join(directory, "qBittorrent.conf") + if os.path.exists(path): + info("Keeping the existing qBittorrent configuration.") + return + say("Pre-seeding qBittorrent configuration...") + with open(path, "w", encoding="utf-8") as handle: + handle.write(QBITTORRENT_CONF) + + +def start_services(plan, engine): + services = ["qbittorrent", "flaresolverr"] + [name for name in ("jackett", "prowlarr") if plan.local(name)] + say() + say("Starting containers in the background to initialize configurations...") + if engine.compose(plan, ["up", "-d", "--remove-orphans"] + services) != 0: + raise SetupError("compose could not start the services. See the output above.") + + +def wait_for_services(plan, engine, timeout=None): + timeout = float(os.environ.get("HELM_SETUP_TIMEOUT", "45") if timeout is None else timeout) + name = next((n for n in ("jackett", "prowlarr") if plan.local(n)), "qbittorrent") + info("Waiting for services to initialize...") + deadline = time.monotonic() + timeout + waited = 0.0 + while True: + container = engine.container_id(plan, name) + if container: + state = engine.output(["inspect", "-f", "{{.State.Status}}", container]).strip() + if state == "running": + say("[OK] Services are initialized and running!") + return True + if state == "exited": + raise SetupError( + f"Container {name} started but crashed immediately. " + f"Run 'docker logs {plan.project}-{name}' to see why." + ) + if time.monotonic() >= deadline: + warn("Timeout reached while waiting for configurations.") + warn("Services may be experiencing slow startup times or are hanging.") + return False + time.sleep(engine.poll) + waited += engine.poll + say(f"Polling status... ({waited:.0f}/{timeout:.0f} seconds)") + + +def grab_api_key(plan, engine, name): + tries = int(os.environ.get("HELM_SETUP_KEY_TRIES", "15")) + poll = float(os.environ.get("HELM_SETUP_KEY_POLL", "3")) + for _ in range(tries): + container = engine.container_id(plan, name) + key = engine.api_key(name, container) if container else "" + if key: + return key + time.sleep(poll) + return "" + + +def configure_api_keys(plan, engine): + if plan.wants("jackett"): + key = plan.external["jackett"][1] if "jackett" in plan.external else plan.jackett_api + if not key: + key = grab_api_key(plan, engine, "jackett") + if key: + say("[+] Successfully grabbed Jackett API Key.") + engine.run( + [ + "exec", + engine.container_id(plan, "jackett"), + "sed", + "-i", + 's|"FlareSolverrUrl":.*|"FlareSolverrUrl": "http://flaresolverr:8191",|', + KEY_FILES["jackett"], + ] + ) + engine.compose(plan, ["restart", "jackett"]) + say("[+] Jackett configured with FlareSolverr.") + else: + warn("Could not find APIKey in Jackett configuration. Using placeholder.") + key = "your_jackett_api_key_here" + plan.jackett_api = key + set_env_value(plan, "JACKETT_API_KEY", key) + if plan.wants("prowlarr"): + key = plan.external["prowlarr"][1] if "prowlarr" in plan.external else plan.prowlarr_api + if not key: + key = grab_api_key(plan, engine, "prowlarr") + if key: + say("[+] Successfully grabbed Prowlarr API Key.") + else: + warn("Could not find APIKey in Prowlarr configuration. Using placeholder.") + key = "your_prowlarr_api_key_here" + plan.prowlarr_api = key + set_env_value(plan, "PROWLARR_API_KEY", key) + + +def launcher_text(plan): + if plan.engine == "podman": + words = [ + "podman", "run", "-it", "--rm", "--entrypoint=", "--security-opt", "label=disable", + "--network", f"{plan.project}_default", "-v", f"{plan.workdir}:/app", + "-v", f"{plan.config}:/config/helm", "-e", "HELM_CONFIG_DIR=/config/helm", + "-v", f"{plan.socket}:/var/run/docker.sock", "--env-file", plan.env_file, + IMAGE, "python", "-m", "helm.cli", + ] # fmt: skip + run = " ".join(shlex.quote(w) for w in words) + ' "$@" 2> >(grep -v "rootless netns" >&2)' + else: + words = ["docker", "compose", "-f", plan.compose_file, "--profile", "cli", "run", "--rm", "cli"] + run = "exec " + " ".join(shlex.quote(w) for w in words) + ' "$@"' + return f"""#!/usr/bin/env bash +# Generated by helm-torrent init for {plan.engine}. Re-run setup to change it. +set -e +export COMPOSE_PROJECT_NAME={shlex.quote(plan.project)} +oneshot=0 +for arg in "$@"; do + case "$arg" in + -o|--oneshot) oneshot=1 ;; + esac +done +if [ "$oneshot" -eq 0 ]; then + set -- --oneshot "$@" +fi +{run} +""" + + +def write_launcher(plan): + say("Generating helm-torrent launcher script...") + path = os.path.join(plan.workdir, "helm-torrent.sh") + with open(path, "w", encoding="utf-8") as handle: + handle.write(launcher_text(plan)) + os.chmod(path, 0o755) + + +def stop_stack(plan, engine): + say("Tearing down containers for Ephemeral (One-Shot) mode...") + if plan.engine == "podman": + # podman stop avoids compose tearing down the network namespace, which hits + # "rootless netns: kill network process: permission denied". + engine.run(["stop"] + [f"{plan.project}-{name}" for name in SERVICES]) + else: + engine.compose(plan, ["stop"]) + + +def print_summary(plan): + say() + say("Setup is 100% complete! Everything is configured.") + say("Your config files and secrets.env were not changed.") + say("---") + say("Security Summary & Data Locations:") + say(f" - Settings: {plan.config}/") + say(f" - Databases: {plan.state}/") + say(f" - Secrets: {plan.env_file} (mode 600)") + say(f" - Downloads: {plan.downloads}/") + say("---") + if any(os.path.exists(os.path.join(plan.config, name)) for name in ("config.toml", "config.jsonc")): + info(f"The containers use INDEXER_MANAGER={plan.indexers} from {plan.env_file}.") + info(f'For a helm-torrent on this machine, set search.indexer_manager = "{plan.indexers}" in your config file.') + say() + + +def finish(plan, engine): + if plan.run_mode == "oneshot": + stop_stack(plan, engine) + write_launcher(plan) + say("Containers stopped. Helm will spin them up automatically when you trigger a download.") + say() + say("To start using the app in its isolated CLI container, run:") + say(" ./helm-torrent.sh") + else: + say("Containers are left running 24/7 in the background.") + say() + say("To start using the app in its isolated CLI container, run:") + say(f" {plan.engine} compose --profile cli run --rm cli") + + +def run_setup(plan, engine=None): + engine = engine or Engine() + for name in (plan.state, plan.downloads, plan.config): + compose.check_value("path", name) + for name in ("jackett", "prowlarr", "qbittorrent", "gluetun"): + os.makedirs(os.path.join(plan.state, name), exist_ok=True) + os.makedirs(plan.downloads, exist_ok=True) + os.makedirs(plan.config, exist_ok=True) + + detect_existing(plan, engine) + choose(plan) + write_compose(plan) + write_env(plan) + if plan.local("jackett"): + seed_jackett(plan) + seed_qbittorrent(plan) + start_services(plan, engine) + wait_for_services(plan, engine) + configure_api_keys(plan, engine) + print_summary(plan) + finish(plan, engine) + + +# ---------------------------------------------------------------- command line + + +def add_arguments(parser): + parser.add_argument("--engine", choices=("docker", "podman"), help="Container engine (asked when missing)") + parser.add_argument("--indexers", choices=("jackett", "prowlarr", "both"), help="Indexer manager to run") + parser.add_argument("--run-mode", choices=("permanent", "oneshot"), help="Keep containers running, or not") + parser.add_argument("--workdir", help="Where docker-compose.yml and helm-torrent.sh go (default: state dir)") + parser.add_argument("--socket", help="Engine socket path on the host") + parser.add_argument("--project", help="Container name prefix (default: COMPOSE_PROJECT_NAME or helm)") + parser.add_argument("--mount-source", action="store_true", help="Mount /src into the CLI container") + parser.add_argument("--skip-prompts", action="store_true", help="Use defaults instead of asking") + + +def default_socket(engine): + if engine == "podman": + found = Engine("podman").output(["info", "--format", "{{.Host.RemoteSocket.Path}}"]).strip() + return found or f"/run/user/{os.getuid()}/podman/podman.sock" + return "/var/run/docker.sock" + + +def engine_command(engine): + """The docker CLI talks to both engines; fall back to podman's own CLI without it.""" + if os.environ.get("HELM_DOCKER_CMD"): + return os.environ["HELM_DOCKER_CMD"] + return "docker" if shutil.which("docker") or engine == "docker" else "podman" + + +def plan_from_args(args, settings_paths): + """Build a Plan from ``helm-torrent init`` arguments, asking for anything missing.""" + state, config, downloads = settings_paths + skip = bool(args.skip_prompts) + probe = Plan("docker", "jackett", "oneshot", state, config, downloads, "", "", skip_prompts=skip) + + engine = args.engine + if engine is None: + reply = ask(probe, "Container engine: [1] Docker (default) [2] Podman: ", "1") + engine = "podman" if reply == "2" else "docker" + indexers = args.indexers + if indexers is None: + reply = ask(probe, "Indexer manager: [1] Jackett (default) [2] Prowlarr [3] Both: ", "3" if skip else "1") + indexers = {"2": "prowlarr", "3": "both"}.get(reply, "jackett") + run_mode = args.run_mode + if run_mode is None: + reply = ask(probe, "Run mode: [1] Permanent [2] Ephemeral one-shot (default): ", "2") + run_mode = "permanent" if reply == "1" else "oneshot" + + return Plan( + engine=engine, + indexers=indexers, + run_mode=run_mode, + state=state, + config=config, + downloads=downloads, + workdir=os.path.abspath(args.workdir or state), + socket=args.socket or default_socket(engine), + project=args.project or os.environ.get("COMPOSE_PROJECT_NAME") or "helm", + source=bool(args.mount_source), + skip_prompts=skip, + ) + + +def main(args): + from helm.core.config_manager import get_config_dir, get_dl_dir, get_state_dir + + paths = ( + os.path.abspath(get_state_dir()), + os.path.abspath(get_config_dir()), + os.path.abspath(get_dl_dir()), + ) + try: + plan = plan_from_args(args, paths) + os.environ["COMPOSE_PROJECT_NAME"] = plan.project + run_setup(plan, Engine(engine_command(plan.engine))) + except (SetupError, compose.TemplateError) as problem: + error(str(problem)) + return 1 + return 0 diff --git a/tests/test_setup_script.py b/tests/test_setup_script.py index 569a545..6b5530e 100644 --- a/tests/test_setup_script.py +++ b/tests/test_setup_script.py @@ -1,21 +1,28 @@ -"""Run the real setup.sh against fake docker, podman and systemctl binaries.""" +"""Run the real setup.sh and helm-torrent init against fake engine binaries. + +``HELM_SETUP_RUNNER`` makes setup.sh run init on the host instead of inside +the image, so these tests see the files the containerised run would write. +""" import itertools import os import shutil +import site import stat import subprocess +import sys from pathlib import Path import pytest import yaml -from helm.core import compose, init_env +from helm.core import compose, stack_setup ROOT = Path(__file__).resolve().parents[1] SETUP = ROOT / "setup.sh" REAL_DOCKER = shutil.which("docker") BASH = shutil.which("bash") +RUNNER = f"{sys.executable} -m helm.cli" pytestmark = pytest.mark.skipif(BASH is None, reason="bash is required") @@ -23,9 +30,14 @@ name=$(basename "$0") printf '%s %s\n' "$name" "$*" >> "$FAKE_LOG" case "$1" in - compose) exit 0 ;; + compose) [ "$2" == "version" ] && exit 0; exit "${FAKE_COMPOSE_STATUS:-0}" ;; info) - if [ "$2" == "--format" ]; then echo "/run/fake/podman.sock"; fi + if [ "$2" == "--format" ]; then + case "$3" in + *RemoteSocket*) echo "/run/fake/podman.sock" ;; + *SecurityOptions*) echo "${FAKE_SECURITY:-[name=seccomp]}" ;; + esac + fi exit 0 ;; ps) if [ "$2" == "--format" ]; then @@ -56,89 +68,70 @@ def make_bin(directory, name, body): path.chmod(path.stat().st_mode | stat.S_IEXEC) -@pytest.fixture -def box(tmp_path): - bin_dir = tmp_path / "bin" - bin_dir.mkdir() - for name in ("docker", "podman"): - make_bin(bin_dir, name, FAKE_ENGINE) - make_bin(bin_dir, "systemctl", '#!/bin/sh\necho "systemctl $*" >> "$FAKE_LOG"\n') - make_bin(bin_dir, "sudo", '#!/bin/sh\necho "sudo $*" >> "$FAKE_LOG"\nexit 97\n') - work = tmp_path / "work dir" - work.mkdir() - home = tmp_path / "home" - home.mkdir() - env = { - "PATH": f"{bin_dir}:{os.environ['PATH']}", - "HOME": str(home), - "FAKE_LOG": str(tmp_path / "calls.log"), - "FAKE_EXTERNAL": "", - "NO_COLOR": "1", - "HELM_SETUP_POLL": "0", - "HELM_SETUP_KEY_POLL": "0", - "HELM_SETUP_KEY_TRIES": "2", - } - - class Box: - pass - - b = Box() - b.tmp, b.work, b.home, b.env, b.log = tmp_path, work, home, env, Path(env["FAKE_LOG"]) - b.state = tmp_path / "state dir" - b.config = tmp_path / "config" - b.dl = tmp_path / "dl" - - def run(*args, script=SETUP, stdin="", extra=None, dirs=True): +class Box: + def __init__(self, tmp_path): + self.tmp = tmp_path + bin_dir = tmp_path / "bin" + bin_dir.mkdir() + for name in ("docker", "podman"): + make_bin(bin_dir, name, FAKE_ENGINE) + make_bin(bin_dir, "systemctl", '#!/bin/sh\necho "systemctl $*" >> "$FAKE_LOG"\n') + make_bin(bin_dir, "sudo", '#!/bin/sh\necho "sudo $*" >> "$FAKE_LOG"\ncat > /dev/null\n') + self.work = tmp_path / "work dir" + self.work.mkdir() + self.home = tmp_path / "home" + self.home.mkdir() + self.log = tmp_path / "calls.log" + self.state = tmp_path / "state dir" + self.config = tmp_path / "config" + self.dl = tmp_path / "dl" + self.env = { + "PATH": f"{bin_dir}:{os.environ['PATH']}", + "HOME": str(self.home), + "PYTHONPATH": str(ROOT / "src"), + # HOME changes below; keep this interpreter's user site-packages. + "PYTHONUSERBASE": site.getuserbase(), + "FAKE_LOG": str(self.log), + "FAKE_EXTERNAL": "", + "NO_COLOR": "1", + "HELM_SETUP_RUNNER": RUNNER, + "HELM_SETUP_POLL": "0", + "HELM_SETUP_KEY_POLL": "0", + "HELM_SETUP_KEY_TRIES": "2", + } + + def run(self, *args, script=SETUP, stdin="", extra=None, dirs=True): argv = [BASH, str(script)] if dirs: - argv += ["--state-dir", str(b.state), "--config-dir", str(b.config), "--downloads-dir", str(b.dl)] - argv += list(args) + argv += ["--state-dir", str(self.state), "--config-dir", str(self.config), "--downloads-dir", str(self.dl)] + env = {**self.env, **(extra or {})} + env = {key: value for key, value in env.items() if value is not None} return subprocess.run( - argv, - cwd=b.work, - env={**b.env, **(extra or {})}, - input=stdin, - capture_output=True, - text=True, - timeout=60, + argv + list(args), cwd=self.work, env=env, input=stdin, capture_output=True, text=True, timeout=120 ) - def calls(): - return b.log.read_text().splitlines() if b.log.exists() else [] + def calls(self): + return self.log.read_text().splitlines() if self.log.exists() else [] - def env_file(): - lines = (b.state / ".env.docker").read_text().splitlines() + def env_file(self): + lines = (self.state / ".env.docker").read_text().splitlines() return dict(line.split("=", 1) for line in lines if "=" in line and not line.startswith("#")) - b.run, b.calls, b.env_file = run, calls, env_file - return b - - -def values(box, socket="/var/run/docker.sock"): - return { - "HELM_STATE": str(box.state), - "HELM_DL": str(box.dl), - "HELM_CONFIG": str(box.config), - "ENGINE_SOCKET": socket, - } - - -def bash_render(blocks, vals, template=compose.TEMPLATE): - return subprocess.run( - [ - BASH, - "-c", - 'source "$1"; render_compose "$2" "$3"', - "render", - str(SETUP), - str(template), - " ".join(sorted(blocks)), - ], - env={**os.environ, **vals}, - capture_output=True, - text=True, - check=False, - ) + def values(self, socket="/var/run/docker.sock"): + return { + "HELM_STATE": str(self.state), + "HELM_DL": str(self.dl), + "HELM_CONFIG": str(self.config), + "ENGINE_SOCKET": socket, + } + + def compose_text(self): + return (self.work / "docker-compose.yml").read_text() + + +@pytest.fixture +def box(tmp_path): + return Box(tmp_path) def all_block_sets(): @@ -153,28 +146,16 @@ def all_block_sets(): # ---------------------------------------------------------------- template -def test_bash_and_python_render_identically_for_every_block_set(): - vals = { - "HELM_STATE": "/tmp/state & co/x\\y", - "HELM_DL": "/dl with space", - "HELM_CONFIG": "/cfg/@HELM_DL@", - "ENGINE_SOCKET": "/run/user/1000/podman/podman.sock", - } - for blocks in all_block_sets(): - result = bash_render(blocks, vals) - assert result.returncode == 0, result.stderr - assert result.stdout == compose.render(blocks, vals), sorted(blocks) - - def test_rendered_files_have_the_expected_services(): vals = {"HELM_STATE": "/s", "HELM_DL": "/d", "HELM_CONFIG": "/c", "ENGINE_SOCKET": "/sock"} for blocks in all_block_sets(): - data = yaml.safe_load(compose.render(blocks, vals)) - services = set(data["services"]) + text = compose.render(blocks, vals) + assert "#@" not in text and "@HELM" not in text + data = yaml.safe_load(text) expected = {"flaresolverr", "qbittorrent"} | (blocks & {"jackett", "prowlarr", "cli"}) if "vpn" in blocks: expected.add("gluetun") - assert services == expected + assert set(data["services"]) == expected qb = data["services"]["qbittorrent"] if "vpn" in blocks: assert qb["network_mode"] == "service:gluetun" and "ports" not in qb @@ -187,20 +168,19 @@ def test_rendered_files_have_the_expected_services(): assert "HELM_CONFIG_DIR=/config/helm" in cli["environment"] assert "/sock:/var/run/docker.sock" in cli["volumes"] assert any(v.endswith("/src:/app/src") for v in cli["volumes"]) == ("source" in blocks) - assert "#@" not in compose.render(blocks, vals) -@pytest.mark.parametrize( - "template", - ["a\n#@ end\n", "a\n#@ if cli\nb\n"], -) -def test_unbalanced_templates_fail_in_both_renderers(tmp_path, template): - path = tmp_path / "bad.yml" - path.write_text(template) - vals = {name: "/x" for name in compose.PLACEHOLDERS} +def test_placeholders_are_replaced_literally(): + vals = {"HELM_STATE": "/s & \\1 $x", "HELM_DL": "/@HELM_STATE@", "HELM_CONFIG": "/c", "ENGINE_SOCKET": "/k"} + text = compose.render({"jackett", "novpn"}, vals) + assert '"/s & \\1 $x/jackett:/config"' in text + assert '"/@HELM_STATE@:/downloads"' in text + + +@pytest.mark.parametrize("template", ["a\n#@ end\n", "a\n#@ if cli\nb\n"]) +def test_unbalanced_templates_fail(template): with pytest.raises(compose.TemplateError): - compose.render({"novpn"}, vals, template=template) - assert bash_render({"novpn"}, vals, template=path).returncode != 0 + compose.render({"novpn"}, {name: "/x" for name in compose.PLACEHOLDERS}, template=template) def test_nested_blocks_need_every_parent_on(): @@ -245,27 +225,11 @@ def test_docker_compose_accepts_every_rendered_file(tmp_path): def test_template_ships_as_package_data(): - pyproject = (ROOT / "pyproject.toml").read_text() - assert '"helm.core" = ["compose.template.yml"]' in pyproject + assert '"helm.core" = ["compose.template.yml"]' in (ROOT / "pyproject.toml").read_text() assert compose.TEMPLATE.is_file() -def test_init_env_uses_the_template_without_the_cli_service(tmp_path): - text = init_env.build_compose("/s", "/d", "/c", use_vpn=True) - assert text == compose.render( - {"jackett", "prowlarr", "vpn"}, {"HELM_STATE": "/s", "HELM_DL": "/d", "HELM_CONFIG": "/c", "ENGINE_SOCKET": ""} - ) - assert "cli" not in yaml.safe_load(text)["services"] - - path = tmp_path / ".env.docker" - path.write_text("old") - path.chmod(0o644) - init_env.write_private(str(path), "QB_PASSWORD=x\n") - assert path.read_text() == "QB_PASSWORD=x\n" - assert stat.S_IMODE(path.stat().st_mode) == 0o600 - - -# ---------------------------------------------------------------- setup.sh runs +# ---------------------------------------------------------------- setup.sh def test_help_and_unknown_option(box): @@ -285,13 +249,15 @@ def test_skip_prompts_with_docker(box): assert result.returncode == 0, result.stderr compose_file = box.work / "docker-compose.yml" - assert compose_file.read_text() == compose.render({"cli", "jackett", "prowlarr", "novpn"}, values(box)) + assert box.compose_text() == compose.render({"cli", "jackett", "prowlarr", "novpn"}, box.values()) env = box.env_file() assert env["JACKETT_API_KEY"] == "jkey-id-jackett" assert env["PROWLARR_API_KEY"] == "pkey-id-prowlarr" assert env["JACKETT_URL"] == "http://jackett:9117" + assert env["PROWLARR_URL"] == "http://prowlarr:9696" assert env["QB_WEBUI"] == "http://qbittorrent:18080" + assert env["QB_USERNAME"] == "admin" assert env["INDEXER_MANAGER"] == "both" assert env["COMPOSE_PROJECT_NAME"] == "helm" assert env["HOST_PWD"] == str(box.work) @@ -299,16 +265,14 @@ def test_skip_prompts_with_docker(box): calls = box.calls() file_arg = f"-f {compose_file}" - assert f"docker compose {file_arg} --profile cli pull cli" in calls assert f"docker compose {file_arg} up -d --remove-orphans qbittorrent flaresolverr jackett prowlarr" in calls assert f"docker compose {file_arg} restart jackett" in calls assert f"docker compose {file_arg} stop" in calls - assert not any(call.startswith("sudo") for call in calls) + assert not any(call.startswith(("sudo", "docker pull", "docker run")) for call in calls) assert (box.state / "jackett/Jackett/Indexers/yts.json").is_file() assert "WebUI\\Username=admin" in (box.state / "qbittorrent/qBittorrent/qBittorrent.conf").read_text() assert not (box.config / "config.json").exists() - for path in (box.config, box.state, box.dl): assert f"{path}/" in result.stdout assert "./helm-torrent.sh" in result.stdout @@ -317,6 +281,7 @@ def test_skip_prompts_with_docker(box): def test_docker_launcher_adds_oneshot_once(box): assert box.run("--skip-prompts").returncode == 0 launcher = box.work / "helm-torrent.sh" + assert stat.S_IMODE(launcher.stat().st_mode) == 0o755 assert subprocess.run([BASH, "-n", str(launcher)], check=False).returncode == 0 if shutil.which("shellcheck"): result = subprocess.run(["shellcheck", str(launcher)], capture_output=True, text=True, check=False) @@ -348,8 +313,7 @@ def test_external_jackett_is_detected_before_files_are_written(box): assert result.returncode == 0, result.stderr assert "Found existing external jackett container: my-jackett" in result.stdout - data = yaml.safe_load((box.work / "docker-compose.yml").read_text()) - assert "jackett" not in data["services"] + assert "jackett" not in yaml.safe_load(box.compose_text())["services"] env = box.env_file() assert env["JACKETT_URL"] == "http://host.docker.internal:29117" assert env["JACKETT_API_KEY"] == "jkey-my-jackett" @@ -358,13 +322,13 @@ def test_external_jackett_is_detected_before_files_are_written(box): assert not (box.state / "jackett/Jackett/Indexers").exists() -def test_interactive_vpn_and_systemd_prompt(box): - answers = "1\n1\n1\nmy-key\nbob\ny\nmullvad\nwireguard\nwg-secret\nn\n" +def test_interactive_vpn_and_systemd(box): + # install, indexer, run mode, systemd (bash); then Jackett key, user, VPN answers (init) + answers = "1\n1\n1\ny\nmy-key\nbob\ny\nmullvad\nwireguard\nwg-secret\n" result = box.run(stdin=answers) assert result.returncode == 0, result.stderr - expected = compose.render({"cli", "jackett", "vpn"}, values(box)) - assert (box.work / "docker-compose.yml").read_text() == expected + assert box.compose_text() == compose.render({"cli", "jackett", "vpn"}, box.values()) env = box.env_file() assert env["QB_WEBUI"] == "http://gluetun:18080" assert env["QB_USERNAME"] == "bob" @@ -372,17 +336,21 @@ def test_interactive_vpn_and_systemd_prompt(box): assert env["VPN_SERVICE_PROVIDER"] == "mullvad" assert env["VPN_TYPE"] == "wireguard" assert env["WIREGUARD_PRIVATE_KEY"] == "wg-secret" - assert "PROWLARR_URL" in env and env["PROWLARR_API_KEY"] == "placeholder" + assert env["PROWLARR_API_KEY"] == "placeholder" assert "left running 24/7" in result.stdout assert not (box.work / "helm-torrent.sh").exists() - assert not any(call.endswith(" stop") for call in box.calls()) + + calls = box.calls() + assert not any(call.endswith(" stop") for call in calls) + assert "sudo tee /etc/systemd/system/helm-app.service" in calls + assert "sudo systemctl enable helm-app.service" in calls def test_empty_vpn_key_disables_the_vpn(box): result = box.run(stdin="1\n1\n2\n\n\ny\nmullvad\nwireguard\n\n") assert result.returncode == 0, result.stderr assert "WireGuard key cannot be empty" in result.stderr - assert "gluetun" not in yaml.safe_load((box.work / "docker-compose.yml").read_text())["services"] + assert "gluetun" not in yaml.safe_load(box.compose_text())["services"] def test_crashed_container_stops_setup(box): @@ -391,24 +359,27 @@ def test_crashed_container_stops_setup(box): assert "crashed immediately" in result.stderr and "docker logs helm-jackett" in result.stderr -def test_podman_uses_the_real_image_and_socket(box): +def test_compose_failure_stops_setup(box): + result = box.run("--skip-prompts", extra={"FAKE_COMPOSE_STATUS": "3"}) + assert result.returncode == 1 + assert "compose could not start the services" in result.stderr + + +def test_podman_uses_its_socket_and_the_real_image(box): result = box.run(stdin="2\n2\n2\n\n\n\n") assert result.returncode == 0, result.stderr sock = "/run/fake/podman.sock" compose_file = box.work / "docker-compose.yml" - assert compose_file.read_text() == compose.render({"cli", "prowlarr", "novpn"}, values(box, sock)) + assert box.compose_text() == compose.render({"cli", "prowlarr", "novpn"}, box.values(sock)) env = box.env_file() assert env["PROWLARR_API_KEY"] == "pkey-id-prowlarr" and env["INDEXER_MANAGER"] == "prowlarr" calls = box.calls() assert "systemctl --user enable --now podman.socket" in calls - assert f"podman compose -f {compose_file} --profile cli pull cli" in calls - up = [call for call in calls if call.startswith("podman run") and " up -d " in call] - assert len(up) == 1 and compose.TEMPLATE.name not in up[0] - assert "ghcr.io/piratebird/helm:latest docker compose -f /app/docker-compose.yml up -d" in up[0] + assert f"podman compose -f {compose_file} up -d --remove-orphans qbittorrent flaresolverr prowlarr" in calls + assert "podman stop helm-prowlarr helm-jackett helm-qbittorrent helm-flaresolverr helm-gluetun" in calls assert "mini-helm" not in " ".join(calls) - assert any(call.startswith("podman stop helm-prowlarr helm-jackett") for call in calls) launcher = box.work / "helm-torrent.sh" box.log.write_text("") @@ -429,27 +400,19 @@ def test_project_name_comes_from_the_environment(box): assert "export COMPOSE_PROJECT_NAME=media" in (box.work / "helm-torrent.sh").read_text() -def test_curl_one_liner_downloads_the_template(box): +def test_checkout_mounts_local_source(box): + (box.work / "src" / "helm").mkdir(parents=True) + assert box.run("--skip-prompts").returncode == 0 + assert box.compose_text() == compose.render({"cli", "jackett", "prowlarr", "source", "novpn"}, box.values()) + + +def test_script_works_away_from_a_checkout(box): script = box.tmp / "fd" / "setup.sh" script.parent.mkdir() shutil.copy(SETUP, script) - if shutil.which("curl") is None: - pytest.skip("curl is not installed") - result = box.run("--skip-prompts", script=script, extra={"HELM_RAW_BASE": f"file://{ROOT}"}) + result = box.run("--skip-prompts", script=script) assert result.returncode == 0, result.stderr - assert "Downloading the compose template" in result.stdout - expected = compose.render({"cli", "jackett", "prowlarr", "novpn"}, values(box)) - assert (box.work / "docker-compose.yml").read_text() == expected - - result = box.run("--skip-prompts", script=script, extra={"HELM_RAW_BASE": f"file://{box.tmp}/missing"}) - assert result.returncode == 1 and "Could not download" in result.stderr - - -def test_checkout_mounts_local_source(box): - (box.work / "src" / "helm").mkdir(parents=True) - assert box.run("--skip-prompts").returncode == 0 - expected = compose.render({"cli", "jackett", "prowlarr", "source", "novpn"}, values(box)) - assert (box.work / "docker-compose.yml").read_text() == expected + assert box.compose_text() == compose.render({"cli", "jackett", "prowlarr", "novpn"}, box.values()) def test_missing_docker_prints_install_help(box, tmp_path): @@ -463,3 +426,224 @@ def test_missing_docker_prints_install_help(box, tmp_path): assert result.returncode == 1 assert "Docker is not installed" in result.stderr assert "Unix Shenanigans Reminder" in result.stdout + + +# ---------------------------------------------------------------- container handoff + + +def init_call(calls): + (call,) = [call for call in calls if call.startswith(("docker run", "podman run"))] + return call + + +def test_init_runs_in_the_image_as_the_user(box): + result = box.run("--skip-prompts", extra={"HELM_SETUP_RUNNER": None}) + assert result.returncode == 0, result.stderr + calls = box.calls() + assert "docker pull ghcr.io/piratebird/helm:latest" in calls + call = init_call(calls) + assert call.startswith( + "docker run --rm -i --security-opt label=disable -v /var/run/docker.sock:/var/run/docker.sock" + ) + for path in (box.work, box.state, box.config, box.dl): + assert f"-v {path}:{path}" in call + assert f"--user {os.getuid()}:{os.getgid()} --group-add " in call + assert f"-w {box.work} -e HOME=/tmp -e HELM_DOCKER_CMD=docker -e COMPOSE_PROJECT_NAME=helm" in call + assert call.endswith( + f"ghcr.io/piratebird/helm:latest init --config-dir {box.config} --state-dir {box.state} " + f"--dl-dir {box.dl} --engine docker --indexers both --workdir {box.work} " + "--socket /var/run/docker.sock --project helm --run-mode oneshot --skip-prompts" + ) + + +def test_rootless_engines_keep_root_in_the_container(box): + result = box.run("--skip-prompts", extra={"HELM_SETUP_RUNNER": None, "FAKE_SECURITY": "[name=rootless]"}) + assert result.returncode == 0, result.stderr + assert "--user" not in init_call(box.calls()) + + box.log.write_text("") + result = box.run(stdin="2\n1\n2\n", extra={"HELM_SETUP_RUNNER": None}) + assert result.returncode == 0, result.stderr + call = init_call(box.calls()) + assert call.startswith("podman run --rm -i --security-opt label=disable -v /run/fake/podman.sock:") + assert "--user" not in call and "--engine podman" in call + + +def test_image_can_be_overridden(box): + result = box.run("--skip-prompts", extra={"HELM_SETUP_RUNNER": None, "HELM_IMAGE": "helm:dev"}) + assert result.returncode == 0, result.stderr + assert "docker pull helm:dev" in box.calls() + assert " helm:dev init " in init_call(box.calls()) + + +# ---------------------------------------------------------------- helm-torrent init directly + + +def run_init(box, *args, stdin=""): + argv = [sys.executable, "-m", "helm.cli", "init", "--config-dir", str(box.config), "--state-dir", str(box.state)] + argv += ["--dl-dir", str(box.dl), *args] + env = {**box.env, "HELM_DOCKER_CMD": "docker"} + return subprocess.run(argv, cwd=box.work, env=env, input=stdin, capture_output=True, text=True, timeout=120) + + +def test_init_asks_for_missing_choices_and_defaults_to_the_state_dir(box): + result = run_init(box, stdin="1\n2\n1\n\n\nn\n") + assert result.returncode == 0, result.stderr + expected = compose.render({"cli", "prowlarr", "novpn"}, box.values()) + assert (box.state / "docker-compose.yml").read_text() == expected + assert box.env_file()["INDEXER_MANAGER"] == "prowlarr" + assert box.env_file()["HOST_PWD"] == str(box.state) + assert "left running 24/7" in result.stdout + + +def test_init_runs_on_a_broken_config_file(box): + box.config.mkdir() + (box.config / "config.toml").write_text("this is [not toml\n") + result = run_init(box, "--engine", "docker", "--indexers", "jackett", "--run-mode", "oneshot", "--skip-prompts") + assert result.returncode == 0, result.stderr + assert "search.indexer_manager" in result.stdout + + +def test_init_rejects_bad_choices(box): + result = run_init(box, "--engine", "lxc") + assert result.returncode == 2 and "invalid choice" in result.stderr + + +def test_init_without_docker_cli_uses_podman(monkeypatch): + monkeypatch.delenv("HELM_DOCKER_CMD", raising=False) + monkeypatch.setattr(stack_setup.shutil, "which", lambda name: None) + assert stack_setup.engine_command("podman") == "podman" + assert stack_setup.engine_command("docker") == "docker" + monkeypatch.setenv("HELM_DOCKER_CMD", "nerdctl") + assert stack_setup.engine_command("podman") == "nerdctl" + + +def make_plan(box, indexers="jackett"): + return stack_setup.Plan( + "docker", indexers, "oneshot", str(box.state), str(box.config), str(box.dl), str(box.work), "/s" + ) + + +def test_openvpn_answers_reach_the_env_file(box, monkeypatch): + answers = iter(["", "", "y", "acme", "openvpn", "user1", "pw1"]) + monkeypatch.setattr("builtins.input", lambda prompt="": next(answers)) + monkeypatch.setattr(sys.stdin, "isatty", lambda: False, raising=False) + plan = make_plan(box) + stack_setup.choose(plan) + assert plan.vpn.provider == "acme" and plan.vpn.kind == "openvpn" + assert plan.vpn.extra == ["OPENVPN_USER=user1", "OPENVPN_PASSWORD=pw1"] + + box.state.mkdir() + stack_setup.write_env(plan) + text = (box.state / ".env.docker").read_text() + assert "VPN_TYPE=openvpn\nOPENVPN_USER=user1\nOPENVPN_PASSWORD=pw1\n" in text + + +def test_custom_openvpn_and_protonvpn_warning(box, monkeypatch, capsys): + answers = iter(["", "", "y", "custom", "openvpn"]) + monkeypatch.setattr("builtins.input", lambda prompt="": next(answers)) + plan = make_plan(box) + stack_setup.choose(plan) + assert plan.vpn.extra == [] and "custom.conf" in capsys.readouterr().out + + answers = iter(["", "", "y", "protonvpn", "openvpn", "", ""]) + stack_setup.choose(plan) + captured = capsys.readouterr() + assert "ProtonVPN blocks P2P" in captured.err and "OpenVPN user cannot be empty" in captured.err + assert plan.vpn is None + + +def test_set_env_value_keeps_other_lines_and_mode(box): + box.state.mkdir() + plan = make_plan(box, "both") + stack_setup.write_private(plan.env_file, "# head\nA=1\nAB=2\n") + stack_setup.set_env_value(plan, "A", "x=y") + assert (box.state / ".env.docker").read_text() == "# head\nA=x=y\nAB=2\n" + assert stat.S_IMODE((box.state / ".env.docker").stat().st_mode) == 0o600 + + +def test_wait_times_out_with_a_warning(box, capsys): + class Quiet(stack_setup.Engine): + def output(self, args): + return "" + + assert stack_setup.wait_for_services(make_plan(box), Quiet(poll=0), timeout=0) is False + assert "Timeout reached" in capsys.readouterr().err + + +def test_missing_api_keys_fall_back_to_placeholders(box): + class Empty(stack_setup.Engine): + def output(self, args): + return "" + + box.state.mkdir() + plan = make_plan(box, "both") + stack_setup.write_env(plan) + os.environ["HELM_SETUP_KEY_TRIES"] = "1" + os.environ["HELM_SETUP_KEY_POLL"] = "0" + try: + stack_setup.configure_api_keys(plan, Empty(command="true", poll=0)) + finally: + del os.environ["HELM_SETUP_KEY_TRIES"], os.environ["HELM_SETUP_KEY_POLL"] + env = box.env_file() + assert env["JACKETT_API_KEY"] == "your_jackett_api_key_here" + assert env["PROWLARR_API_KEY"] == "your_prowlarr_api_key_here" + + +# ---------------------------------------------------------------- whole flow in process + + +@pytest.mark.parametrize( + "engine, indexers, run_mode, vpn, external", + [ + ("docker", "both", "oneshot", False, ""), + ("podman", "prowlarr", "oneshot", False, ""), + ("docker", "jackett", "permanent", True, ""), + ("docker", "both", "permanent", False, "other-prowlarr"), + ], +) +def test_run_setup_in_process(box, monkeypatch, capsys, engine, indexers, run_mode, vpn, external): + for name, value in box.env.items(): + monkeypatch.setenv(name, value) + monkeypatch.setenv("FAKE_EXTERNAL", external) + replies = {"VPN using Gluetun": "y" if vpn else "n", "VPN Provider": "nordvpn", "WireGuard Private Key": "k"} + monkeypatch.setattr("builtins.input", lambda prompt="": next((v for k, v in replies.items() if k in prompt), "")) + plan = stack_setup.Plan( + engine, indexers, run_mode, str(box.state), str(box.config), str(box.dl), str(box.work), "/sock" + ) + fake = str(box.tmp / "bin" / engine) + stack_setup.run_setup(plan, stack_setup.Engine(fake, poll=0)) + out = capsys.readouterr().out + + blocks = {"cli", "vpn" if vpn else "novpn"} | {n for n in ("jackett", "prowlarr") if plan.local(n)} + assert box.compose_text() == compose.render(blocks, box.values("/sock")) + env = box.env_file() + assert env["INDEXER_MANAGER"] == indexers + if external: + assert "prowlarr" not in yaml.safe_load(box.compose_text())["services"] + assert env["PROWLARR_API_KEY"] == f"pkey-{external}" + elif plan.wants("prowlarr"): + assert env["PROWLARR_API_KEY"] == "pkey-id-prowlarr" + if plan.wants("jackett"): + assert env["JACKETT_API_KEY"] == "jkey-id-jackett" + assert ("WIREGUARD_PRIVATE_KEY=k" in (box.state / ".env.docker").read_text()) == vpn + assert (box.work / "helm-torrent.sh").exists() == (run_mode == "oneshot") + assert "Setup is 100% complete" in out + + +def test_main_reports_setup_errors(box, monkeypatch, capsys): + import argparse + + for name, value in box.env.items(): + monkeypatch.setenv(name, value) + monkeypatch.setenv("HELM_CONFIG_DIR", str(box.config)) + monkeypatch.setenv("HELM_STATE_DIR", str(box.state)) + monkeypatch.setenv("HELM_DL_DIR", str(box.dl)) + monkeypatch.setenv("FAKE_STATE", "exited") + monkeypatch.setenv("HELM_DOCKER_CMD", str(box.tmp / "bin" / "docker")) + parser = argparse.ArgumentParser() + stack_setup.add_arguments(parser) + args = parser.parse_args(["--engine", "docker", "--indexers", "jackett", "--run-mode", "oneshot", "--skip-prompts"]) + assert stack_setup.main(args) == 1 + assert "crashed immediately" in capsys.readouterr().err + assert (box.state / "docker-compose.yml").exists() From 780b3425242ba08e8fb2d8a0d601b2aece2866ec Mon Sep 17 00:00:00 2001 From: Piratebird <141295458+Piratebird@users.noreply.github.com> Date: Tue, 3 Nov 2026 00:13:15 +0200 Subject: [PATCH 08/18] :shipit: refactor(layout): move helm.core into feature packages and split cli.py - Split helm.core into config, search, torrents, services, stack, benchmarks and net packages - Move the logger to helm.logger and the compose template next to helm.stack - Keep every module name, so only import paths change and behaviour stays the same - Keep helm.core.http, logger and rss_fetcher as thin aliases for Lite plugins - Split cli.py into helm/cli with one module per command group under commands/ - Route the lazy imports and patched helpers through helm.cli.deps for tests - Anchor the config/ ignore rule to the repo root so src/helm/config is tracked --- .gitignore | 4 +- README.md | 4 +- docs/BENCHMARK.md | 12 +- pyproject.toml | 2 +- src/helm/benchmarks/__init__.py | 1 + src/helm/{core => benchmarks}/benchmark.py | 10 +- .../{core => benchmarks}/device_profile.py | 6 +- .../{core => benchmarks}/stack_benchmark.py | 6 +- src/helm/cli.py | 833 ------------------ src/helm/cli/__init__.py | 6 + src/helm/cli/__main__.py | 17 + src/helm/cli/app.py | 115 +++ src/helm/cli/commands/__init__.py | 1 + src/helm/cli/commands/background.py | 42 + src/helm/cli/commands/banner.py | 49 ++ src/helm/cli/commands/headless.py | 38 + src/helm/cli/commands/indexers.py | 88 ++ src/helm/cli/commands/session.py | 210 +++++ src/helm/cli/commands/status.py | 44 + src/helm/cli/commands/utility.py | 67 ++ src/helm/cli/deps.py | 42 + src/helm/cli/parser.py | 196 +++++ src/helm/config/__init__.py | 1 + src/helm/{core => config}/config_commands.py | 6 +- src/helm/{core => config}/config_manager.py | 0 src/helm/{core => config}/config_wizard.py | 6 +- src/helm/{core => config}/secret_manager.py | 2 +- src/helm/{core => config}/settings.py | 6 +- src/helm/core/__init__.py | 5 + src/helm/core/http.py | 20 +- src/helm/core/logger.py | 148 +--- src/helm/core/rss_fetcher.py | 390 +------- src/helm/logger.py | 147 ++++ src/helm/net/__init__.py | 1 + src/helm/net/http.py | 19 + src/helm/plugins/bittorrented.py | 4 +- src/helm/plugins/eztv.py | 4 +- src/helm/plugins/helpers.py | 2 +- src/helm/plugins/novaprinter.py | 2 +- src/helm/plugins/subsplease.py | 4 +- src/helm/plugins/torrentproject.py | 2 +- src/helm/plugins/x1337.py | 2 +- src/helm/plugins/yts.py | 4 +- src/helm/search/__init__.py | 1 + src/helm/{core => search}/indexer_manager.py | 6 +- src/helm/{core => search}/lite_fetcher.py | 14 +- .../{core => search}/lite_plugin_loader.py | 8 +- src/helm/search/rss_fetcher.py | 389 ++++++++ src/helm/{core => search}/search_runner.py | 16 +- src/helm/{core => search}/torrent_filter.py | 0 src/helm/services/__init__.py | 1 + src/helm/{core => services}/jobs.py | 28 +- src/helm/{core => services}/runtime.py | 4 +- src/helm/{core => services}/server.py | 10 +- src/helm/{core => services}/watch.py | 8 +- src/helm/stack/__init__.py | 1 + src/helm/{core => stack}/compose.py | 0 src/helm/{core => stack}/compose.template.yml | 4 +- src/helm/{core => stack}/oneshot.py | 4 +- src/helm/{core => stack}/stack_setup.py | 4 +- src/helm/torrents/__init__.py | 1 + .../{core => torrents}/lite_downloader.py | 4 +- .../{core => torrents}/qbittorrent_client.py | 8 +- src/helm/{core => torrents}/torrent_links.py | 2 +- src/helm/ui/ansi.py | 2 +- src/helm/ui/banner.py | 8 +- src/helm/ui/theme.py | 2 +- src/helm/ui/tui.py | 8 +- tests/conftest.py | 2 +- tests/test_benchmark.py | 4 +- tests/test_bittorrented_plugin.py | 2 +- tests/test_cli.py | 72 +- tests/test_config_commands.py | 6 +- tests/test_config_manager.py | 2 +- tests/test_device_profile.py | 6 +- tests/test_eztv_plugin.py | 2 +- tests/test_headless_cli.py | 2 +- tests/test_jobs.py | 16 +- tests/test_lite_fetcher.py | 30 +- tests/test_lite_plugin_loader.py | 6 +- tests/test_logger.py | 12 +- tests/test_module_paths.py | 46 + tests/test_prowlarr_manager.py | 2 +- tests/test_qbittorrent_client.py | 4 +- tests/test_rss_fetcher.py | 14 +- tests/test_runtime.py | 6 +- tests/test_scraper_fixtures.py | 6 +- tests/test_search_runner.py | 12 +- tests/test_secret_manager.py | 6 +- tests/test_server.py | 10 +- tests/test_service_boundaries.py | 10 +- tests/test_settings.py | 10 +- tests/test_setup_script.py | 4 +- tests/test_stack_benchmark.py | 6 +- tests/test_subsplease_plugin.py | 2 +- tests/test_terminal_codes.py | 24 +- tests/test_theme_banner.py | 4 +- tests/test_torrent_filter.py | 2 +- tests/test_torrent_links.py | 4 +- tests/test_watch.py | 6 +- tests/test_x1337_plugin.py | 2 +- tests/test_yts_plugin.py | 2 +- 102 files changed, 1802 insertions(+), 1643 deletions(-) create mode 100644 src/helm/benchmarks/__init__.py rename src/helm/{core => benchmarks}/benchmark.py (98%) rename src/helm/{core => benchmarks}/device_profile.py (97%) rename src/helm/{core => benchmarks}/stack_benchmark.py (99%) delete mode 100644 src/helm/cli.py create mode 100644 src/helm/cli/__init__.py create mode 100644 src/helm/cli/__main__.py create mode 100644 src/helm/cli/app.py create mode 100644 src/helm/cli/commands/__init__.py create mode 100644 src/helm/cli/commands/background.py create mode 100644 src/helm/cli/commands/banner.py create mode 100644 src/helm/cli/commands/headless.py create mode 100644 src/helm/cli/commands/indexers.py create mode 100644 src/helm/cli/commands/session.py create mode 100644 src/helm/cli/commands/status.py create mode 100644 src/helm/cli/commands/utility.py create mode 100644 src/helm/cli/deps.py create mode 100644 src/helm/cli/parser.py create mode 100644 src/helm/config/__init__.py rename src/helm/{core => config}/config_commands.py (98%) rename src/helm/{core => config}/config_manager.py (100%) rename src/helm/{core => config}/config_wizard.py (98%) rename src/helm/{core => config}/secret_manager.py (98%) rename src/helm/{core => config}/settings.py (99%) create mode 100644 src/helm/logger.py create mode 100644 src/helm/net/__init__.py create mode 100644 src/helm/net/http.py create mode 100644 src/helm/search/__init__.py rename src/helm/{core => search}/indexer_manager.py (98%) rename src/helm/{core => search}/lite_fetcher.py (94%) rename src/helm/{core => search}/lite_plugin_loader.py (94%) create mode 100644 src/helm/search/rss_fetcher.py rename src/helm/{core => search}/search_runner.py (92%) rename src/helm/{core => search}/torrent_filter.py (100%) create mode 100644 src/helm/services/__init__.py rename src/helm/{core => services}/jobs.py (94%) rename src/helm/{core => services}/runtime.py (98%) rename src/helm/{core => services}/server.py (97%) rename src/helm/{core => services}/watch.py (95%) create mode 100644 src/helm/stack/__init__.py rename src/helm/{core => stack}/compose.py (100%) rename src/helm/{core => stack}/compose.template.yml (98%) rename src/helm/{core => stack}/oneshot.py (98%) rename src/helm/{core => stack}/stack_setup.py (99%) create mode 100644 src/helm/torrents/__init__.py rename src/helm/{core => torrents}/lite_downloader.py (97%) rename src/helm/{core => torrents}/qbittorrent_client.py (95%) rename src/helm/{core => torrents}/torrent_links.py (99%) create mode 100644 tests/test_module_paths.py diff --git a/.gitignore b/.gitignore index 85f137c..61aa077 100644 --- a/.gitignore +++ b/.gitignore @@ -34,10 +34,10 @@ testing/ bugs_notes.txt # Docker / App Data -# docker-compose.yml is generated by setup.sh from src/helm/core/compose.template.yml +# docker-compose.yml is generated by setup.sh from src/helm/stack/compose.template.yml docker-compose.yml docker_data/ -config/ +/config/ downloads/ # Auto-generated launcher (machine-specific) diff --git a/README.md b/README.md index e8b30cb..b570d29 100644 --- a/README.md +++ b/README.md @@ -127,7 +127,7 @@ The script will guide you through: 2. Choosing your run mode (Ephemeral vs Permanent) 3. Setting up a VPN (optional) -`setup.sh` only handles the host: the container engine, native installs and the optional systemd unit. It then pulls `ghcr.io/piratebird/helm` and runs `helm-torrent init` inside it, with the engine socket and your directories mounted at the same paths, so the files it writes are owned by you. `init` writes `docker-compose.yml` in the current directory from `src/helm/core/compose.template.yml`, writes `state/.env.docker` with mode `0600` (including `INDEXER_MANAGER` for the containers), reads the Jackett and Prowlarr API keys, and creates the `helm-torrent.sh` launcher in one-shot mode. The CLI container gets your config directory, so `config.toml` and `config.jsonc` work there too. Set `COMPOSE_PROJECT_NAME` to change the container name prefix (default `helm`), `HELM_IMAGE` to use another image, or `HELM_SETUP_RUNNER=helm-torrent` to run `init` on the host instead of in the image. +`setup.sh` only handles the host: the container engine, native installs and the optional systemd unit. It then pulls `ghcr.io/piratebird/helm` and runs `helm-torrent init` inside it, with the engine socket and your directories mounted at the same paths, so the files it writes are owned by you. `init` writes `docker-compose.yml` in the current directory from `src/helm/stack/compose.template.yml`, writes `state/.env.docker` with mode `0600` (including `INDEXER_MANAGER` for the containers), reads the Jackett and Prowlarr API keys, and creates the `helm-torrent.sh` launcher in one-shot mode. The CLI container gets your config directory, so `config.toml` and `config.jsonc` work there too. Set `COMPOSE_PROJECT_NAME` to change the container name prefix (default `helm`), `HELM_IMAGE` to use another image, or `HELM_SETUP_RUNNER=helm-torrent` to run `init` on the host instead of in the image.
@@ -304,7 +304,7 @@ Host downloads, user plugins, source files, images, and Kubernetes Helm configur The generated Compose configuration declares per-service CPU and memory limits. Enforcement depends on the container engine and host cgroup configuration; verify the limits on your deployment. One-shot mode stops service containers after use, while the container engine, filesystem cache, and other host processes may remain active. -The [resource benchmark report](docs/BENCHMARK.md) includes a tested harness, raw PSS samples, and three verified local search/download trials at each of two concurrency settings. It separates these measurements from unverified historical container figures. Run `python -m helm.core.benchmark --help` for reproduction options. +The [resource benchmark report](docs/BENCHMARK.md) includes a tested harness, raw PSS samples, and three verified local search/download trials at each of two concurrency settings. It separates these measurements from unverified historical container figures. Run `python -m helm.benchmarks.benchmark --help` for reproduction options. ## Disclaimer diff --git a/docs/BENCHMARK.md b/docs/BENCHMARK.md index 5fc7411..a936d0e 100644 --- a/docs/BENCHMARK.md +++ b/docs/BENCHMARK.md @@ -2,7 +2,7 @@ ## Reproducible local workload (October 2026) -The tested harness is [benchmark.py](../src/helm/core/benchmark.py). Its [raw samples](benchmarks/local-loopback.json) record three trials at six-worker concurrency, per-sample PSS, phase events, checksums, source SHA-256 fingerprints, the base Git revision and dirty-tree status, Python/kernel/CPU details, and whether engine overhead was included. +The tested harness is [benchmark.py](../src/helm/benchmarks/benchmark.py). Its [raw samples](benchmarks/local-loopback.json) record three trials at six-worker concurrency, per-sample PSS, phase events, checksums, source SHA-256 fingerprints, the base Git revision and dirty-tree status, Python/kernel/CPU details, and whether engine overhead was included. Measured environment: **11th Gen Intel(R) Core(TM) i5-1135G7 @ 2.40GHz**, 8 logical CPUs, Linux kernel `7.2.11`, Python `3.14.8`, libtorrent `2.0.11.0`. These measurements were taken from an uncommitted working tree; source hashes identify the measured implementation. @@ -35,7 +35,7 @@ Two workers reduced the observed peak memory at the cost of a longer fixture sea ## Production stack (November 2026) -[stack_benchmark.py](../src/helm/core/stack_benchmark.py) starts Jackett, Prowlarr, qBittorrent and FlareSolverr in a disposable project, using the same image IDs on both engines. A generated indexer page is searched through Prowlarr and Jackett, then qBittorrent downloads a generated 16 MiB payload from a local seeder and its SHA-256 is verified. The raw samples are in [stack-docker.json](benchmarks/stack-docker.json) and [stack-podman.json](benchmarks/stack-podman.json). +[stack_benchmark.py](../src/helm/benchmarks/stack_benchmark.py) starts Jackett, Prowlarr, qBittorrent and FlareSolverr in a disposable project, using the same image IDs on both engines. A generated indexer page is searched through Prowlarr and Jackett, then qBittorrent downloads a generated 16 MiB payload from a local seeder and its SHA-256 is verified. The raw samples are in [stack-docker.json](benchmarks/stack-docker.json) and [stack-podman.json](benchmarks/stack-podman.json). Each engine completed three trials. Effective cgroup limits matched the request on every service: 256 MiB and 0.5 CPU, or 512 MiB and 0.5 CPU for FlareSolverr. All containers stopped, and cleanup reported no errors. @@ -51,19 +51,19 @@ Do not read these runs as a Docker-versus-Podman ranking. The engines ran one af The default image IDs exist only on the host that recorded them. Elsewhere, pass `--image-manifest images.json` or `--image service=reference`: ```bash -PYTHONPATH=src python -m helm.core.stack_benchmark --engine docker --output docs/benchmarks/stack-docker.json --repeats 3 +PYTHONPATH=src python -m helm.benchmarks.stack_benchmark --engine docker --output docs/benchmarks/stack-docker.json --repeats 3 ``` ## Run the harness ```bash python -m pip install -e '.[dev,download]' -PYTHONPATH=src python -m helm.core.benchmark --output docs/benchmarks/local-loopback.json --repeats 3 --search-workers 6 -PYTHONPATH=src python -m helm.core.benchmark --output docs/benchmarks/local-loopback-workers2.json --repeats 3 --search-workers 2 +PYTHONPATH=src python -m helm.benchmarks.benchmark --output docs/benchmarks/local-loopback.json --repeats 3 --search-workers 6 +PYTHONPATH=src python -m helm.benchmarks.benchmark --output docs/benchmarks/local-loopback-workers2.json --repeats 3 --search-workers 2 # Optional: sample an ALREADY RUNNING stack and shared engine processes. # This does not start, stop, configure, or download through the attached stack. -PYTHONPATH=src python -m helm.core.benchmark --output /tmp/helm-attached.json --engine docker --project helm --include-engine +PYTHONPATH=src python -m helm.benchmarks.benchmark --output /tmp/helm-attached.json --engine docker --project helm --include-engine python -m pytest tests/test_benchmark.py tests/test_search_runner.py tests/test_scraper_fixtures.py -q ``` diff --git a/pyproject.toml b/pyproject.toml index a6c707e..b23501e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -43,7 +43,7 @@ helm-torrent = "helm.cli:main" where = ["src"] [tool.setuptools.package-data] -"helm.core" = ["compose.template.yml"] +"helm.stack" = ["compose.template.yml"] [tool.pytest.ini_options] pythonpath = ["src"] diff --git a/src/helm/benchmarks/__init__.py b/src/helm/benchmarks/__init__.py new file mode 100644 index 0000000..dd9a482 --- /dev/null +++ b/src/helm/benchmarks/__init__.py @@ -0,0 +1 @@ +"""Benchmarks and device profiling.""" diff --git a/src/helm/core/benchmark.py b/src/helm/benchmarks/benchmark.py similarity index 98% rename from src/helm/core/benchmark.py rename to src/helm/benchmarks/benchmark.py index fac245e..b4d766b 100644 --- a/src/helm/core/benchmark.py +++ b/src/helm/benchmarks/benchmark.py @@ -19,7 +19,7 @@ import time from pathlib import Path -from helm.core.runtime import child_environment +from helm.services.runtime import child_environment ENGINE_NAMES = {"dockerd", "containerd", "conmon", "pasta", "slirp4netns", "rootlesskit"} @@ -214,8 +214,8 @@ def binding_version(binding): def workload(payload_bytes, timeout, fixture_plugins=12, fixture_results=100, search_workers=6): - from helm.core.lite_plugin_loader import plugin_jobs - from helm.core.search_runner import run_searches + from helm.search.lite_plugin_loader import plugin_jobs + from helm.search.search_runner import run_searches with tempfile.TemporaryDirectory(prefix="helm-benchmark-workload-") as temporary: directory = Path(temporary) @@ -271,7 +271,7 @@ def run_trial( [ sys.executable, "-m", - "helm.core.benchmark", + "helm.benchmarks.benchmark", "--worker", str(payload_bytes), str(timeout), @@ -285,7 +285,7 @@ def run_trial( env=environment, start_new_session=True, ) - from helm.core.search_runner import stop_worker + from helm.search.search_runner import stop_worker samples, events = [], [] current = "startup" diff --git a/src/helm/core/device_profile.py b/src/helm/benchmarks/device_profile.py similarity index 97% rename from src/helm/core/device_profile.py rename to src/helm/benchmarks/device_profile.py index 1df6756..498d540 100644 --- a/src/helm/core/device_profile.py +++ b/src/helm/benchmarks/device_profile.py @@ -7,9 +7,9 @@ import tempfile from pathlib import Path -from helm.core.benchmark import run_trial -from helm.core.runtime import process_alive -from helm.core.search_runner import SearchJob, run_searches +from helm.benchmarks.benchmark import run_trial +from helm.search.search_runner import SearchJob, run_searches +from helm.services.runtime import process_alive def battery_sysfs(root=Path("/sys/class/power_supply")): diff --git a/src/helm/core/stack_benchmark.py b/src/helm/benchmarks/stack_benchmark.py similarity index 99% rename from src/helm/core/stack_benchmark.py rename to src/helm/benchmarks/stack_benchmark.py index d0e1e2e..ca05d89 100644 --- a/src/helm/core/stack_benchmark.py +++ b/src/helm/benchmarks/stack_benchmark.py @@ -18,9 +18,9 @@ import requests -from helm.core.benchmark import container_metadata -from helm.core.secret_manager import redact_text -from helm.core.torrent_links import metadata_source +from helm.benchmarks.benchmark import container_metadata +from helm.config.secret_manager import redact_text +from helm.torrents.torrent_links import metadata_source DEFAULT_IMAGES = { "jackett": "sha256:d39ca96018ff40dc20730d80f96195a784ec71b1fb647b86a6db1d01431c85c5", diff --git a/src/helm/cli.py b/src/helm/cli.py deleted file mode 100644 index 4b5a0ab..0000000 --- a/src/helm/cli.py +++ /dev/null @@ -1,833 +0,0 @@ -import argparse -import importlib -import json -import os -import re -import shutil -import subprocess -import sys -import time - -from dotenv import load_dotenv - -from helm.core.config_manager import CONTENT_PROFILES, NEGATIVE_KEYWORDS, worker_count # noqa: E402 -from helm.core.logger import configure_logging, tail_log # noqa: E402 -from helm.core.secret_manager import get_secret, get_secrets_file # noqa: E402 -from helm.core.settings import ConfigError, load_settings, remember # noqa: E402 -from helm.ui.ansi import T # noqa: E402 -from helm.ui.banner import WORDMARK as logo # noqa: E402 - - -def _lazy(module, name): - """Defer a heavy import so --help and headless commands start quickly.""" - - def call(*args, **kwargs): - return getattr(importlib.import_module(module), name)(*args, **kwargs) - - return call - - -add_magnet = _lazy("helm.core.qbittorrent_client", "add_magnet") -animated_search = _lazy("helm.ui.tui", "animated_search") -dedupe = _lazy("helm.core.torrent_filter", "dedupe") -ensure_config = _lazy("helm.core.config_wizard", "ensure_config") -filter_items = _lazy("helm.core.torrent_filter", "filter_items") -interactive_indexer_selector = _lazy("helm.ui.tui", "interactive_indexer_selector") -interactive_selector = _lazy("helm.ui.tui", "interactive_selector") -wait_for_download = _lazy("helm.core.oneshot", "wait_for_download") - - -def _send_magnet(selected, lite_mode, json_mode=False, success_msg="Torrent sent successfully :)"): - """Send a torrent to qBittorrent, falling back to the built-in downloader if it is unavailable.""" - if lite_mode: - from helm.core.lite_downloader import download_magnet - - return download_magnet(selected.link) - - try: - add_magnet(selected.link) - if not json_mode: - print(f"{T.TEXT}{success_msg}{T.RST}") - except Exception as e: - print( - f"\n{T.WARNING}[!] qBittorrent not available ({e}). Falling back to LITE MODE downloader...{T.RST}\n", - file=sys.stderr, - ) - from helm.core.lite_downloader import download_magnet - - return download_magnet(selected.link) - return True - - -def _cmd_status(): - """Print running helm containers and the configured Web UI URLs (never prompts).""" - print("Checking container status and Web UIs...") - cmd_runner = "docker" if shutil.which("docker") else "podman" if shutil.which("podman") else None - res = None - if cmd_runner: - cmd = [cmd_runner, "ps", "--format", "{{.Names}}: {{.Status}}"] - try: - res = subprocess.run(cmd, check=True, capture_output=True, text=True) - except Exception: - print(f"Failed to run {cmd_runner} ps.") - else: - print("Native Mode - No containers running.") - - if res is not None: - print("-" * 40) - helm_containers = [line for line in res.stdout.splitlines() if "helm" in line.lower()] - print("\n".join(helm_containers) if helm_containers else "No helm containers found.") - print("-" * 40) - - settings = load_settings() - container_text = (res.stdout or "").lower() if res else "" - print("\n--- Web UIs ---") - if container_text and "jackett" not in container_text: - print("Jackett: not running") - else: - print(f"Jackett: {settings.get('services.jackett')}") - if container_text and "prowlarr" not in container_text: - print("Prowlarr: not running") - else: - print(f"Prowlarr: {settings.get('services.prowlarr')}") - if container_text and "qbittorrent" not in container_text: - print("qBittorrent: not running") - else: - print(f"qBittorrent: {settings.get('services.qbittorrent')}") - print("---------------") - - -def build_parser(): - base_parser = argparse.ArgumentParser(add_help=False) - global_opts = base_parser.add_argument_group("Global Options") - global_opts.add_argument( - "--config-dir", type=str, default=argparse.SUPPRESS, help="Override the configuration directory" - ) - global_opts.add_argument("--state-dir", type=str, default=argparse.SUPPRESS, help="Override the state directory") - global_opts.add_argument( - "--daemon", - action="store_true", - default=argparse.SUPPRESS, - help="Run a headless command in the background, or start a detached tmux UI", - ) - global_opts.add_argument( - "--session", default=argparse.SUPPRESS, help="Create a named reconnectable tmux UI session" - ) - global_opts.add_argument("--status", action="store_true", help="List running containers and their Web UI URLs") - global_opts.add_argument("--dl-dir", type=str, default=argparse.SUPPRESS, help="Override the downloads directory") - global_opts.add_argument( - "--lite-workers", - type=int, - choices=range(1, 13), - default=argparse.SUPPRESS, - help="Maximum concurrent Lite processes (default: HELM_LITE_WORKERS or 6)", - ) - global_opts.add_argument( - "-o", - "--oneshot", - action="store_true", - default=argparse.SUPPRESS, - help="One-shot mode: start stack, download, tear down", - ) - global_opts.add_argument( - "-l", - "--lite", - action="store_true", - default=argparse.SUPPRESS, - help="Lite mode: bypass Jackett and use public trackers", - ) - global_opts.add_argument( - "-j", "--json", action="store_true", default=argparse.SUPPRESS, help="Output results as JSON" - ) - - parser = argparse.ArgumentParser( - prog="helm-torrent", - description="The Helm - Torrent automation CLI", - formatter_class=argparse.RawTextHelpFormatter, - parents=[base_parser], - ) - - subparsers = parser.add_subparsers(dest="command", title="Commands", metavar="") - - # UI - # Init - init_parser = subparsers.add_parser( - "init", help="Set up the container stack: compose file, .env.docker, API keys", parents=[base_parser] - ) - from helm.core.stack_setup import add_arguments as add_init_arguments - - add_init_arguments(init_parser) - - # UI - subparsers.add_parser( - "ui", help="Launch the interactive terminal UI (Default if no command given)", parents=[base_parser] - ) - - # Search - search_parser = subparsers.add_parser( - "search", help="Search and download via CLI flags without TUI", parents=[base_parser] - ) - search_parser.add_argument("query", type=str, nargs="+", help="Search query") - search_parser.add_argument( - "-t", "--type", type=str.lower, choices=sorted(CONTENT_PROFILES), default="video", help="Content type" - ) - search_parser.add_argument( - "-a", "--auto", action="store_true", help="Automatically select and send the top torrent" - ) - - # Indexers - idx_parser = subparsers.add_parser("indexers", help="Manage Indexers interactively", parents=[base_parser]) - idx_parser.add_argument("--prowlarr", action="store_true", help="Manage Prowlarr indexers explicitly") - idx_parser.add_argument("--jackett", action="store_true", help="Manage Jackett indexers explicitly") - - # Utility Commands - subparsers.add_parser("status", help="List running containers and their Web UI URLs", parents=[base_parser]) - subparsers.add_parser("logs", help="Tail the last 20 lines of the application log", parents=[base_parser]) - subparsers.add_parser( - "paths", help="Print all system data locations (Config, State, Downloads)", parents=[base_parser] - ) - subparsers.add_parser( - "bug-report", help="Zip the config and logs to the Desktop for reporting", parents=[base_parser] - ) - - download_parser = subparsers.add_parser( - "download", help="Download a magnet, detail URL or .torrent file", parents=[base_parser] - ) - download_parser.add_argument("source") - watch_parser = subparsers.add_parser( - "watch", help="Queue stable .torrent and magnet files from a directory", parents=[base_parser] - ) - watch_parser.add_argument("directory") - watch_parser.add_argument("--interval", type=float, default=1) - watch_parser.add_argument("--once", action="store_true", help="Scan once and submit queued downloads") - watch_parser.add_argument( - "--enqueue-only", action="store_true", help="Leave processing to a running serve/watch worker" - ) - for name in ("serve", "files"): - service_parser = subparsers.add_parser( - name, - help="Authenticated job API and completed-file streaming" - if name == "serve" - else "Read-only completed-file server", - parents=[base_parser], - ) - service_parser.add_argument("--host", default="127.0.0.1") - service_parser.add_argument("--port", type=int, default=8765) - attach_parser = subparsers.add_parser("attach", help="Reconnect to a named tmux UI", parents=[base_parser]) - attach_parser.add_argument("name", nargs="?", default="main") - daemon_parser = subparsers.add_parser( - "daemon", help="List or stop managed background commands", parents=[base_parser] - ) - daemon_parser.add_argument("action", choices=["status", "stop"]) - daemon_parser.add_argument("id", nargs="?") - - subparsers.add_parser("banner", help="Print the banner, even when banner.enabled is false", parents=[base_parser]) - - from helm.core.config_commands import add_parser as add_config_parser - - add_config_parser(subparsers, [base_parser]) - - return parser - - -def _parse_args(parser): - args = parser.parse_args() - if getattr(args, "status", False): - args.command = "status" - - if not args.command: - args.command = "ui" - - if not hasattr(args, "lite"): - args.lite = False - if not hasattr(args, "json"): - args.json = False - if not hasattr(args, "oneshot"): - args.oneshot = False - - if args.command == "search": - args.query = " ".join(args.query).strip() - if not args.query: - parser.error("search query must not be empty") - else: - args.query = None - args.type = "video" - args.auto = False - - if args.command not in ("ui", "search", "indexers"): - args.oneshot = False - - if getattr(args, "config_dir", None): - os.environ["HELM_CONFIG_DIR"] = os.path.abspath(args.config_dir) - if getattr(args, "state_dir", None): - os.environ["HELM_STATE_DIR"] = os.path.abspath(args.state_dir) - if getattr(args, "dl_dir", None): - os.environ["HELM_DL_DIR"] = os.path.abspath(args.dl_dir) - - # Config commands must run on a broken file and report true origins, and setup - # must not stop on one, so they neither load settings early nor export the - # worker count. - if args.command not in ("config", "init"): - requested = getattr(args, "lite_workers", None) - if requested is None and "HELM_LITE_WORKERS" not in os.environ: - requested = load_settings().get("search.lite_workers") - try: - workers = worker_count(requested) - except ValueError as error: - parser.error(str(error)) - os.environ["HELM_LITE_WORKERS"] = str(workers) - - load_dotenv(get_secrets_file()) - configure_logging() - return args - - -def _dispatch_background(args, parser): - """Handle tmux and daemon management commands; return True when one ran.""" - daemon_mode = getattr(args, "daemon", False) - session = getattr(args, "session", None) - if args.command == "attach": - from helm.core.runtime import attach_session - - attach_session(args.name) - return True - if args.command == "daemon": - from helm.core.runtime import daemon_records, stop_daemon - - if args.action == "status": - print(json.dumps(daemon_records(), indent=2)) - elif not args.id: - parser.error("daemon stop requires an id") - else: - print(json.dumps({"stopped": stop_daemon(args.id)})) - return True - if session or (daemon_mode and args.command == "ui"): - if args.command not in ("ui", "indexers"): - parser.error("--session is supported for ui/indexers; headless commands use --daemon") - from helm.core.runtime import start_session - - start_session(session or "main", sys.argv[1:]) - return True - if daemon_mode: - if args.command not in ("search", "download", "watch", "serve", "files"): - parser.error("--daemon requires a headless command or ui") - if args.command == "search" and not (args.auto or args.json): - parser.error("background searches require --auto or --json") - from helm.core.runtime import start_daemon - - start_daemon(sys.argv[1:]) - return True - return False - - -def _run_download(source, lite): - """Run one queued download, also waiting if a service worker already owns it.""" - from helm.core.jobs import JobStore, process_one - - store = JobStore() - job = store.enqueue(source, lite) - while store.get(job["id"])["status"] in ("pending", "running"): - if not process_one(store): - time.sleep(1) - final = store.get(job["id"]) - print(json.dumps({"id": final["id"], "status": final["status"], "error": final["error"]})) - return 0 if final["status"] in ("succeeded", "submitted") else 1 - - -def _run_headless(args, parser): - settings = load_settings() - lite = args.lite or settings.get("search.lite_only") - if not lite and not (get_secret("QB_PASSWORD") or settings.origin("services.qbittorrent") != "default"): - lite = True - if args.command == "watch": - from helm.core.watch import run_watch - - return run_watch(args.directory, lite, args.interval, args.once, args.enqueue_only) - if args.command in ("serve", "files"): - if not 0 <= args.port <= 65535: - parser.error("port must be between 0 and 65535") - from helm.core.server import run_server - - return run_server(args.host, args.port, lite, read_only=args.command == "files") - return _run_download(args.source, lite) - - -def _run_utility(command): - if command == "paths": - from helm.core.config_manager import get_config_dir, get_dl_dir, get_log_dir - - print(f"{T.BOLD}{T.INFO}Helm Data Locations:{T.RST}") - print(f" Configuration: {get_config_dir()}") - print(f" State/Logs: {get_log_dir()}") - print(f" Downloads: {get_dl_dir()}") - return - - if command == "logs": - from helm.core.config_manager import get_log_dir - - log_file = os.path.join(get_log_dir(), "helm.log") - if os.path.exists(log_file): - print("--- Last 20 lines ---") - try: - sys.stdout.write(tail_log(log_file)) - print("\n---------------------") - except Exception as e: - print(f"Could not read log file: {e}") - else: - print("Log file does not exist yet.") - return - - if command == "bug-report": - import zipfile - - from helm.core.config_manager import get_log_dir - from helm.core.settings import read_file, report_config_file - - desktop = os.path.join(os.path.expanduser("~"), "Desktop") - if not os.path.exists(desktop): - desktop = os.path.expanduser("~") - zip_path = os.path.join(desktop, "helm-bug-report.zip") - config_file = report_config_file() - log_file = os.path.join(get_log_dir(), "helm.log") - - with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zipf: - if os.path.exists(config_file): - from helm.core.secret_manager import redact_config - - try: - zipf.writestr("config.json", json.dumps(redact_config(read_file(config_file)), indent=4)) - except Exception: - print("Could not redact the config; omitting it from the bug report.", file=sys.stderr) - if os.path.exists(log_file): - from helm.core.secret_manager import redact_text - - with open(log_file, "r", encoding="utf-8", errors="replace") as source, zipf.open( - "helm.log", "w" - ) as target: - for line in source: - target.write(redact_text(line).encode("utf-8")) - print(f"Bug report successfully created at: {zip_path}") - print("Please attach this zip file when creating an issue on GitHub.") - return - - -def _banner_context(args): - if args.lite: - return {"mode": "lite"} - if args.oneshot: - return {"mode": "one-shot"} - return {} - - -def _cmd_banner(args): - from helm.ui.ansi import color_enabled, render_banner - from helm.ui.banner import build_banner - from helm.ui.theme import load_theme - - settings = load_settings() - banner = build_banner(settings, _banner_context(args)) - if args.json: - data = { - "theme": settings.get("theme.preset"), - "logo": ["".join(text for _color, text in line) for line in banner.logo], - "modules": [entry.__dict__ for entry in banner.entries], - } - print(json.dumps(data, ensure_ascii=False)) - return - sys.stdout.write(render_banner(banner, load_theme(settings), color=color_enabled(sys.stdout))) - - -def _print_header(args, subtitle): - """Print the banner at UI start, or the plain wordmark when banner.enabled is false.""" - settings = load_settings() - if settings.get("banner.enabled"): - from helm.ui.ansi import color_enabled, render_banner - from helm.ui.banner import build_banner - from helm.ui.theme import load_theme - - banner = build_banner(settings, _banner_context(args)) - sys.stdout.write("\n" + render_banner(banner, load_theme(settings), color=color_enabled(sys.stdout)) + "\n") - else: - print(f"{T.LOGO}{logo}{T.RST}") - print(f"{T.ACCENT}{subtitle}{T.RST}\n") - - -def main(): - """Console entry point. It bypasses the __main__ block below.""" - try: - run() - except ConfigError as error: - print(f"{T.ERROR}[!] {error}{T.RST}", file=sys.stderr) - raise SystemExit(1) from None - - -def run(): - parser = build_parser() - args = _parse_args(parser) - if _dispatch_background(args, parser): - return - if args.command == "config": - from helm.core.config_commands import run as run_config - - raise SystemExit(run_config(args)) - if args.command == "banner": - _cmd_banner(args) - return - if args.command in ("watch", "serve", "files", "download"): - raise SystemExit(_run_headless(args, parser)) - - if args.command == "status": - # Container status is a read-only query: it must never spin up the - # ephemeral stack, prompt for config, or require an API key. Reap it - # as early as possible so agents can call it non-interactively. - _cmd_status() - return - - if args.command == "init": - from helm.core.stack_setup import main as setup_main - - try: - status = setup_main(args) - except KeyboardInterrupt: - print(f"\n{T.ACCENT}later bozo!{T.RST}") - status = 130 - raise SystemExit(status) from None - - if args.command in ("paths", "logs", "bug-report"): - _run_utility(args.command) - raise SystemExit(0) from None - - if not args.lite: - if load_settings().get("search.lite_only"): - args.lite = True - elif ( - not os.getenv("JACKETT_API_KEY") - and not get_secret("JACKETT_API_KEY") - and not os.getenv("PROWLARR_API_KEY") - and not get_secret("PROWLARR_API_KEY") - ): - if args.json or os.environ.get("HELM_DAEMONIZED") == "1": - # Machine-readable output must never interleave prompts; fall - # back to Lite Mode silently instead of asking the user. - args.lite = True - remember({"search.lite_only": True}) - else: - try: - choice = ( - input( - f"\n{T.BOLD}{T.TEXT}? No configuration found. Would you like to run in Lite Mode (zero setup)? [Y/n]:{T.RST} " - ) - .strip() - .lower() - ) - if choice != "n": - args.lite = True - remember({"search.lite_only": True}) - else: - ensure_config() - except (KeyboardInterrupt, EOFError): - print(f"\n{T.ACCENT}later bozo!{T.RST}") - raise SystemExit(0) from None - else: - ensure_config() - - # Lite searches never start a container stack, even with --oneshot. - args.oneshot = args.oneshot and not args.lite - from helm.core.oneshot import spin_up_oneshot, teardown_oneshot - - started = False - - def cleanup(): - nonlocal started - if started: - started = False - teardown_oneshot() - elif not args.oneshot and not args.lite: - # Ctrl-E explicitly requests cleanup for an existing permanent stack. - teardown_oneshot() - - try: - if args.oneshot: - # Mark ownership before startup so partial startup is cleaned up too. - started = True - spin_up_oneshot() - _run_session(args, cleanup) - finally: - if started: - cleanup() - - -def _manage_indexers(args): - if args.lite: - print(f"{T.ERROR}Cannot manage Indexers in Lite Mode.{T.RST}", file=sys.stderr) - raise SystemExit(1) from None - ensure_config() - - use_prowlarr = getattr(args, "prowlarr", False) - use_jackett = getattr(args, "jackett", False) - - if not use_prowlarr and not use_jackett: - manager_type = load_settings().get("search.indexer_manager") - elif use_prowlarr: - manager_type = "prowlarr" - else: - manager_type = "jackett" - - try: - if manager_type == "prowlarr": - from helm.core.indexer_manager import ProwlarrManager - - manager = ProwlarrManager() - mgr_name = "Prowlarr" - else: - from helm.core.indexer_manager import JackettManager - - manager = JackettManager() - mgr_name = "Jackett" - except Exception as e: - print(f"{T.ERROR}Failed to initialize Manager: {e}{T.RST}", file=sys.stderr) - raise SystemExit(1) from None - - sys.stdout.write(f"{T.LOGO}Fetching indexers from {mgr_name}...{T.RST}\r\n") - sys.stdout.flush() - all_indexers = manager.get_all_indexers() - - while True: - try: - selected_indexer = interactive_indexer_selector(all_indexers) - if selected_indexer: - if selected_indexer["configured"]: - sys.stdout.write(f"\r\n{T.TEXT}Removing {selected_indexer['title']}...{T.RST}\r\n") - sys.stdout.flush() - try: - manager.remove_indexer(selected_indexer["id"]) - selected_indexer["configured"] = False - except Exception as e: - sys.stdout.write(f"\r\n{T.ERROR}Failed to remove: {e}{T.RST}\r\n") - sys.stdout.flush() - time.sleep(2) - else: - if selected_indexer.get("type", "public") != "public": - sys.stdout.write( - f"\r\n{T.ERROR}Cannot add {selected_indexer['type']} trackers via CLI as they require credentials. Please use the Jackett Web UI ({manager.url}).{T.RST}\r\n" - ) - sys.stdout.flush() - time.sleep(3) - else: - sys.stdout.write(f"\r\n{T.TEXT}Adding {selected_indexer['title']}...{T.RST}\r\n") - sys.stdout.flush() - try: - manager.add_indexer(selected_indexer["id"]) - selected_indexer["configured"] = True - except Exception as e: - error_msg = str(e) - if "500" in error_msg: - error_msg = "Jackett rejected the default config. Please configure this indexer manually via the Jackett Web UI." - sys.stdout.write(f"\r\n{T.ERROR}Failed to add: {error_msg}{T.RST}\r\n") - sys.stdout.flush() - time.sleep(3) - except KeyboardInterrupt: - sys.stdout.write(f"\n{T.ACCENT}Exiting indexer management.{T.RST}\n") - sys.stdout.flush() - try: - choice = input(f"{T.BOLD}{T.TEXT}? Would you like to proceed to search? [Y/n]:{T.RST} ").strip().lower() - if choice == "n": - raise SystemExit(0) from None - except (KeyboardInterrupt, EOFError): - print(f"\n{T.ACCENT}later bozo!{T.RST}") - raise SystemExit(0) from None - - -def _run_session(args, teardown_oneshot): - if args.command == "indexers": - _manage_indexers(args) - - mode_str = " (ONE-SHOT MODE)" if args.oneshot else "" - - if not args.json and not args.query: - _print_header(args, f"THE HELM - Torrent automation MVP{mode_str}") - - # State Machine Loop - state = "PROMPT" - search_query = "" - categories = [] - filtered = [] - - while True: - if state == "PROMPT": - if args.query: - search_query = args.query - categories = [args.type.lower()] - state = "SEARCHING" - else: - try: - search_query = input(f"{T.BOLD}{T.TEXT}? What would you like to search for:{T.RST} ").strip() - except (KeyboardInterrupt, EOFError): - print(f"\n{T.ACCENT}later bozo!{T.RST}") - raise SystemExit(0) from None - - if not search_query: - continue - - from helm.ui.tui import interactive_checkbox_selector - - try: - selected_cats = interactive_checkbox_selector( - ["video", "games", "software", "books", "music"], "Content type" - ) - except KeyboardInterrupt: - print(f"\n{T.ACCENT}later bozo!{T.RST}") - raise SystemExit(0) from None - - if selected_cats == "BACK": - # Go back to query prompt by staying in PROMPT - print(f"{T.CLEAR}{T.HOME}", end="") - continue - categories = selected_cats - print(f"{T.CLEAR}{T.HOME}", end="") - state = "SEARCHING" - - elif state == "SEARCHING": - keywords = [] - negatives = [] - for cat in categories: - keywords.extend(CONTENT_PROFILES.get(cat, [])) - negatives.extend(NEGATIVE_KEYWORDS.get(cat, [])) - - # Collect profiles for scoring - cat_profiles = {cat: CONTENT_PROFILES.get(cat, []) for cat in categories} - all_positives = [kw for kws in cat_profiles.values() for kw in kws] - - # Remove selected keywords from negatives to prevent cross-cancellation - negatives = [n for n in negatives if n not in all_positives] - - query_words = set(re.findall(r"\b\w+\b", search_query.lower())) - negatives = [n for n in negatives if n.lower() not in query_words] - - # Special case for books - cleaned_query = search_query - if "books" in categories and len(categories) == 1: - cleaned_query = re.sub(r"[^\w\s]", "", search_query) - - # Pass comma-separated categories so Jackett can hit multiple endpoints - try: - all_items, args.lite = animated_search( - cleaned_query, ",".join(categories), lite_mode=args.lite, show_spinner=not args.json - ) - except KeyboardInterrupt: - print(f"\n{T.ACCENT}later bozo!{T.RST}") - raise SystemExit(0) from None - - source_name = "Lite mode" if args.lite else "Jackett & Lite" - if not args.json: - print(f"{T.LOGO}{source_name} returned {len(all_items)} raw results{T.RST}") - - min_seeds = load_settings().get("search.min_seeds") - - unique_items = dedupe(all_items) - filtered = filter_items(unique_items, cat_profiles, negatives, min_score=0, min_seeds=min_seeds) - - if not filtered: - if args.json: - print(json.dumps([])) - raise SystemExit(1) from None - else: - print(f"\n{T.ERROR}No torrents were found :({T.RST}", file=sys.stderr) - if not all_items and args.lite: - print( - "Lite sources may be unreachable or have no matches. " - "Try a specific query and check 'helm-torrent logs' for source errors.", - file=sys.stderr, - ) - elif all_items: - print( - f"All {len(all_items)} results were removed by filters " - f"(minimum seeders: {min_seeds}). Review min_seeds and content type.", - file=sys.stderr, - ) - # If we have arguments, we exit. Else we go back to prompt. - if args.query: - raise SystemExit(1) from None - else: - input("Press Enter to try again...") - print(f"{T.CLEAR}{T.HOME}", end="") - state = "PROMPT" - continue - - if args.json: - from helm.core.secret_manager import sanitize_link - - json_output = [ - { - "title": t.title, - "link": sanitize_link(t.link), - "seeders": getattr(t, "seeders", 0), - "indexer": getattr(t, "indexer", "Unknown"), - } - for t in filtered - ] - print(json.dumps(json_output, indent=2)) - sys.stdout.flush() - raise SystemExit(0) from None - - if args.auto: - selected = filtered[0] - if ( - _send_magnet(selected, args.lite, args.json, success_msg="Top torrent sent successfully :)") - is False - ): - raise SystemExit(1) - if args.oneshot and not args.lite: - wait_for_download() - raise SystemExit(0) from None - - state = "RESULTS" - - elif state == "RESULTS": - do_teardown = False - try: - media_type_str = "+".join(categories) if categories else "" - selected, do_teardown = interactive_selector( - filtered, mode_str, lite_mode=args.lite, media_type=media_type_str - ) - - if do_teardown == "BACK": - print(f"{T.CLEAR}{T.HOME}", end="") - if args.query: - # Cannot go back if started from CLI args - raise SystemExit(0) from None - state = "PROMPT" - continue - - print() - if _send_magnet(selected, args.lite, args.json) is False: - raise SystemExit(1) - if (args.oneshot or do_teardown) and not args.lite: - wait_for_download() - if not args.oneshot: - teardown_oneshot() - break - - except KeyboardInterrupt: - print(f"\n{T.ACCENT}later bozo!{T.RST}") - if do_teardown and not args.oneshot and not args.lite: - try: - teardown_oneshot() - except Exception: - pass - raise SystemExit(0) from None - - -if __name__ == "__main__": - try: - main() - except KeyboardInterrupt: - import sys - - print(f"\n{T.WARNING}[!] Process interrupted by user.{T.RST}", file=sys.stderr) - sys.exit(130) - except Exception as e: - import sys - - print(f"\n{T.ERROR}[!] An unexpected error occurred: {e}{T.RST}", file=sys.stderr) - sys.exit(1) diff --git a/src/helm/cli/__init__.py b/src/helm/cli/__init__.py new file mode 100644 index 0000000..8c150b3 --- /dev/null +++ b/src/helm/cli/__init__.py @@ -0,0 +1,6 @@ +"""helm-torrent command line. ``helm.cli:main`` is the console entry point.""" + +from helm.cli.app import main, run +from helm.cli.parser import build_parser + +__all__ = ["build_parser", "main", "run"] diff --git a/src/helm/cli/__main__.py b/src/helm/cli/__main__.py new file mode 100644 index 0000000..2810abc --- /dev/null +++ b/src/helm/cli/__main__.py @@ -0,0 +1,17 @@ +"""python -m helm.cli""" + +from helm.cli import main +from helm.ui.ansi import T + +try: + main() +except KeyboardInterrupt: + import sys + + print(f"\n{T.WARNING}[!] Process interrupted by user.{T.RST}", file=sys.stderr) + sys.exit(130) +except Exception as e: + import sys + + print(f"\n{T.ERROR}[!] An unexpected error occurred: {e}{T.RST}", file=sys.stderr) + sys.exit(1) diff --git a/src/helm/cli/app.py b/src/helm/cli/app.py new file mode 100644 index 0000000..e5eb901 --- /dev/null +++ b/src/helm/cli/app.py @@ -0,0 +1,115 @@ +"""The helm-torrent entry point: parse arguments and hand off to a command.""" + +import os +import sys + +from helm.cli import deps +from helm.cli.commands import background, banner, headless, session, status, utility +from helm.cli.parser import build_parser, parse_args +from helm.config.settings import ConfigError +from helm.ui.ansi import T + + +def main(): + """Console entry point. It bypasses helm/cli/__main__.py, which wraps it for python -m.""" + try: + run() + except ConfigError as error: + print(f"{T.ERROR}[!] {error}{T.RST}", file=sys.stderr) + raise SystemExit(1) from None + + +def run(): + parser = build_parser() + args = parse_args(parser) + if background.dispatch_background(args, parser): + return + if args.command == "config": + from helm.config.config_commands import run as run_config + + raise SystemExit(run_config(args)) + if args.command == "banner": + banner.run(args) + return + if args.command in ("watch", "serve", "files", "download"): + raise SystemExit(headless.run(args, parser)) + + if args.command == "status": + # Container status is a read-only query: it must never spin up the + # ephemeral stack, prompt for config, or require an API key. Reap it + # as early as possible so agents can call it non-interactively. + status.run() + return + + if args.command == "init": + from helm.stack.stack_setup import main as setup_main + + try: + code = setup_main(args) + except KeyboardInterrupt: + print(f"\n{T.ACCENT}later bozo!{T.RST}") + code = 130 + raise SystemExit(code) from None + + if args.command in ("paths", "logs", "bug-report"): + utility.run(args.command) + raise SystemExit(0) from None + + if not args.lite: + if deps.load_settings().get("search.lite_only"): + args.lite = True + elif ( + not os.getenv("JACKETT_API_KEY") + and not deps.get_secret("JACKETT_API_KEY") + and not os.getenv("PROWLARR_API_KEY") + and not deps.get_secret("PROWLARR_API_KEY") + ): + if args.json or os.environ.get("HELM_DAEMONIZED") == "1": + # Machine-readable output must never interleave prompts; fall + # back to Lite Mode silently instead of asking the user. + args.lite = True + deps.remember({"search.lite_only": True}) + else: + try: + choice = ( + input( + f"\n{T.BOLD}{T.TEXT}? No configuration found. Would you like to run in Lite Mode (zero setup)? [Y/n]:{T.RST} " + ) + .strip() + .lower() + ) + if choice != "n": + args.lite = True + deps.remember({"search.lite_only": True}) + else: + deps.ensure_config() + except (KeyboardInterrupt, EOFError): + print(f"\n{T.ACCENT}later bozo!{T.RST}") + raise SystemExit(0) from None + else: + deps.ensure_config() + + # Lite searches never start a container stack, even with --oneshot. + args.oneshot = args.oneshot and not args.lite + from helm.stack.oneshot import spin_up_oneshot, teardown_oneshot + + started = False + + def cleanup(): + nonlocal started + if started: + started = False + teardown_oneshot() + elif not args.oneshot and not args.lite: + # Ctrl-E explicitly requests cleanup for an existing permanent stack. + teardown_oneshot() + + try: + if args.oneshot: + # Mark ownership before startup so partial startup is cleaned up too. + started = True + spin_up_oneshot() + session.run(args, cleanup) + finally: + if started: + cleanup() diff --git a/src/helm/cli/commands/__init__.py b/src/helm/cli/commands/__init__.py new file mode 100644 index 0000000..61a80fc --- /dev/null +++ b/src/helm/cli/commands/__init__.py @@ -0,0 +1 @@ +"""One module per helm-torrent command.""" diff --git a/src/helm/cli/commands/background.py b/src/helm/cli/commands/background.py new file mode 100644 index 0000000..90a2ff7 --- /dev/null +++ b/src/helm/cli/commands/background.py @@ -0,0 +1,42 @@ +"""helm-torrent attach and daemon, plus --daemon and --session.""" + +import json +import sys + + +def dispatch_background(args, parser): + """Handle tmux and daemon management commands; return True when one ran.""" + daemon_mode = getattr(args, "daemon", False) + session = getattr(args, "session", None) + if args.command == "attach": + from helm.services.runtime import attach_session + + attach_session(args.name) + return True + if args.command == "daemon": + from helm.services.runtime import daemon_records, stop_daemon + + if args.action == "status": + print(json.dumps(daemon_records(), indent=2)) + elif not args.id: + parser.error("daemon stop requires an id") + else: + print(json.dumps({"stopped": stop_daemon(args.id)})) + return True + if session or (daemon_mode and args.command == "ui"): + if args.command not in ("ui", "indexers"): + parser.error("--session is supported for ui/indexers; headless commands use --daemon") + from helm.services.runtime import start_session + + start_session(session or "main", sys.argv[1:]) + return True + if daemon_mode: + if args.command not in ("search", "download", "watch", "serve", "files"): + parser.error("--daemon requires a headless command or ui") + if args.command == "search" and not (args.auto or args.json): + parser.error("background searches require --auto or --json") + from helm.services.runtime import start_daemon + + start_daemon(sys.argv[1:]) + return True + return False diff --git a/src/helm/cli/commands/banner.py b/src/helm/cli/commands/banner.py new file mode 100644 index 0000000..30d1c01 --- /dev/null +++ b/src/helm/cli/commands/banner.py @@ -0,0 +1,49 @@ +"""helm-torrent banner, and the header the interactive UI prints.""" + +import json +import sys + +from helm.cli import deps +from helm.ui.ansi import T +from helm.ui.banner import WORDMARK as logo + + +def banner_context(args): + if args.lite: + return {"mode": "lite"} + if args.oneshot: + return {"mode": "one-shot"} + return {} + + +def run(args): + from helm.ui.ansi import color_enabled, render_banner + from helm.ui.banner import build_banner + from helm.ui.theme import load_theme + + settings = deps.load_settings() + banner = build_banner(settings, banner_context(args)) + if args.json: + data = { + "theme": settings.get("theme.preset"), + "logo": ["".join(text for _color, text in line) for line in banner.logo], + "modules": [entry.__dict__ for entry in banner.entries], + } + print(json.dumps(data, ensure_ascii=False)) + return + sys.stdout.write(render_banner(banner, load_theme(settings), color=color_enabled(sys.stdout))) + + +def print_header(args, subtitle): + """Print the banner at UI start, or the plain wordmark when banner.enabled is false.""" + settings = deps.load_settings() + if settings.get("banner.enabled"): + from helm.ui.ansi import color_enabled, render_banner + from helm.ui.banner import build_banner + from helm.ui.theme import load_theme + + banner = build_banner(settings, banner_context(args)) + sys.stdout.write("\n" + render_banner(banner, load_theme(settings), color=color_enabled(sys.stdout)) + "\n") + else: + print(f"{T.LOGO}{logo}{T.RST}") + print(f"{T.ACCENT}{subtitle}{T.RST}\n") diff --git a/src/helm/cli/commands/headless.py b/src/helm/cli/commands/headless.py new file mode 100644 index 0000000..4a15664 --- /dev/null +++ b/src/helm/cli/commands/headless.py @@ -0,0 +1,38 @@ +"""helm-torrent download, watch, serve and files.""" + +import json +import time + +from helm.cli import deps + + +def run_download(source, lite): + """Run one queued download, also waiting if a service worker already owns it.""" + from helm.services.jobs import JobStore, process_one + + store = JobStore() + job = store.enqueue(source, lite) + while store.get(job["id"])["status"] in ("pending", "running"): + if not process_one(store): + time.sleep(1) + final = store.get(job["id"]) + print(json.dumps({"id": final["id"], "status": final["status"], "error": final["error"]})) + return 0 if final["status"] in ("succeeded", "submitted") else 1 + + +def run(args, parser): + settings = deps.load_settings() + lite = args.lite or settings.get("search.lite_only") + if not lite and not (deps.get_secret("QB_PASSWORD") or settings.origin("services.qbittorrent") != "default"): + lite = True + if args.command == "watch": + from helm.services.watch import run_watch + + return run_watch(args.directory, lite, args.interval, args.once, args.enqueue_only) + if args.command in ("serve", "files"): + if not 0 <= args.port <= 65535: + parser.error("port must be between 0 and 65535") + from helm.services.server import run_server + + return run_server(args.host, args.port, lite, read_only=args.command == "files") + return run_download(args.source, lite) diff --git a/src/helm/cli/commands/indexers.py b/src/helm/cli/commands/indexers.py new file mode 100644 index 0000000..02b13fb --- /dev/null +++ b/src/helm/cli/commands/indexers.py @@ -0,0 +1,88 @@ +"""helm-torrent indexers: add and remove Jackett or Prowlarr indexers.""" + +import sys +import time + +from helm.cli import deps +from helm.ui.ansi import T + + +def manage_indexers(args): + if args.lite: + print(f"{T.ERROR}Cannot manage Indexers in Lite Mode.{T.RST}", file=sys.stderr) + raise SystemExit(1) from None + deps.ensure_config() + + use_prowlarr = getattr(args, "prowlarr", False) + use_jackett = getattr(args, "jackett", False) + + if not use_prowlarr and not use_jackett: + manager_type = deps.load_settings().get("search.indexer_manager") + elif use_prowlarr: + manager_type = "prowlarr" + else: + manager_type = "jackett" + + try: + if manager_type == "prowlarr": + from helm.search.indexer_manager import ProwlarrManager + + manager = ProwlarrManager() + mgr_name = "Prowlarr" + else: + from helm.search.indexer_manager import JackettManager + + manager = JackettManager() + mgr_name = "Jackett" + except Exception as e: + print(f"{T.ERROR}Failed to initialize Manager: {e}{T.RST}", file=sys.stderr) + raise SystemExit(1) from None + + sys.stdout.write(f"{T.LOGO}Fetching indexers from {mgr_name}...{T.RST}\r\n") + sys.stdout.flush() + all_indexers = manager.get_all_indexers() + + while True: + try: + selected_indexer = deps.interactive_indexer_selector(all_indexers) + if selected_indexer: + if selected_indexer["configured"]: + sys.stdout.write(f"\r\n{T.TEXT}Removing {selected_indexer['title']}...{T.RST}\r\n") + sys.stdout.flush() + try: + manager.remove_indexer(selected_indexer["id"]) + selected_indexer["configured"] = False + except Exception as e: + sys.stdout.write(f"\r\n{T.ERROR}Failed to remove: {e}{T.RST}\r\n") + sys.stdout.flush() + time.sleep(2) + else: + if selected_indexer.get("type", "public") != "public": + sys.stdout.write( + f"\r\n{T.ERROR}Cannot add {selected_indexer['type']} trackers via CLI as they require credentials. Please use the Jackett Web UI ({manager.url}).{T.RST}\r\n" + ) + sys.stdout.flush() + time.sleep(3) + else: + sys.stdout.write(f"\r\n{T.TEXT}Adding {selected_indexer['title']}...{T.RST}\r\n") + sys.stdout.flush() + try: + manager.add_indexer(selected_indexer["id"]) + selected_indexer["configured"] = True + except Exception as e: + error_msg = str(e) + if "500" in error_msg: + error_msg = "Jackett rejected the default config. Please configure this indexer manually via the Jackett Web UI." + sys.stdout.write(f"\r\n{T.ERROR}Failed to add: {error_msg}{T.RST}\r\n") + sys.stdout.flush() + time.sleep(3) + except KeyboardInterrupt: + sys.stdout.write(f"\n{T.ACCENT}Exiting indexer management.{T.RST}\n") + sys.stdout.flush() + try: + choice = input(f"{T.BOLD}{T.TEXT}? Would you like to proceed to search? [Y/n]:{T.RST} ").strip().lower() + if choice == "n": + raise SystemExit(0) from None + except (KeyboardInterrupt, EOFError): + print(f"\n{T.ACCENT}later bozo!{T.RST}") + raise SystemExit(0) from None diff --git a/src/helm/cli/commands/session.py b/src/helm/cli/commands/session.py new file mode 100644 index 0000000..beb4bd8 --- /dev/null +++ b/src/helm/cli/commands/session.py @@ -0,0 +1,210 @@ +"""The interactive search session behind helm-torrent, ui and search.""" + +import json +import re +import sys + +from helm.cli import deps +from helm.cli.commands.banner import print_header +from helm.cli.commands.indexers import manage_indexers +from helm.config.config_manager import CONTENT_PROFILES, NEGATIVE_KEYWORDS +from helm.ui.ansi import T + + +def send_magnet(selected, lite_mode, json_mode=False, success_msg="Torrent sent successfully :)"): + """Send a torrent to qBittorrent, falling back to the built-in downloader if it is unavailable.""" + if lite_mode: + from helm.torrents.lite_downloader import download_magnet + + return download_magnet(selected.link) + + try: + deps.add_magnet(selected.link) + if not json_mode: + print(f"{T.TEXT}{success_msg}{T.RST}") + except Exception as e: + print( + f"\n{T.WARNING}[!] qBittorrent not available ({e}). Falling back to LITE MODE downloader...{T.RST}\n", + file=sys.stderr, + ) + from helm.torrents.lite_downloader import download_magnet + + return download_magnet(selected.link) + return True + + +def run(args, teardown_oneshot): + if args.command == "indexers": + manage_indexers(args) + + mode_str = " (ONE-SHOT MODE)" if args.oneshot else "" + + if not args.json and not args.query: + print_header(args, f"THE HELM - Torrent automation MVP{mode_str}") + + # State Machine Loop + state = "PROMPT" + search_query = "" + categories = [] + filtered = [] + + while True: + if state == "PROMPT": + if args.query: + search_query = args.query + categories = [args.type.lower()] + state = "SEARCHING" + else: + try: + search_query = input(f"{T.BOLD}{T.TEXT}? What would you like to search for:{T.RST} ").strip() + except (KeyboardInterrupt, EOFError): + print(f"\n{T.ACCENT}later bozo!{T.RST}") + raise SystemExit(0) from None + + if not search_query: + continue + + from helm.ui.tui import interactive_checkbox_selector + + try: + selected_cats = interactive_checkbox_selector( + ["video", "games", "software", "books", "music"], "Content type" + ) + except KeyboardInterrupt: + print(f"\n{T.ACCENT}later bozo!{T.RST}") + raise SystemExit(0) from None + + if selected_cats == "BACK": + # Go back to query prompt by staying in PROMPT + print(f"{T.CLEAR}{T.HOME}", end="") + continue + categories = selected_cats + print(f"{T.CLEAR}{T.HOME}", end="") + state = "SEARCHING" + + elif state == "SEARCHING": + keywords = [] + negatives = [] + for cat in categories: + keywords.extend(CONTENT_PROFILES.get(cat, [])) + negatives.extend(NEGATIVE_KEYWORDS.get(cat, [])) + + # Collect profiles for scoring + cat_profiles = {cat: CONTENT_PROFILES.get(cat, []) for cat in categories} + all_positives = [kw for kws in cat_profiles.values() for kw in kws] + + # Remove selected keywords from negatives to prevent cross-cancellation + negatives = [n for n in negatives if n not in all_positives] + + query_words = set(re.findall(r"\b\w+\b", search_query.lower())) + negatives = [n for n in negatives if n.lower() not in query_words] + + # Special case for books + cleaned_query = search_query + if "books" in categories and len(categories) == 1: + cleaned_query = re.sub(r"[^\w\s]", "", search_query) + + # Pass comma-separated categories so Jackett can hit multiple endpoints + try: + all_items, args.lite = deps.animated_search( + cleaned_query, ",".join(categories), lite_mode=args.lite, show_spinner=not args.json + ) + except KeyboardInterrupt: + print(f"\n{T.ACCENT}later bozo!{T.RST}") + raise SystemExit(0) from None + + source_name = "Lite mode" if args.lite else "Jackett & Lite" + if not args.json: + print(f"{T.LOGO}{source_name} returned {len(all_items)} raw results{T.RST}") + + min_seeds = deps.load_settings().get("search.min_seeds") + + unique_items = deps.dedupe(all_items) + filtered = deps.filter_items(unique_items, cat_profiles, negatives, min_score=0, min_seeds=min_seeds) + + if not filtered: + if args.json: + print(json.dumps([])) + raise SystemExit(1) from None + else: + print(f"\n{T.ERROR}No torrents were found :({T.RST}", file=sys.stderr) + if not all_items and args.lite: + print( + "Lite sources may be unreachable or have no matches. " + "Try a specific query and check 'helm-torrent logs' for source errors.", + file=sys.stderr, + ) + elif all_items: + print( + f"All {len(all_items)} results were removed by filters " + f"(minimum seeders: {min_seeds}). Review min_seeds and content type.", + file=sys.stderr, + ) + # If we have arguments, we exit. Else we go back to prompt. + if args.query: + raise SystemExit(1) from None + else: + input("Press Enter to try again...") + print(f"{T.CLEAR}{T.HOME}", end="") + state = "PROMPT" + continue + + if args.json: + from helm.config.secret_manager import sanitize_link + + json_output = [ + { + "title": t.title, + "link": sanitize_link(t.link), + "seeders": getattr(t, "seeders", 0), + "indexer": getattr(t, "indexer", "Unknown"), + } + for t in filtered + ] + print(json.dumps(json_output, indent=2)) + sys.stdout.flush() + raise SystemExit(0) from None + + if args.auto: + selected = filtered[0] + if send_magnet(selected, args.lite, args.json, success_msg="Top torrent sent successfully :)") is False: + raise SystemExit(1) + if args.oneshot and not args.lite: + deps.wait_for_download() + raise SystemExit(0) from None + + state = "RESULTS" + + elif state == "RESULTS": + do_teardown = False + try: + media_type_str = "+".join(categories) if categories else "" + selected, do_teardown = deps.interactive_selector( + filtered, mode_str, lite_mode=args.lite, media_type=media_type_str + ) + + if do_teardown == "BACK": + print(f"{T.CLEAR}{T.HOME}", end="") + if args.query: + # Cannot go back if started from CLI args + raise SystemExit(0) from None + state = "PROMPT" + continue + + print() + if send_magnet(selected, args.lite, args.json) is False: + raise SystemExit(1) + if (args.oneshot or do_teardown) and not args.lite: + deps.wait_for_download() + if not args.oneshot: + teardown_oneshot() + break + + except KeyboardInterrupt: + print(f"\n{T.ACCENT}later bozo!{T.RST}") + if do_teardown and not args.oneshot and not args.lite: + try: + teardown_oneshot() + except Exception: + pass + raise SystemExit(0) from None diff --git a/src/helm/cli/commands/status.py b/src/helm/cli/commands/status.py new file mode 100644 index 0000000..6eab34c --- /dev/null +++ b/src/helm/cli/commands/status.py @@ -0,0 +1,44 @@ +"""helm-torrent status: running containers and Web UI URLs.""" + +import shutil +import subprocess + +from helm.cli import deps + + +def run(): + """Print running helm containers and the configured Web UI URLs (never prompts).""" + print("Checking container status and Web UIs...") + cmd_runner = "docker" if shutil.which("docker") else "podman" if shutil.which("podman") else None + res = None + if cmd_runner: + cmd = [cmd_runner, "ps", "--format", "{{.Names}}: {{.Status}}"] + try: + res = subprocess.run(cmd, check=True, capture_output=True, text=True) + except Exception: + print(f"Failed to run {cmd_runner} ps.") + else: + print("Native Mode - No containers running.") + + if res is not None: + print("-" * 40) + helm_containers = [line for line in res.stdout.splitlines() if "helm" in line.lower()] + print("\n".join(helm_containers) if helm_containers else "No helm containers found.") + print("-" * 40) + + settings = deps.load_settings() + container_text = (res.stdout or "").lower() if res else "" + print("\n--- Web UIs ---") + if container_text and "jackett" not in container_text: + print("Jackett: not running") + else: + print(f"Jackett: {settings.get('services.jackett')}") + if container_text and "prowlarr" not in container_text: + print("Prowlarr: not running") + else: + print(f"Prowlarr: {settings.get('services.prowlarr')}") + if container_text and "qbittorrent" not in container_text: + print("qBittorrent: not running") + else: + print(f"qBittorrent: {settings.get('services.qbittorrent')}") + print("---------------") diff --git a/src/helm/cli/commands/utility.py b/src/helm/cli/commands/utility.py new file mode 100644 index 0000000..a37b5bc --- /dev/null +++ b/src/helm/cli/commands/utility.py @@ -0,0 +1,67 @@ +"""helm-torrent paths, logs and bug-report.""" + +import json +import os +import sys + +from helm.logger import tail_log +from helm.ui.ansi import T + + +def run(command): + if command == "paths": + from helm.config.config_manager import get_config_dir, get_dl_dir, get_log_dir + + print(f"{T.BOLD}{T.INFO}Helm Data Locations:{T.RST}") + print(f" Configuration: {get_config_dir()}") + print(f" State/Logs: {get_log_dir()}") + print(f" Downloads: {get_dl_dir()}") + return + + if command == "logs": + from helm.config.config_manager import get_log_dir + + log_file = os.path.join(get_log_dir(), "helm.log") + if os.path.exists(log_file): + print("--- Last 20 lines ---") + try: + sys.stdout.write(tail_log(log_file)) + print("\n---------------------") + except Exception as e: + print(f"Could not read log file: {e}") + else: + print("Log file does not exist yet.") + return + + if command == "bug-report": + import zipfile + + from helm.config.config_manager import get_log_dir + from helm.config.settings import read_file, report_config_file + + desktop = os.path.join(os.path.expanduser("~"), "Desktop") + if not os.path.exists(desktop): + desktop = os.path.expanduser("~") + zip_path = os.path.join(desktop, "helm-bug-report.zip") + config_file = report_config_file() + log_file = os.path.join(get_log_dir(), "helm.log") + + with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zipf: + if os.path.exists(config_file): + from helm.config.secret_manager import redact_config + + try: + zipf.writestr("config.json", json.dumps(redact_config(read_file(config_file)), indent=4)) + except Exception: + print("Could not redact the config; omitting it from the bug report.", file=sys.stderr) + if os.path.exists(log_file): + from helm.config.secret_manager import redact_text + + with open(log_file, "r", encoding="utf-8", errors="replace") as source, zipf.open( + "helm.log", "w" + ) as target: + for line in source: + target.write(redact_text(line).encode("utf-8")) + print(f"Bug report successfully created at: {zip_path}") + print("Please attach this zip file when creating an issue on GitHub.") + return diff --git a/src/helm/cli/deps.py b/src/helm/cli/deps.py new file mode 100644 index 0000000..01cf50b --- /dev/null +++ b/src/helm/cli/deps.py @@ -0,0 +1,42 @@ +"""Functions the commands call through this module, so tests replace them in one place. + +Heavy modules load on first call, which keeps --help and headless commands fast. +""" + +import importlib + +from helm.config.secret_manager import get_secret +from helm.config.settings import load_settings, remember + +__all__ = [ + "add_magnet", + "animated_search", + "dedupe", + "ensure_config", + "filter_items", + "get_secret", + "interactive_indexer_selector", + "interactive_selector", + "load_settings", + "remember", + "wait_for_download", +] + + +def _lazy(module, name): + """Defer a heavy import so --help and headless commands start quickly.""" + + def call(*args, **kwargs): + return getattr(importlib.import_module(module), name)(*args, **kwargs) + + return call + + +add_magnet = _lazy("helm.torrents.qbittorrent_client", "add_magnet") +animated_search = _lazy("helm.ui.tui", "animated_search") +dedupe = _lazy("helm.search.torrent_filter", "dedupe") +ensure_config = _lazy("helm.config.config_wizard", "ensure_config") +filter_items = _lazy("helm.search.torrent_filter", "filter_items") +interactive_indexer_selector = _lazy("helm.ui.tui", "interactive_indexer_selector") +interactive_selector = _lazy("helm.ui.tui", "interactive_selector") +wait_for_download = _lazy("helm.stack.oneshot", "wait_for_download") diff --git a/src/helm/cli/parser.py b/src/helm/cli/parser.py new file mode 100644 index 0000000..ef7685a --- /dev/null +++ b/src/helm/cli/parser.py @@ -0,0 +1,196 @@ +"""Argument parsing for helm-torrent.""" + +import argparse +import os + +from dotenv import load_dotenv + +from helm.cli import deps +from helm.config.config_manager import CONTENT_PROFILES, worker_count +from helm.config.secret_manager import get_secrets_file +from helm.logger import configure_logging + + +def build_parser(): + base_parser = argparse.ArgumentParser(add_help=False) + global_opts = base_parser.add_argument_group("Global Options") + global_opts.add_argument( + "--config-dir", type=str, default=argparse.SUPPRESS, help="Override the configuration directory" + ) + global_opts.add_argument("--state-dir", type=str, default=argparse.SUPPRESS, help="Override the state directory") + global_opts.add_argument( + "--daemon", + action="store_true", + default=argparse.SUPPRESS, + help="Run a headless command in the background, or start a detached tmux UI", + ) + global_opts.add_argument( + "--session", default=argparse.SUPPRESS, help="Create a named reconnectable tmux UI session" + ) + global_opts.add_argument("--status", action="store_true", help="List running containers and their Web UI URLs") + global_opts.add_argument("--dl-dir", type=str, default=argparse.SUPPRESS, help="Override the downloads directory") + global_opts.add_argument( + "--lite-workers", + type=int, + choices=range(1, 13), + default=argparse.SUPPRESS, + help="Maximum concurrent Lite processes (default: HELM_LITE_WORKERS or 6)", + ) + global_opts.add_argument( + "-o", + "--oneshot", + action="store_true", + default=argparse.SUPPRESS, + help="One-shot mode: start stack, download, tear down", + ) + global_opts.add_argument( + "-l", + "--lite", + action="store_true", + default=argparse.SUPPRESS, + help="Lite mode: bypass Jackett and use public trackers", + ) + global_opts.add_argument( + "-j", "--json", action="store_true", default=argparse.SUPPRESS, help="Output results as JSON" + ) + + parser = argparse.ArgumentParser( + prog="helm-torrent", + description="The Helm - Torrent automation CLI", + formatter_class=argparse.RawTextHelpFormatter, + parents=[base_parser], + ) + + subparsers = parser.add_subparsers(dest="command", title="Commands", metavar="") + + # UI + # Init + init_parser = subparsers.add_parser( + "init", help="Set up the container stack: compose file, .env.docker, API keys", parents=[base_parser] + ) + from helm.stack.stack_setup import add_arguments as add_init_arguments + + add_init_arguments(init_parser) + + # UI + subparsers.add_parser( + "ui", help="Launch the interactive terminal UI (Default if no command given)", parents=[base_parser] + ) + + # Search + search_parser = subparsers.add_parser( + "search", help="Search and download via CLI flags without TUI", parents=[base_parser] + ) + search_parser.add_argument("query", type=str, nargs="+", help="Search query") + search_parser.add_argument( + "-t", "--type", type=str.lower, choices=sorted(CONTENT_PROFILES), default="video", help="Content type" + ) + search_parser.add_argument( + "-a", "--auto", action="store_true", help="Automatically select and send the top torrent" + ) + + # Indexers + idx_parser = subparsers.add_parser("indexers", help="Manage Indexers interactively", parents=[base_parser]) + idx_parser.add_argument("--prowlarr", action="store_true", help="Manage Prowlarr indexers explicitly") + idx_parser.add_argument("--jackett", action="store_true", help="Manage Jackett indexers explicitly") + + # Utility Commands + subparsers.add_parser("status", help="List running containers and their Web UI URLs", parents=[base_parser]) + subparsers.add_parser("logs", help="Tail the last 20 lines of the application log", parents=[base_parser]) + subparsers.add_parser( + "paths", help="Print all system data locations (Config, State, Downloads)", parents=[base_parser] + ) + subparsers.add_parser( + "bug-report", help="Zip the config and logs to the Desktop for reporting", parents=[base_parser] + ) + + download_parser = subparsers.add_parser( + "download", help="Download a magnet, detail URL or .torrent file", parents=[base_parser] + ) + download_parser.add_argument("source") + watch_parser = subparsers.add_parser( + "watch", help="Queue stable .torrent and magnet files from a directory", parents=[base_parser] + ) + watch_parser.add_argument("directory") + watch_parser.add_argument("--interval", type=float, default=1) + watch_parser.add_argument("--once", action="store_true", help="Scan once and submit queued downloads") + watch_parser.add_argument( + "--enqueue-only", action="store_true", help="Leave processing to a running serve/watch worker" + ) + for name in ("serve", "files"): + service_parser = subparsers.add_parser( + name, + help="Authenticated job API and completed-file streaming" + if name == "serve" + else "Read-only completed-file server", + parents=[base_parser], + ) + service_parser.add_argument("--host", default="127.0.0.1") + service_parser.add_argument("--port", type=int, default=8765) + attach_parser = subparsers.add_parser("attach", help="Reconnect to a named tmux UI", parents=[base_parser]) + attach_parser.add_argument("name", nargs="?", default="main") + daemon_parser = subparsers.add_parser( + "daemon", help="List or stop managed background commands", parents=[base_parser] + ) + daemon_parser.add_argument("action", choices=["status", "stop"]) + daemon_parser.add_argument("id", nargs="?") + + subparsers.add_parser("banner", help="Print the banner, even when banner.enabled is false", parents=[base_parser]) + + from helm.config.config_commands import add_parser as add_config_parser + + add_config_parser(subparsers, [base_parser]) + + return parser + + +def parse_args(parser): + args = parser.parse_args() + if getattr(args, "status", False): + args.command = "status" + + if not args.command: + args.command = "ui" + + if not hasattr(args, "lite"): + args.lite = False + if not hasattr(args, "json"): + args.json = False + if not hasattr(args, "oneshot"): + args.oneshot = False + + if args.command == "search": + args.query = " ".join(args.query).strip() + if not args.query: + parser.error("search query must not be empty") + else: + args.query = None + args.type = "video" + args.auto = False + + if args.command not in ("ui", "search", "indexers"): + args.oneshot = False + + if getattr(args, "config_dir", None): + os.environ["HELM_CONFIG_DIR"] = os.path.abspath(args.config_dir) + if getattr(args, "state_dir", None): + os.environ["HELM_STATE_DIR"] = os.path.abspath(args.state_dir) + if getattr(args, "dl_dir", None): + os.environ["HELM_DL_DIR"] = os.path.abspath(args.dl_dir) + + # Config commands must run on a broken file and report true origins, and setup + # must not stop on one, so they neither load settings early nor export the + # worker count. + if args.command not in ("config", "init"): + requested = getattr(args, "lite_workers", None) + if requested is None and "HELM_LITE_WORKERS" not in os.environ: + requested = deps.load_settings().get("search.lite_workers") + try: + workers = worker_count(requested) + except ValueError as error: + parser.error(str(error)) + os.environ["HELM_LITE_WORKERS"] = str(workers) + + load_dotenv(get_secrets_file()) + configure_logging() + return args diff --git a/src/helm/config/__init__.py b/src/helm/config/__init__.py new file mode 100644 index 0000000..96b5c3a --- /dev/null +++ b/src/helm/config/__init__.py @@ -0,0 +1 @@ +"""Settings, config files, secrets and the setup wizard.""" diff --git a/src/helm/core/config_commands.py b/src/helm/config/config_commands.py similarity index 98% rename from src/helm/core/config_commands.py rename to src/helm/config/config_commands.py index 7ae2f70..55a1552 100644 --- a/src/helm/core/config_commands.py +++ b/src/helm/config/config_commands.py @@ -15,9 +15,9 @@ import urllib.request from urllib.parse import urlsplit, urlunsplit -from helm.core.config_manager import get_config_dir, get_dl_dir, get_state_dir -from helm.core.secret_manager import get_secrets_file -from helm.core.settings import ( +from helm.config.config_manager import get_config_dir, get_dl_dir, get_state_dir +from helm.config.secret_manager import get_secrets_file +from helm.config.settings import ( FIELDS, USER_FILES, ConfigError, diff --git a/src/helm/core/config_manager.py b/src/helm/config/config_manager.py similarity index 100% rename from src/helm/core/config_manager.py rename to src/helm/config/config_manager.py diff --git a/src/helm/core/config_wizard.py b/src/helm/config/config_wizard.py similarity index 98% rename from src/helm/core/config_wizard.py rename to src/helm/config/config_wizard.py index 3c2e093..c53a28b 100644 --- a/src/helm/core/config_wizard.py +++ b/src/helm/config/config_wizard.py @@ -3,8 +3,8 @@ import requests -from helm.core.secret_manager import get_secret, set_secrets -from helm.core.settings import load_settings, remember +from helm.config.secret_manager import get_secret, set_secrets +from helm.config.settings import load_settings, remember from helm.ui.ansi import T @@ -262,7 +262,7 @@ def ensure_config(): os.environ[variable] = settings.get(path) # Push all resolved secrets into the environment so native modules can use them. - from helm.core.config_manager import SECRET_KEYS + from helm.config.config_manager import SECRET_KEYS for k in SECRET_KEYS: value = get_secret(k) diff --git a/src/helm/core/secret_manager.py b/src/helm/config/secret_manager.py similarity index 98% rename from src/helm/core/secret_manager.py rename to src/helm/config/secret_manager.py index 8b139b6..ebc41a7 100644 --- a/src/helm/core/secret_manager.py +++ b/src/helm/config/secret_manager.py @@ -21,7 +21,7 @@ import tempfile from urllib.parse import quote, quote_plus -from helm.core.config_manager import SECRET_KEYS, get_config_dir +from helm.config.config_manager import SECRET_KEYS, get_config_dir _SECRETS_CACHE = None _SECRETS_CACHE_PATH = None diff --git a/src/helm/core/settings.py b/src/helm/config/settings.py similarity index 99% rename from src/helm/core/settings.py rename to src/helm/config/settings.py index fb8a46c..9d88ff3 100644 --- a/src/helm/core/settings.py +++ b/src/helm/config/settings.py @@ -15,8 +15,8 @@ from dataclasses import dataclass from typing import Any, Tuple -from helm.core import config_manager -from helm.core.config_manager import CONTENT_PROFILES, get_config_dir, get_state_dir +from helm.config import config_manager +from helm.config.config_manager import CONTENT_PROFILES, get_config_dir, get_state_dir class ConfigError(ValueError): @@ -376,7 +376,7 @@ def migrate_legacy(): if not data: return - from helm.core.secret_manager import migrate_config_secrets + from helm.config.secret_manager import migrate_config_secrets had_secrets = any(key in data for key in config_manager.SECRET_KEYS) data = migrate_config_secrets(data) diff --git a/src/helm/core/__init__.py b/src/helm/core/__init__.py index e69de29..19b3dee 100644 --- a/src/helm/core/__init__.py +++ b/src/helm/core/__init__.py @@ -0,0 +1,5 @@ +"""Old module paths kept for Lite plugins written against them. + +Helm's own code lives in the feature packages (``helm.config``, ``helm.search``, +``helm.net`` and so on). Only the modules plugins import are kept here. +""" diff --git a/src/helm/core/http.py b/src/helm/core/http.py index 356415a..ed8a5a3 100644 --- a/src/helm/core/http.py +++ b/src/helm/core/http.py @@ -1,19 +1,3 @@ -"""Connection reuse within each worker thread without sharing mutable cookies.""" +"""Compatibility path for plugins: use ``helm.net.http``.""" -import threading - -import requests - -_MAX_SOCKETS = 8 -_local = threading.local() - - -def get_shared_session() -> requests.Session: - session = getattr(_local, "session", None) - if session is None: - session = requests.Session() - adapter = requests.adapters.HTTPAdapter(pool_connections=_MAX_SOCKETS, pool_maxsize=_MAX_SOCKETS) - session.mount("https://", adapter) - session.mount("http://", adapter) - _local.session = session - return session +from helm.net.http import * # noqa: F401,F403 diff --git a/src/helm/core/logger.py b/src/helm/core/logger.py index 710cf73..1eef0fb 100644 --- a/src/helm/core/logger.py +++ b/src/helm/core/logger.py @@ -1,147 +1,3 @@ -import json -import logging -import os -import shutil -import sys -from datetime import datetime, timezone -from logging.handlers import RotatingFileHandler +"""Compatibility path for plugins: use ``helm.logger``.""" -from helm.core.config_manager import get_log_dir -from helm.core.secret_manager import redact_config, redact_text - - -class JSONFormatter(logging.Formatter): - def format(self, record): - log_obj = { - "timestamp": datetime.fromtimestamp(record.created, timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), - "level": record.levelname, - "module": record.name, - "event": record.getMessage(), - } - if getattr(record, "error_code", None): - log_obj["error_code"] = record.error_code - if record.exc_info: - log_obj["error_trace"] = self.formatException(record.exc_info) - - # Add any extra fields passed dynamically - for key, value in record.__dict__.items(): - if key not in [ - "args", - "asctime", - "created", - "exc_info", - "exc_text", - "filename", - "funcName", - "levelname", - "levelno", - "lineno", - "module", - "msecs", - "message", - "msg", - "name", - "pathname", - "process", - "processName", - "relativeCreated", - "stack_info", - "thread", - "threadName", - "error_code", - "file_only", - ]: - log_obj[key] = value - - return json.dumps(redact_config(log_obj)) - - -class FileOnlyFilter(logging.Filter): - """Drops records flagged ``file_only=True`` from the console so they only reach the log file.""" - - def filter(self, record: logging.LogRecord) -> bool: - return not getattr(record, "file_only", False) - - -class PlainTextFormatter(logging.Formatter): - def format(self, record): - timestamp = datetime.fromtimestamp(record.created).strftime("%Y-%m-%d %H:%M:%S") - level = record.levelname.ljust(5) - module = record.name - message = record.getMessage() - formatted = f"[{timestamp}] [{level}] [{module}] - {message}" - if record.exc_info: - formatted += f"\n{self.formatException(record.exc_info)}" - return redact_text(formatted) - - -class ConsoleFormatter(logging.Formatter): - def format(self, record): - timestamp = datetime.fromtimestamp(record.created).strftime("%Y-%m-%d %H:%M:%S") - level = record.levelname.ljust(5) - module = record.name - message = record.getMessage() - return redact_text(f"[{timestamp}] [{level}] [{module}] - {message}") - - -def get_logger(name: str): - # Importing modules must not create files before CLI path overrides are known. - logger = logging.getLogger(name) - logger.setLevel(logging.DEBUG) - if not logger.handlers: - logger.addHandler(logging.NullHandler()) - return logger - - -def configure_logging(file_logging=True, verbose=None): - root = logging.getLogger() - root.setLevel(logging.DEBUG) - for handler in list(root.handlers): - if getattr(handler, "_helm_handler", False): - root.removeHandler(handler) - handler.close() - formatter = JSONFormatter() if os.environ.get("HELM_LOG_JSON", "false").lower() == "true" else PlainTextFormatter() - if verbose is None: - verbose = os.environ.get("HELM_VERBOSE", "false").lower() == "true" - console = logging.StreamHandler(sys.stderr) - console.setLevel(logging.DEBUG if verbose else logging.WARNING) - console.setFormatter(formatter if verbose else ConsoleFormatter()) - console.addFilter(FileOnlyFilter()) - handlers = [console] - if file_logging: - directory = get_log_dir() - os.makedirs(directory, exist_ok=True) - path = os.path.join(directory, "helm.log") - old = os.path.expanduser("~/.helm_data/logs/helm.log") - if os.path.isfile(old) and not os.path.exists(path): - try: - shutil.move(old, path) - except OSError: - pass - handler = RotatingFileHandler(path, maxBytes=5 * 1024 * 1024, backupCount=3) - handler.setLevel(logging.DEBUG) - handler.setFormatter(formatter) - handlers.append(handler) - for handler in handlers: - handler._helm_handler = True - root.addHandler(handler) - - -def tail_log(path, lines=20, max_bytes=1024 * 1024): - """Read a bounded suffix; never scan an entire large log to display its tail.""" - if lines < 1 or max_bytes < 1: - return "" - with open(path, "rb") as stream: - stream.seek(0, os.SEEK_END) - end = stream.tell() - data = b"" - position = end - while position and data.count(b"\n") <= lines and len(data) < max_bytes: - amount = min(8192, position, max_bytes - len(data)) - position -= amount - stream.seek(position) - data = stream.read(amount) + data - if position and b"\n" in data: - data = data.split(b"\n", 1)[1] - result = b"\n".join(data.splitlines()[-lines:]).decode("utf-8", errors="replace") - return redact_text(result) + ("\n" if result else "") +from helm.logger import * # noqa: F401,F403 diff --git a/src/helm/core/rss_fetcher.py b/src/helm/core/rss_fetcher.py index fdb9c41..6b57caa 100644 --- a/src/helm/core/rss_fetcher.py +++ b/src/helm/core/rss_fetcher.py @@ -1,389 +1,3 @@ -""" -core/rss_fetcher.py +"""Compatibility path for plugins: use ``helm.search.rss_fetcher``.""" -responsible for fetching and parsing RSS(really simple syndication) feeds from multiple indexers - -""" - -import email.utils -import urllib.error -import xml.etree.ElementTree as ET -from dataclasses import dataclass -from typing import List - -import requests - -from helm.core.logger import get_logger -from helm.core.secret_manager import get_secret - -logger = get_logger(__name__) - - -@dataclass -class SourceOutcome: - source: str - status: str - count: int = 0 - - -class SearchResults(list): - """List-compatible results with diagnostics owned by this search only.""" - - def __init__(self, items=(), outcomes=()) -> None: - super().__init__(items) - self.outcomes: List[SourceOutcome] = list(outcomes) - - def extend(self, items) -> None: - super().extend(items) - self.outcomes.extend(getattr(items, "outcomes", ())) - - -def source_status(error): - """Report a safe category rather than exposing URLs or credentials.""" - if isinstance(error, (requests.exceptions.Timeout, TimeoutError)): - return "timeout" - if isinstance(error, (requests.exceptions.HTTPError, urllib.error.HTTPError)): - return "http_error" - if isinstance(error, (ValueError, TypeError, KeyError, AttributeError, ET.ParseError)): - return "parse_error" - if isinstance(error, (requests.exceptions.RequestException, urllib.error.URLError)): - return "connection_error" - return "error" - - -class TorrentItem: - def __init__(self, title, link, seeders, leechers=0, size=0, pubdate=None, indexer="Unknown"): - self.title = title - self.link = link - self.seeders = seeders - self.leechers = leechers - self.size = size - self.pubdate = pubdate - self.indexer = indexer - - -CATEGORY_MAP = {"video": "2000,5000", "games": "4000", "software": "4000", "books": "8000", "music": "3000"} - - -def _parse_feed(xml_text): - root = ET.fromstring(xml_text) - ns = {"torznab": "http://torznab.com/schemas/2015/feed"} - items = [] - for elem in root.findall("./channel/item"): - title = elem.findtext("title", default="") - link = elem.findtext("link", default="") - - pubdate_text = elem.findtext("pubDate") - pubdate = None - if pubdate_text: - try: - parsed = email.utils.parsedate_to_datetime(pubdate_text) - pubdate = parsed.strftime("%Y-%m-%d") - except Exception: - pass - - size_elem = elem.find("size") - size = 0 - if size_elem is not None and size_elem.text and size_elem.text.isdigit(): - size = int(size_elem.text) - - seeders = 0 - leechers = 0 - for attr in elem.findall("torznab:attr", namespaces=ns): - name = attr.get("name") - value = attr.get("value", "") - if name == "seeders": - try: - seeders = int(value) - except ValueError: - pass - elif name == "peers": - try: - peers = int(value) - leechers = peers - seeders - except ValueError: - pass - elif name == "leechers": - try: - leechers = int(value) - except ValueError: - pass - elif name == "size" and size == 0: - try: - size = int(value) - except ValueError: - pass - - if leechers < 0: - leechers = 0 - - indexer_elem = elem.find("jackettindexer") - indexer = indexer_elem.text if indexer_elem is not None else "Jackett" - - items.append(TorrentItem(title, link, seeders, leechers, size, pubdate, indexer)) - return items - - -def _get_configured_indexers(jackett_url, api_key): - url = f"{jackett_url}/api/v2.0/indexers/all/results/torznab/api" - r = requests.get(url, params={"apikey": api_key, "t": "indexers"}, timeout=15) - r.raise_for_status() - root = ET.fromstring(r.content) - return [idx.get("id") for idx in root.findall("indexer") if idx.get("configured") == "true"] - - -def _search_indexer(jackett_url, api_key, indexer_id, query, cat): - url = f"{jackett_url}/api/v2.0/indexers/{indexer_id}/results/torznab/api" - params = {"apikey": api_key, "q": query} - if cat: - params["cat"] = cat - r = requests.get(url, params=params, timeout=60) - r.raise_for_status() - return _parse_feed(r.text) - - -def _fetch_aggregate(jackett_url, api_key, query, cat): - url = f"{jackett_url}/api/v2.0/indexers/all/results/torznab/api" - params = {"apikey": api_key, "q": query} - if cat: - params["cat"] = cat - r = requests.get(url, params=params, timeout=120) - r.raise_for_status() - return _parse_feed(r.text) - - -def search_prowlarr(query, content_type="video"): - from helm.core.secret_manager import get_secret - from helm.core.settings import load_settings - - prowlarr_url = load_settings().get("services.prowlarr") - api_key = get_secret("PROWLARR_API_KEY") - - if not api_key or "your_prowlarr_api_key_here" in api_key.lower(): - logger.warning("Event: Prowlarr API key not configured or is placeholder.") - return [] - - # Seed default indexers on first use when none are configured. - try: - idx_r = requests.get(f"{prowlarr_url}/api/v1/indexer", headers={"X-Api-Key": api_key}, timeout=5) - if idx_r.status_code == 200 and len(idx_r.json()) == 0: - logger.info("Event: Prowlarr indexers empty. Seeding defaults...") - from helm.core.indexer_manager import ProwlarrManager - - seed_count = ProwlarrManager().seed_default_indexers() - logger.info("Event: Seeded %s default Prowlarr indexers.", seed_count) - except Exception: - pass - - endpoint = f"{prowlarr_url}/api/v1/search" - params = {"query": query, "apikey": api_key} - - try: - r = requests.get(endpoint, params=params, timeout=60) - r.raise_for_status() - - results = [] - data = r.json() - - for item in data: - title = item.get("title", "unknown") - size = item.get("size", 0) - seeders = item.get("seeders") or 0 - leechers = item.get("leechers") or 0 - indexer = item.get("indexer", "unknown") - download_url = item.get("magnetUrl") or item.get("downloadUrl") - - if not download_url: - continue - - results.append( - TorrentItem( - title, - download_url, - seeders, - leechers, - size, - pubdate=None, - indexer=f"Prowlarr ({indexer})", - ) - ) - - logger.info(f"Event: Prowlarr aggregated JSON search returned {len(results)} results") - return sorted(results, key=lambda x: x.seeders, reverse=True) - - except Exception as e: - logger.error(f"Event: Prowlarr JSON search failed: {e}. Falling back to Torznab XML parsing.") - - cats = content_type.split(",") - cat_ids = [] - for c in cats: - if c in CATEGORY_MAP: - cat_ids.append(CATEGORY_MAP[c]) - cat = ",".join(cat_ids) if cat_ids else CATEGORY_MAP.get("video") - - # Prowlarr Torznab: /{appId}/api?apikey=...&t=search&q=... - torznab_url = f"{prowlarr_url}/1/api" - params_xml = {"t": "search", "q": query, "apikey": api_key} - if cat: - params_xml["cat"] = cat - - try: - r = requests.get(torznab_url, params=params_xml, timeout=120) - r.raise_for_status() - items = _parse_feed(r.text) - logger.info(f"Event: Prowlarr Torznab fallback returned {len(items)} results") - return items - except Exception as ex: - logger.error(f"Event: Prowlarr Torznab fallback also failed: {ex}", exc_info=True) - return [] - - -def search_indexers(query, content_type="video", fallback_lite=True): - """ - Search using the configured Indexer Manager. - - Runs the configured manager (Prowlarr, Jackett, or both), falls back to the - other manager when configured, and finally to native Lite Mode plugins so a - search never comes up empty. - """ - from helm.core.settings import load_settings - - manager = load_settings().get("search.indexer_manager") - - def dedupe(items): - seen = set() - unique = [] - for item in items: - key = (item.title.lower().strip(), item.size) - if key not in seen: - seen.add(key) - unique.append(item) - return unique - - items = [] - if manager in ("prowlarr", "both"): - items.extend(search_prowlarr(query, content_type)) - if manager in ("jackett", "both"): - items.extend(search_jackett(query, content_type)) - elif manager == "prowlarr" and not items: - logger.info("Event: Prowlarr returned no results, falling back to Jackett.") - items.extend(search_jackett(query, content_type)) - - if items: - return dedupe(items) - - if not fallback_lite: - return [] - - logger.info("Event: Media Server search failed or returned 0 results, falling back to Lite mode...") - import asyncio - - from helm.core.lite_fetcher import search_all_plugins - - return dedupe(asyncio.run(search_all_plugins(query, content_type))) - - -def search_jackett(query, content_type="video"): - from helm.core.settings import load_settings - - jackett_url = load_settings().get("services.jackett") - api_key = get_secret("JACKETT_API_KEY") - if not api_key: - logger.info("Event: Jackett API key not configured. Seamlessly falling back to native Lite Mode plugins.") - return [] - - # 1) Try JSON API first - endpoint = f"{jackett_url}/api/v2.0/indexers/all/results" - params = {"Query": query, "apikey": api_key} - try: - r = requests.get(endpoint, params=params, timeout=60) - r.raise_for_status() - - results = [] - data = r.json() - items = data.get("Results", []) - - for item in items: - title = item.get("Title", "unknown") - size = item.get("Size", 0) - seeders = item.get("Seeders") or 0 - leechers = item.get("Peers") or 0 - indexer = item.get("Tracker", "unknown") - download_url = item.get("MagnetUri") or item.get("Link") - - if not download_url: - continue - - results.append( - TorrentItem(title, download_url, seeders, leechers, size, pubdate=None, indexer=f"Jackett ({indexer})") - ) - - if results: - logger.info(f"Event: Jackett aggregated JSON search returned {len(results)} results") - return sorted(results, key=lambda x: x.seeders, reverse=True) - - except Exception as e: - logger.error(f"Event: Jackett JSON search failed: {e}. Falling back to ThreadPool Torznab XML parsing.") - - # 2) Hard fallback to XML Torznab Parsing - cats = content_type.split(",") - cat_ids = [] - for c in cats: - if c in CATEGORY_MAP: - cat_ids.append(CATEGORY_MAP[c]) - cat = ",".join(cat_ids) if cat_ids else CATEGORY_MAP.get("video") - - try: - indexers = _get_configured_indexers(jackett_url, api_key) - except Exception as e: - logger.debug( - f"Event: Could not list configured indexers ({e}); falling back to aggregate search", exc_info=True - ) - indexers = [] - - items = [] - if indexers: - import concurrent.futures - - def run(indexer_id): - try: - return indexer_id, _search_indexer(jackett_url, api_key, indexer_id, query, cat) - except Exception as e: - logger.debug(f"Event: Indexer '{indexer_id}' failed: {e}", exc_info=True) - return indexer_id, [] - - with concurrent.futures.ThreadPoolExecutor(max_workers=6) as executor: - futures = [executor.submit(run, idx) for idx in indexers] - for future in concurrent.futures.as_completed(futures, timeout=120): - indexer_id, indexer_items = future.result() - if indexer_items: - logger.info(f"Event: Jackett indexer '{indexer_id}' returned {len(indexer_items)} results") - items.extend(indexer_items) - - # If every per-indexer query failed (e.g. all returned errors), retry - # with Jackett's aggregate endpoint before giving up. - if not items: - try: - items = _fetch_aggregate(jackett_url, api_key, query, cat) - except Exception as e: - logger.debug(f"Event: Jackett aggregate torznab also failed: {e}", exc_info=True) - - else: - # No specific indexers found, try aggregate - try: - items = _fetch_aggregate(jackett_url, api_key, query, cat) - except Exception as e: - logger.debug(f"Event: Jackett aggregate torznab failed: {e}", exc_info=True) - - # Jackett's per-indexer endpoints can hand back the same release twice. - # Collapse exact title+size duplicates so the dedupe and display stay clean. - if len(items) > 1: - seen = set() - unique = [] - for item in items: - key = (item.title.lower().strip(), item.size) - if key not in seen: - seen.add(key) - unique.append(item) - return unique - return items +from helm.search.rss_fetcher import * # noqa: F401,F403 diff --git a/src/helm/logger.py b/src/helm/logger.py new file mode 100644 index 0000000..b8c4efe --- /dev/null +++ b/src/helm/logger.py @@ -0,0 +1,147 @@ +import json +import logging +import os +import shutil +import sys +from datetime import datetime, timezone +from logging.handlers import RotatingFileHandler + +from helm.config.config_manager import get_log_dir +from helm.config.secret_manager import redact_config, redact_text + + +class JSONFormatter(logging.Formatter): + def format(self, record): + log_obj = { + "timestamp": datetime.fromtimestamp(record.created, timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), + "level": record.levelname, + "module": record.name, + "event": record.getMessage(), + } + if getattr(record, "error_code", None): + log_obj["error_code"] = record.error_code + if record.exc_info: + log_obj["error_trace"] = self.formatException(record.exc_info) + + # Add any extra fields passed dynamically + for key, value in record.__dict__.items(): + if key not in [ + "args", + "asctime", + "created", + "exc_info", + "exc_text", + "filename", + "funcName", + "levelname", + "levelno", + "lineno", + "module", + "msecs", + "message", + "msg", + "name", + "pathname", + "process", + "processName", + "relativeCreated", + "stack_info", + "thread", + "threadName", + "error_code", + "file_only", + ]: + log_obj[key] = value + + return json.dumps(redact_config(log_obj)) + + +class FileOnlyFilter(logging.Filter): + """Drops records flagged ``file_only=True`` from the console so they only reach the log file.""" + + def filter(self, record: logging.LogRecord) -> bool: + return not getattr(record, "file_only", False) + + +class PlainTextFormatter(logging.Formatter): + def format(self, record): + timestamp = datetime.fromtimestamp(record.created).strftime("%Y-%m-%d %H:%M:%S") + level = record.levelname.ljust(5) + module = record.name + message = record.getMessage() + formatted = f"[{timestamp}] [{level}] [{module}] - {message}" + if record.exc_info: + formatted += f"\n{self.formatException(record.exc_info)}" + return redact_text(formatted) + + +class ConsoleFormatter(logging.Formatter): + def format(self, record): + timestamp = datetime.fromtimestamp(record.created).strftime("%Y-%m-%d %H:%M:%S") + level = record.levelname.ljust(5) + module = record.name + message = record.getMessage() + return redact_text(f"[{timestamp}] [{level}] [{module}] - {message}") + + +def get_logger(name: str): + # Importing modules must not create files before CLI path overrides are known. + logger = logging.getLogger(name) + logger.setLevel(logging.DEBUG) + if not logger.handlers: + logger.addHandler(logging.NullHandler()) + return logger + + +def configure_logging(file_logging=True, verbose=None): + root = logging.getLogger() + root.setLevel(logging.DEBUG) + for handler in list(root.handlers): + if getattr(handler, "_helm_handler", False): + root.removeHandler(handler) + handler.close() + formatter = JSONFormatter() if os.environ.get("HELM_LOG_JSON", "false").lower() == "true" else PlainTextFormatter() + if verbose is None: + verbose = os.environ.get("HELM_VERBOSE", "false").lower() == "true" + console = logging.StreamHandler(sys.stderr) + console.setLevel(logging.DEBUG if verbose else logging.WARNING) + console.setFormatter(formatter if verbose else ConsoleFormatter()) + console.addFilter(FileOnlyFilter()) + handlers = [console] + if file_logging: + directory = get_log_dir() + os.makedirs(directory, exist_ok=True) + path = os.path.join(directory, "helm.log") + old = os.path.expanduser("~/.helm_data/logs/helm.log") + if os.path.isfile(old) and not os.path.exists(path): + try: + shutil.move(old, path) + except OSError: + pass + handler = RotatingFileHandler(path, maxBytes=5 * 1024 * 1024, backupCount=3) + handler.setLevel(logging.DEBUG) + handler.setFormatter(formatter) + handlers.append(handler) + for handler in handlers: + handler._helm_handler = True + root.addHandler(handler) + + +def tail_log(path, lines=20, max_bytes=1024 * 1024): + """Read a bounded suffix; never scan an entire large log to display its tail.""" + if lines < 1 or max_bytes < 1: + return "" + with open(path, "rb") as stream: + stream.seek(0, os.SEEK_END) + end = stream.tell() + data = b"" + position = end + while position and data.count(b"\n") <= lines and len(data) < max_bytes: + amount = min(8192, position, max_bytes - len(data)) + position -= amount + stream.seek(position) + data = stream.read(amount) + data + if position and b"\n" in data: + data = data.split(b"\n", 1)[1] + result = b"\n".join(data.splitlines()[-lines:]).decode("utf-8", errors="replace") + return redact_text(result) + ("\n" if result else "") diff --git a/src/helm/net/__init__.py b/src/helm/net/__init__.py new file mode 100644 index 0000000..9af3b95 --- /dev/null +++ b/src/helm/net/__init__.py @@ -0,0 +1 @@ +"""Shared HTTP session.""" diff --git a/src/helm/net/http.py b/src/helm/net/http.py new file mode 100644 index 0000000..356415a --- /dev/null +++ b/src/helm/net/http.py @@ -0,0 +1,19 @@ +"""Connection reuse within each worker thread without sharing mutable cookies.""" + +import threading + +import requests + +_MAX_SOCKETS = 8 +_local = threading.local() + + +def get_shared_session() -> requests.Session: + session = getattr(_local, "session", None) + if session is None: + session = requests.Session() + adapter = requests.adapters.HTTPAdapter(pool_connections=_MAX_SOCKETS, pool_maxsize=_MAX_SOCKETS) + session.mount("https://", adapter) + session.mount("http://", adapter) + _local.session = session + return session diff --git a/src/helm/plugins/bittorrented.py b/src/helm/plugins/bittorrented.py index b9da8a2..cb79d5b 100644 --- a/src/helm/plugins/bittorrented.py +++ b/src/helm/plugins/bittorrented.py @@ -11,8 +11,8 @@ import requests from novaprinter import prettyPrinter, report_error -from helm.core.http import get_shared_session -from helm.core.logger import get_logger +from helm.logger import get_logger +from helm.net.http import get_shared_session logger = get_logger(__name__) diff --git a/src/helm/plugins/eztv.py b/src/helm/plugins/eztv.py index 0a23b2b..4f53750 100644 --- a/src/helm/plugins/eztv.py +++ b/src/helm/plugins/eztv.py @@ -9,8 +9,8 @@ import requests from novaprinter import prettyPrinter, report_error -from helm.core.http import get_shared_session -from helm.core.logger import get_logger +from helm.logger import get_logger +from helm.net.http import get_shared_session logger = get_logger(__name__) diff --git a/src/helm/plugins/helpers.py b/src/helm/plugins/helpers.py index d32a314..8d9f6f5 100644 --- a/src/helm/plugins/helpers.py +++ b/src/helm/plugins/helpers.py @@ -1,4 +1,4 @@ -from helm.core.http import get_shared_session +from helm.net.http import get_shared_session def retrieve_url(url, request_data=None): diff --git a/src/helm/plugins/novaprinter.py b/src/helm/plugins/novaprinter.py index 8d6642c..23c4d61 100644 --- a/src/helm/plugins/novaprinter.py +++ b/src/helm/plugins/novaprinter.py @@ -1,7 +1,7 @@ import threading from typing import List -from helm.core.rss_fetcher import TorrentItem, source_status +from helm.search.rss_fetcher import TorrentItem, source_status class _ThreadLocalResults(threading.local): diff --git a/src/helm/plugins/subsplease.py b/src/helm/plugins/subsplease.py index 8f951d4..c1f8634 100644 --- a/src/helm/plugins/subsplease.py +++ b/src/helm/plugins/subsplease.py @@ -9,8 +9,8 @@ from novaprinter import prettyPrinter, report_error -from helm.core.http import get_shared_session -from helm.core.logger import get_logger +from helm.logger import get_logger +from helm.net.http import get_shared_session logger = get_logger(__name__) diff --git a/src/helm/plugins/torrentproject.py b/src/helm/plugins/torrentproject.py index 73664bb..98cffc4 100644 --- a/src/helm/plugins/torrentproject.py +++ b/src/helm/plugins/torrentproject.py @@ -10,7 +10,7 @@ from helpers import retrieve_url, validate_html from novaprinter import prettyPrinter -from helm.core.logger import get_logger +from helm.logger import get_logger class torrentproject: diff --git a/src/helm/plugins/x1337.py b/src/helm/plugins/x1337.py index 180c099..7f7f5bc 100644 --- a/src/helm/plugins/x1337.py +++ b/src/helm/plugins/x1337.py @@ -13,7 +13,7 @@ from helpers import retrieve_url, validate_html from novaprinter import prettyPrinter, report_error -from helm.core.logger import get_logger +from helm.logger import get_logger logger = get_logger(__name__) diff --git a/src/helm/plugins/yts.py b/src/helm/plugins/yts.py index 1e6078c..dc82f73 100644 --- a/src/helm/plugins/yts.py +++ b/src/helm/plugins/yts.py @@ -7,8 +7,8 @@ import requests from novaprinter import prettyPrinter, report_error -from helm.core.http import get_shared_session -from helm.core.logger import get_logger +from helm.logger import get_logger +from helm.net.http import get_shared_session logger = get_logger(__name__) diff --git a/src/helm/search/__init__.py b/src/helm/search/__init__.py new file mode 100644 index 0000000..9a25574 --- /dev/null +++ b/src/helm/search/__init__.py @@ -0,0 +1 @@ +"""Search sources, the Lite plugin runner and result filtering.""" diff --git a/src/helm/core/indexer_manager.py b/src/helm/search/indexer_manager.py similarity index 98% rename from src/helm/core/indexer_manager.py rename to src/helm/search/indexer_manager.py index a08c2a4..7a490c2 100644 --- a/src/helm/core/indexer_manager.py +++ b/src/helm/search/indexer_manager.py @@ -2,9 +2,9 @@ import requests -from helm.core.logger import get_logger -from helm.core.secret_manager import get_secret -from helm.core.settings import load_settings +from helm.config.secret_manager import get_secret +from helm.config.settings import load_settings +from helm.logger import get_logger logger = get_logger(__name__) diff --git a/src/helm/core/lite_fetcher.py b/src/helm/search/lite_fetcher.py similarity index 94% rename from src/helm/core/lite_fetcher.py rename to src/helm/search/lite_fetcher.py index cd3b808..5053fa1 100644 --- a/src/helm/core/lite_fetcher.py +++ b/src/helm/search/lite_fetcher.py @@ -6,11 +6,11 @@ from typing import List from urllib.parse import quote -from helm.core.config_manager import get_config_dir -from helm.core.http import get_shared_session -from helm.core.lite_plugin_loader import PLUGIN_SEARCH_TIMEOUT -from helm.core.logger import get_logger -from helm.core.rss_fetcher import SearchResults, SourceOutcome, TorrentItem, source_status +from helm.config.config_manager import get_config_dir +from helm.logger import get_logger +from helm.net.http import get_shared_session +from helm.search.lite_plugin_loader import PLUGIN_SEARCH_TIMEOUT +from helm.search.rss_fetcher import SearchResults, SourceOutcome, TorrentItem, source_status logger = get_logger(__name__) @@ -177,8 +177,8 @@ def _plugin_dirs(): def _collect_all(query, content_type="video"): - from helm.core.lite_plugin_loader import plugin_jobs - from helm.core.search_runner import SearchJob, run_searches + from helm.search.lite_plugin_loader import plugin_jobs + from helm.search.search_runner import SearchJob, run_searches jobs = [ SearchJob("Apibay", "inline", "apibay"), diff --git a/src/helm/core/lite_plugin_loader.py b/src/helm/search/lite_plugin_loader.py similarity index 94% rename from src/helm/core/lite_plugin_loader.py rename to src/helm/search/lite_plugin_loader.py index 614d992..e3eefe5 100644 --- a/src/helm/core/lite_plugin_loader.py +++ b/src/helm/search/lite_plugin_loader.py @@ -2,8 +2,8 @@ import os import sys -from helm.core.logger import get_logger -from helm.core.rss_fetcher import SearchResults, SourceOutcome, source_status +from helm.logger import get_logger +from helm.search.rss_fetcher import SearchResults, SourceOutcome, source_status logger = get_logger(__name__) PLUGIN_SEARCH_TIMEOUT = 30 @@ -15,7 +15,7 @@ def plugin_jobs(plugin_dirs): - from helm.core.search_runner import SearchJob + from helm.search.search_runner import SearchJob jobs = [] for directory in plugin_dirs: @@ -110,6 +110,6 @@ def _execute_plugin(plugin, query, content_type="all"): def run_plugins(query, plugin_dirs, content_type="all"): - from helm.core.search_runner import run_searches + from helm.search.search_runner import run_searches return run_searches(plugin_jobs(plugin_dirs), query, content_type, timeout=PLUGIN_SEARCH_TIMEOUT) diff --git a/src/helm/search/rss_fetcher.py b/src/helm/search/rss_fetcher.py new file mode 100644 index 0000000..11b18ae --- /dev/null +++ b/src/helm/search/rss_fetcher.py @@ -0,0 +1,389 @@ +""" +core/rss_fetcher.py + +responsible for fetching and parsing RSS(really simple syndication) feeds from multiple indexers + +""" + +import email.utils +import urllib.error +import xml.etree.ElementTree as ET +from dataclasses import dataclass +from typing import List + +import requests + +from helm.config.secret_manager import get_secret +from helm.logger import get_logger + +logger = get_logger(__name__) + + +@dataclass +class SourceOutcome: + source: str + status: str + count: int = 0 + + +class SearchResults(list): + """List-compatible results with diagnostics owned by this search only.""" + + def __init__(self, items=(), outcomes=()) -> None: + super().__init__(items) + self.outcomes: List[SourceOutcome] = list(outcomes) + + def extend(self, items) -> None: + super().extend(items) + self.outcomes.extend(getattr(items, "outcomes", ())) + + +def source_status(error): + """Report a safe category rather than exposing URLs or credentials.""" + if isinstance(error, (requests.exceptions.Timeout, TimeoutError)): + return "timeout" + if isinstance(error, (requests.exceptions.HTTPError, urllib.error.HTTPError)): + return "http_error" + if isinstance(error, (ValueError, TypeError, KeyError, AttributeError, ET.ParseError)): + return "parse_error" + if isinstance(error, (requests.exceptions.RequestException, urllib.error.URLError)): + return "connection_error" + return "error" + + +class TorrentItem: + def __init__(self, title, link, seeders, leechers=0, size=0, pubdate=None, indexer="Unknown"): + self.title = title + self.link = link + self.seeders = seeders + self.leechers = leechers + self.size = size + self.pubdate = pubdate + self.indexer = indexer + + +CATEGORY_MAP = {"video": "2000,5000", "games": "4000", "software": "4000", "books": "8000", "music": "3000"} + + +def _parse_feed(xml_text): + root = ET.fromstring(xml_text) + ns = {"torznab": "http://torznab.com/schemas/2015/feed"} + items = [] + for elem in root.findall("./channel/item"): + title = elem.findtext("title", default="") + link = elem.findtext("link", default="") + + pubdate_text = elem.findtext("pubDate") + pubdate = None + if pubdate_text: + try: + parsed = email.utils.parsedate_to_datetime(pubdate_text) + pubdate = parsed.strftime("%Y-%m-%d") + except Exception: + pass + + size_elem = elem.find("size") + size = 0 + if size_elem is not None and size_elem.text and size_elem.text.isdigit(): + size = int(size_elem.text) + + seeders = 0 + leechers = 0 + for attr in elem.findall("torznab:attr", namespaces=ns): + name = attr.get("name") + value = attr.get("value", "") + if name == "seeders": + try: + seeders = int(value) + except ValueError: + pass + elif name == "peers": + try: + peers = int(value) + leechers = peers - seeders + except ValueError: + pass + elif name == "leechers": + try: + leechers = int(value) + except ValueError: + pass + elif name == "size" and size == 0: + try: + size = int(value) + except ValueError: + pass + + if leechers < 0: + leechers = 0 + + indexer_elem = elem.find("jackettindexer") + indexer = indexer_elem.text if indexer_elem is not None else "Jackett" + + items.append(TorrentItem(title, link, seeders, leechers, size, pubdate, indexer)) + return items + + +def _get_configured_indexers(jackett_url, api_key): + url = f"{jackett_url}/api/v2.0/indexers/all/results/torznab/api" + r = requests.get(url, params={"apikey": api_key, "t": "indexers"}, timeout=15) + r.raise_for_status() + root = ET.fromstring(r.content) + return [idx.get("id") for idx in root.findall("indexer") if idx.get("configured") == "true"] + + +def _search_indexer(jackett_url, api_key, indexer_id, query, cat): + url = f"{jackett_url}/api/v2.0/indexers/{indexer_id}/results/torznab/api" + params = {"apikey": api_key, "q": query} + if cat: + params["cat"] = cat + r = requests.get(url, params=params, timeout=60) + r.raise_for_status() + return _parse_feed(r.text) + + +def _fetch_aggregate(jackett_url, api_key, query, cat): + url = f"{jackett_url}/api/v2.0/indexers/all/results/torznab/api" + params = {"apikey": api_key, "q": query} + if cat: + params["cat"] = cat + r = requests.get(url, params=params, timeout=120) + r.raise_for_status() + return _parse_feed(r.text) + + +def search_prowlarr(query, content_type="video"): + from helm.config.secret_manager import get_secret + from helm.config.settings import load_settings + + prowlarr_url = load_settings().get("services.prowlarr") + api_key = get_secret("PROWLARR_API_KEY") + + if not api_key or "your_prowlarr_api_key_here" in api_key.lower(): + logger.warning("Event: Prowlarr API key not configured or is placeholder.") + return [] + + # Seed default indexers on first use when none are configured. + try: + idx_r = requests.get(f"{prowlarr_url}/api/v1/indexer", headers={"X-Api-Key": api_key}, timeout=5) + if idx_r.status_code == 200 and len(idx_r.json()) == 0: + logger.info("Event: Prowlarr indexers empty. Seeding defaults...") + from helm.search.indexer_manager import ProwlarrManager + + seed_count = ProwlarrManager().seed_default_indexers() + logger.info("Event: Seeded %s default Prowlarr indexers.", seed_count) + except Exception: + pass + + endpoint = f"{prowlarr_url}/api/v1/search" + params = {"query": query, "apikey": api_key} + + try: + r = requests.get(endpoint, params=params, timeout=60) + r.raise_for_status() + + results = [] + data = r.json() + + for item in data: + title = item.get("title", "unknown") + size = item.get("size", 0) + seeders = item.get("seeders") or 0 + leechers = item.get("leechers") or 0 + indexer = item.get("indexer", "unknown") + download_url = item.get("magnetUrl") or item.get("downloadUrl") + + if not download_url: + continue + + results.append( + TorrentItem( + title, + download_url, + seeders, + leechers, + size, + pubdate=None, + indexer=f"Prowlarr ({indexer})", + ) + ) + + logger.info(f"Event: Prowlarr aggregated JSON search returned {len(results)} results") + return sorted(results, key=lambda x: x.seeders, reverse=True) + + except Exception as e: + logger.error(f"Event: Prowlarr JSON search failed: {e}. Falling back to Torznab XML parsing.") + + cats = content_type.split(",") + cat_ids = [] + for c in cats: + if c in CATEGORY_MAP: + cat_ids.append(CATEGORY_MAP[c]) + cat = ",".join(cat_ids) if cat_ids else CATEGORY_MAP.get("video") + + # Prowlarr Torznab: /{appId}/api?apikey=...&t=search&q=... + torznab_url = f"{prowlarr_url}/1/api" + params_xml = {"t": "search", "q": query, "apikey": api_key} + if cat: + params_xml["cat"] = cat + + try: + r = requests.get(torznab_url, params=params_xml, timeout=120) + r.raise_for_status() + items = _parse_feed(r.text) + logger.info(f"Event: Prowlarr Torznab fallback returned {len(items)} results") + return items + except Exception as ex: + logger.error(f"Event: Prowlarr Torznab fallback also failed: {ex}", exc_info=True) + return [] + + +def search_indexers(query, content_type="video", fallback_lite=True): + """ + Search using the configured Indexer Manager. + + Runs the configured manager (Prowlarr, Jackett, or both), falls back to the + other manager when configured, and finally to native Lite Mode plugins so a + search never comes up empty. + """ + from helm.config.settings import load_settings + + manager = load_settings().get("search.indexer_manager") + + def dedupe(items): + seen = set() + unique = [] + for item in items: + key = (item.title.lower().strip(), item.size) + if key not in seen: + seen.add(key) + unique.append(item) + return unique + + items = [] + if manager in ("prowlarr", "both"): + items.extend(search_prowlarr(query, content_type)) + if manager in ("jackett", "both"): + items.extend(search_jackett(query, content_type)) + elif manager == "prowlarr" and not items: + logger.info("Event: Prowlarr returned no results, falling back to Jackett.") + items.extend(search_jackett(query, content_type)) + + if items: + return dedupe(items) + + if not fallback_lite: + return [] + + logger.info("Event: Media Server search failed or returned 0 results, falling back to Lite mode...") + import asyncio + + from helm.search.lite_fetcher import search_all_plugins + + return dedupe(asyncio.run(search_all_plugins(query, content_type))) + + +def search_jackett(query, content_type="video"): + from helm.config.settings import load_settings + + jackett_url = load_settings().get("services.jackett") + api_key = get_secret("JACKETT_API_KEY") + if not api_key: + logger.info("Event: Jackett API key not configured. Seamlessly falling back to native Lite Mode plugins.") + return [] + + # 1) Try JSON API first + endpoint = f"{jackett_url}/api/v2.0/indexers/all/results" + params = {"Query": query, "apikey": api_key} + try: + r = requests.get(endpoint, params=params, timeout=60) + r.raise_for_status() + + results = [] + data = r.json() + items = data.get("Results", []) + + for item in items: + title = item.get("Title", "unknown") + size = item.get("Size", 0) + seeders = item.get("Seeders") or 0 + leechers = item.get("Peers") or 0 + indexer = item.get("Tracker", "unknown") + download_url = item.get("MagnetUri") or item.get("Link") + + if not download_url: + continue + + results.append( + TorrentItem(title, download_url, seeders, leechers, size, pubdate=None, indexer=f"Jackett ({indexer})") + ) + + if results: + logger.info(f"Event: Jackett aggregated JSON search returned {len(results)} results") + return sorted(results, key=lambda x: x.seeders, reverse=True) + + except Exception as e: + logger.error(f"Event: Jackett JSON search failed: {e}. Falling back to ThreadPool Torznab XML parsing.") + + # 2) Hard fallback to XML Torznab Parsing + cats = content_type.split(",") + cat_ids = [] + for c in cats: + if c in CATEGORY_MAP: + cat_ids.append(CATEGORY_MAP[c]) + cat = ",".join(cat_ids) if cat_ids else CATEGORY_MAP.get("video") + + try: + indexers = _get_configured_indexers(jackett_url, api_key) + except Exception as e: + logger.debug( + f"Event: Could not list configured indexers ({e}); falling back to aggregate search", exc_info=True + ) + indexers = [] + + items = [] + if indexers: + import concurrent.futures + + def run(indexer_id): + try: + return indexer_id, _search_indexer(jackett_url, api_key, indexer_id, query, cat) + except Exception as e: + logger.debug(f"Event: Indexer '{indexer_id}' failed: {e}", exc_info=True) + return indexer_id, [] + + with concurrent.futures.ThreadPoolExecutor(max_workers=6) as executor: + futures = [executor.submit(run, idx) for idx in indexers] + for future in concurrent.futures.as_completed(futures, timeout=120): + indexer_id, indexer_items = future.result() + if indexer_items: + logger.info(f"Event: Jackett indexer '{indexer_id}' returned {len(indexer_items)} results") + items.extend(indexer_items) + + # If every per-indexer query failed (e.g. all returned errors), retry + # with Jackett's aggregate endpoint before giving up. + if not items: + try: + items = _fetch_aggregate(jackett_url, api_key, query, cat) + except Exception as e: + logger.debug(f"Event: Jackett aggregate torznab also failed: {e}", exc_info=True) + + else: + # No specific indexers found, try aggregate + try: + items = _fetch_aggregate(jackett_url, api_key, query, cat) + except Exception as e: + logger.debug(f"Event: Jackett aggregate torznab failed: {e}", exc_info=True) + + # Jackett's per-indexer endpoints can hand back the same release twice. + # Collapse exact title+size duplicates so the dedupe and display stay clean. + if len(items) > 1: + seen = set() + unique = [] + for item in items: + key = (item.title.lower().strip(), item.size) + if key not in seen: + seen.add(key) + unique.append(item) + return unique + return items diff --git a/src/helm/core/search_runner.py b/src/helm/search/search_runner.py similarity index 92% rename from src/helm/core/search_runner.py rename to src/helm/search/search_runner.py index 2352071..f4ea08b 100644 --- a/src/helm/core/search_runner.py +++ b/src/helm/search/search_runner.py @@ -12,10 +12,10 @@ import time from dataclasses import asdict, dataclass -from helm.core.config_manager import worker_count -from helm.core.logger import get_logger -from helm.core.rss_fetcher import SearchResults, SourceOutcome, TorrentItem, source_status -from helm.core.runtime import child_environment +from helm.config.config_manager import worker_count +from helm.logger import get_logger +from helm.search.rss_fetcher import SearchResults, SourceOutcome, TorrentItem, source_status +from helm.services.runtime import child_environment logger = get_logger(__name__) @@ -75,7 +75,7 @@ def run(job): if cancelled.is_set(): return SearchResults([], [SourceOutcome(job.source, "cancelled")]) process = subprocess.Popen( - [sys.executable, "-m", "helm.core.search_runner", "--worker"], + [sys.executable, "-m", "helm.search.search_runner", "--worker"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, @@ -134,7 +134,7 @@ def run(job): def execute_job(job, query, content_type): if job.kind == "inline": - from helm.core import lite_fetcher + from helm.search import lite_fetcher functions = { "apibay": lite_fetcher._fetch_apibay, @@ -143,7 +143,7 @@ def execute_job(job, query, content_type): } return functions[job.target](query) if job.kind == "plugin": - from helm.core.lite_plugin_loader import _execute_plugin, load_plugin + from helm.search.lite_plugin_loader import _execute_plugin, load_plugin plugin = load_plugin(job.target) return _execute_plugin(plugin, query, content_type) @@ -151,7 +151,7 @@ def execute_job(job, query, content_type): def worker(): - from helm.core.logger import configure_logging + from helm.logger import configure_logging # The parent captures and files these diagnostics at DEBUG. Workers never # rotate a shared log file or write directly into the user's console. diff --git a/src/helm/core/torrent_filter.py b/src/helm/search/torrent_filter.py similarity index 100% rename from src/helm/core/torrent_filter.py rename to src/helm/search/torrent_filter.py diff --git a/src/helm/services/__init__.py b/src/helm/services/__init__.py new file mode 100644 index 0000000..31a7dc4 --- /dev/null +++ b/src/helm/services/__init__.py @@ -0,0 +1 @@ +"""Job queue, HTTP server, watch folder and background daemons.""" diff --git a/src/helm/core/jobs.py b/src/helm/services/jobs.py similarity index 94% rename from src/helm/core/jobs.py rename to src/helm/services/jobs.py index 8b3b1f2..e42f186 100644 --- a/src/helm/core/jobs.py +++ b/src/helm/services/jobs.py @@ -12,10 +12,10 @@ from pathlib import Path, PurePosixPath from urllib.parse import urlsplit -from helm.core.config_manager import get_dl_dir, get_state_dir -from helm.core.runtime import child_environment, process_alive, process_start -from helm.core.secret_manager import redact_text -from helm.core.torrent_links import MAX_METADATA, metadata_source, validate_magnet +from helm.config.config_manager import get_dl_dir, get_state_dir +from helm.config.secret_manager import redact_text +from helm.services.runtime import child_environment, process_alive, process_start +from helm.torrents.torrent_links import MAX_METADATA, metadata_source, validate_magnet TERMINAL = {"succeeded", "failed", "cancelled"} RETRYABLE = ("failed", "cancelled") @@ -212,8 +212,8 @@ def job_tag(identifier): def execute_job(store, identifier): - from helm.core.lite_downloader import download_magnet - from helm.core.qbittorrent_client import SHARED_TAG, add_magnet + from helm.torrents.lite_downloader import download_magnet + from helm.torrents.qbittorrent_client import SHARED_TAG, add_magnet job = store.get(identifier) if job is None or job["status"] != "running": @@ -234,14 +234,14 @@ def execute_job(store, identifier): def cancel_job(store, identifier): """Cancel a job, and its qBittorrent torrent when one may have been submitted.""" - from helm.core.logger import get_logger + from helm.logger import get_logger job = store.get(identifier) if job is None: raise KeyError(identifier) changed = store.cancel(identifier) if changed and not job["lite"] and job["status"] in ("running", "submitted"): - from helm.core.qbittorrent_client import delete_tagged + from helm.torrents.qbittorrent_client import delete_tagged try: delete_tagged(job_tag(identifier)) @@ -251,7 +251,7 @@ def cancel_job(store, identifier): def process_one(store, stop=None, cancel_poll=1.0): - from helm.core.search_runner import stop_worker + from helm.search.search_runner import stop_worker stop = stop or threading.Event() job = store.claim() @@ -266,7 +266,7 @@ def process_one(store, stop=None, cancel_poll=1.0): with os.fdopen(fd, "wb") as stream: try: process = subprocess.Popen( - [sys.executable, "-m", "helm.core.jobs", "--worker", str(store.path), identifier], + [sys.executable, "-m", "helm.services.jobs", "--worker", str(store.path), identifier], stdin=subprocess.DEVNULL, stdout=stream, stderr=stream, @@ -298,7 +298,7 @@ def process_one(store, stop=None, cancel_poll=1.0): def host_path(save_path, name): """Map a path reported by qBittorrent, possibly inside its container, to this host.""" - from helm.core.settings import load_settings + from helm.config.settings import load_settings mount = PurePosixPath(load_settings().get("services.qbittorrent_downloads_root")) reported = PurePosixPath(save_path or mount) / name @@ -308,7 +308,7 @@ def host_path(save_path, name): def reconcile_qbittorrent(store): - from helm.core.qbittorrent_client import qb_request, tagged_torrents + from helm.torrents.qbittorrent_client import qb_request, tagged_torrents pending = store.with_status("submitted") if not pending: @@ -336,7 +336,7 @@ def reconcile_qbittorrent(store): def queue_loop(store, stop, reconcile_every=5): - from helm.core.logger import get_logger + from helm.logger import get_logger logger = get_logger(__name__) failures = 0 @@ -373,7 +373,7 @@ def exit_with_parent(parent, interval=1): if __name__ == "__main__": if len(sys.argv) != 4 or sys.argv[1] != "--worker": raise SystemExit("Internal job worker") - from helm.core.logger import configure_logging + from helm.logger import configure_logging threading.Thread(target=exit_with_parent, args=(os.getppid(),), daemon=True).start() configure_logging(file_logging=False, verbose=True) diff --git a/src/helm/core/runtime.py b/src/helm/services/runtime.py similarity index 98% rename from src/helm/core/runtime.py rename to src/helm/services/runtime.py index 228674e..47fa180 100644 --- a/src/helm/core/runtime.py +++ b/src/helm/services/runtime.py @@ -11,8 +11,8 @@ import uuid from pathlib import Path -from helm.core.config_manager import get_state_dir -from helm.core.secret_manager import redact_text +from helm.config.config_manager import get_state_dir +from helm.config.secret_manager import redact_text # Paths and settings a tmux server started earlier would otherwise not see. Secrets # are excluded because new-session arguments are visible in the process list. diff --git a/src/helm/core/server.py b/src/helm/services/server.py similarity index 97% rename from src/helm/core/server.py rename to src/helm/services/server.py index 783b97f..8968d1a 100644 --- a/src/helm/core/server.py +++ b/src/helm/services/server.py @@ -14,11 +14,11 @@ from pathlib import Path from urllib.parse import quote, unquote, urlsplit -from helm.core.config_manager import get_dl_dir -from helm.core.jobs import JobStore, cancel_job, public_job, queue_loop -from helm.core.logger import get_logger -from helm.core.secret_manager import get_secret, set_secrets -from helm.core.torrent_links import validate_magnet +from helm.config.config_manager import get_dl_dir +from helm.config.secret_manager import get_secret, set_secrets +from helm.logger import get_logger +from helm.services.jobs import JobStore, cancel_job, public_job, queue_loop +from helm.torrents.torrent_links import validate_magnet logger = get_logger(__name__) diff --git a/src/helm/core/watch.py b/src/helm/services/watch.py similarity index 95% rename from src/helm/core/watch.py rename to src/helm/services/watch.py index 387592b..0cfa63a 100644 --- a/src/helm/core/watch.py +++ b/src/helm/services/watch.py @@ -7,10 +7,10 @@ from pathlib import Path from urllib.parse import urlsplit -from helm.core.jobs import JobStore, process_one, queue_loop -from helm.core.logger import get_logger -from helm.core.secret_manager import redact_text -from helm.core.torrent_links import MAX_METADATA +from helm.config.secret_manager import redact_text +from helm.logger import get_logger +from helm.services.jobs import JobStore, process_one, queue_loop +from helm.torrents.torrent_links import MAX_METADATA logger = get_logger(__name__) diff --git a/src/helm/stack/__init__.py b/src/helm/stack/__init__.py new file mode 100644 index 0000000..d9b3ca0 --- /dev/null +++ b/src/helm/stack/__init__.py @@ -0,0 +1 @@ +"""Container stack setup, the compose template and one-shot mode.""" diff --git a/src/helm/core/compose.py b/src/helm/stack/compose.py similarity index 100% rename from src/helm/core/compose.py rename to src/helm/stack/compose.py diff --git a/src/helm/core/compose.template.yml b/src/helm/stack/compose.template.yml similarity index 98% rename from src/helm/core/compose.template.yml rename to src/helm/stack/compose.template.yml index 3901fc8..ad15050 100644 --- a/src/helm/core/compose.template.yml +++ b/src/helm/stack/compose.template.yml @@ -1,10 +1,10 @@ -#@ Template rules, shared by setup.sh (render_compose) and helm.core.compose: +#@ Template rules, shared by setup.sh (render_compose) and helm.stack.compose: #@ "if NAME" ... "end" marker lines keep what is between them only when #@ block NAME is on. Blocks nest. Lines starting with these markers never #@ reach the output. The four placeholders (state, downloads, config and #@ engine socket, each written between at-signs) become real paths, and #@ ${...} values are left for compose to fill in. -# Generated by Helm from src/helm/core/compose.template.yml. +# Generated by Helm from src/helm/stack/compose.template.yml. # Re-run ./setup.sh (or helm-torrent init) to change it instead of editing it. services: diff --git a/src/helm/core/oneshot.py b/src/helm/stack/oneshot.py similarity index 98% rename from src/helm/core/oneshot.py rename to src/helm/stack/oneshot.py index cc3222e..cde8204 100644 --- a/src/helm/core/oneshot.py +++ b/src/helm/stack/oneshot.py @@ -38,7 +38,7 @@ def spin_up_oneshot(): print(f"\n{T.BOLD}{T.INFO}Initializing One-Shot Ephemeral Stack...{T.RST}") print(f"{T.ITALIC}Bringing up Jackett, Prowlarr, Flaresolverr, and qBittorrent via docker compose...{T.RST}") - from helm.core.config_manager import get_state_dir + from helm.config.config_manager import get_state_dir state_dir = get_state_dir() compose_file = os.path.join(state_dir, "docker-compose.yml") @@ -145,7 +145,7 @@ def wait_for_download(): print(f"\n{T.INFO}Waiting for download to complete before tearing down the stack...{T.RST}") print(f"{T.ITALIC}(Press Ctrl+C to cancel, or Ctrl+P then Ctrl+Q to detach and run in background){T.RST}") - import helm.core.qbittorrent_client as qbc + import helm.torrents.qbittorrent_client as qbc # temporarily inject webui for the wait functionality qb_webui = os.environ.get("QB_WEBUI", "http://qbittorrent:18080") diff --git a/src/helm/core/stack_setup.py b/src/helm/stack/stack_setup.py similarity index 99% rename from src/helm/core/stack_setup.py rename to src/helm/stack/stack_setup.py index 4b184a9..7527a97 100644 --- a/src/helm/core/stack_setup.py +++ b/src/helm/stack/stack_setup.py @@ -21,7 +21,7 @@ from dataclasses import dataclass, field from typing import Dict, List, Optional, Tuple -from helm.core import compose +from helm.stack import compose IMAGE = "ghcr.io/piratebird/helm:latest" SERVICES = ("prowlarr", "jackett", "qbittorrent", "flaresolverr", "gluetun") @@ -576,7 +576,7 @@ def plan_from_args(args, settings_paths): def main(args): - from helm.core.config_manager import get_config_dir, get_dl_dir, get_state_dir + from helm.config.config_manager import get_config_dir, get_dl_dir, get_state_dir paths = ( os.path.abspath(get_state_dir()), diff --git a/src/helm/torrents/__init__.py b/src/helm/torrents/__init__.py new file mode 100644 index 0000000..65c1e5f --- /dev/null +++ b/src/helm/torrents/__init__.py @@ -0,0 +1 @@ +"""Torrent links, the Lite downloader and the qBittorrent client.""" diff --git a/src/helm/core/lite_downloader.py b/src/helm/torrents/lite_downloader.py similarity index 97% rename from src/helm/core/lite_downloader.py rename to src/helm/torrents/lite_downloader.py index 2a89c80..0d4f508 100644 --- a/src/helm/core/lite_downloader.py +++ b/src/helm/torrents/lite_downloader.py @@ -16,7 +16,7 @@ def download_magnet(magnet_link, save_path=None, on_complete=None): return False if save_path is None: - from helm.core.config_manager import get_dl_dir + from helm.config.config_manager import get_dl_dir save_path = get_dl_dir() save_path = os.path.abspath(os.path.expanduser(os.fspath(save_path))) @@ -36,7 +36,7 @@ def download_magnet(magnet_link, save_path=None, on_complete=None): "router.bittorrent.com:6881,router.utorrent.com:6881,dht.transmissionbt.com:6881,dht.aelitis.com:6881" ), } - from helm.core.torrent_links import resolve_torrent + from helm.torrents.torrent_links import resolve_torrent source = resolve_torrent(magnet_link) ses = lt.session(settings) diff --git a/src/helm/core/qbittorrent_client.py b/src/helm/torrents/qbittorrent_client.py similarity index 95% rename from src/helm/core/qbittorrent_client.py rename to src/helm/torrents/qbittorrent_client.py index 9d1fb25..9e3431a 100644 --- a/src/helm/core/qbittorrent_client.py +++ b/src/helm/torrents/qbittorrent_client.py @@ -11,10 +11,10 @@ import requests -from helm.core.logger import get_logger -from helm.core.secret_manager import get_secret -from helm.core.settings import get_qb_url, load_settings -from helm.core.torrent_links import resolve_torrent +from helm.config.secret_manager import get_secret +from helm.config.settings import get_qb_url, load_settings +from helm.logger import get_logger +from helm.torrents.torrent_links import resolve_torrent logger = get_logger(__name__) diff --git a/src/helm/core/torrent_links.py b/src/helm/torrents/torrent_links.py similarity index 99% rename from src/helm/core/torrent_links.py rename to src/helm/torrents/torrent_links.py index 8549791..7a5ab31 100644 --- a/src/helm/core/torrent_links.py +++ b/src/helm/torrents/torrent_links.py @@ -10,7 +10,7 @@ from bs4 import BeautifulSoup -from helm.core.http import get_shared_session +from helm.net.http import get_shared_session MAX_METADATA = 8 * 1024 * 1024 diff --git a/src/helm/ui/ansi.py b/src/helm/ui/ansi.py index ea73718..75ed783 100644 --- a/src/helm/ui/ansi.py +++ b/src/helm/ui/ansi.py @@ -131,7 +131,7 @@ def __init__(self): self._codes = None def _build(self): - from helm.core.settings import COLOR_NAMES, ConfigError, Settings, load_settings + from helm.config.settings import COLOR_NAMES, ConfigError, Settings, load_settings from helm.ui.theme import load_theme try: diff --git a/src/helm/ui/banner.py b/src/helm/ui/banner.py index 0a48351..12393d7 100644 --- a/src/helm/ui/banner.py +++ b/src/helm/ui/banner.py @@ -17,7 +17,7 @@ from dataclasses import dataclass, field from typing import List, Optional, Tuple -from helm.core.config_manager import get_config_dir, get_dl_dir, get_state_dir +from helm.config.config_manager import get_config_dir, get_dl_dir, get_state_dir # The current UI's block wordmark. LOGOS = { @@ -156,7 +156,7 @@ def _mode(settings, context): def _lite_sources(): - from helm.core.lite_plugin_loader import plugin_jobs + from helm.search.lite_plugin_loader import plugin_jobs bundled = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "plugins") return len(plugin_jobs([os.path.join(get_config_dir(), "plugins"), bundled])) @@ -167,7 +167,7 @@ def _manager_count(name, settings, timeout): import requests - from helm.core.secret_manager import get_secret + from helm.config.secret_manager import get_secret url = settings.get(f"services.{name}") key = get_secret(f"{name.upper()}_API_KEY") @@ -226,7 +226,7 @@ def _downloads(): def _services(settings, timeout): - from helm.core.config_commands import probe + from helm.config.config_commands import probe if settings.get("search.lite_only"): return "not used in Lite mode" diff --git a/src/helm/ui/theme.py b/src/helm/ui/theme.py index d9601d9..c88cfdf 100644 --- a/src/helm/ui/theme.py +++ b/src/helm/ui/theme.py @@ -11,7 +11,7 @@ from dataclasses import dataclass, field from typing import Dict -from helm.core.settings import COLOR_NAMES, HELM_COLORS +from helm.config.settings import COLOR_NAMES, HELM_COLORS PRESETS: Dict[str, Dict[str, str]] = { # The colours the UI used before themes existed, so the default look stays the same. diff --git a/src/helm/ui/tui.py b/src/helm/ui/tui.py index 8391822..2fd5210 100644 --- a/src/helm/ui/tui.py +++ b/src/helm/ui/tui.py @@ -88,7 +88,7 @@ def animate(): t = threading.Thread(target=animate) t.start() - from helm.core.rss_fetcher import SearchResults + from helm.search.rss_fetcher import SearchResults res = SearchResults() used_lite = lite_mode @@ -96,12 +96,12 @@ def animate(): import concurrent.futures def fetch_jackett(): - from helm.core.rss_fetcher import search_indexers + from helm.search.rss_fetcher import search_indexers return search_indexers(query, content_type, fallback_lite=False) def fetch_lite(): - from helm.core.lite_fetcher import search_lite + from helm.search.lite_fetcher import search_lite return search_lite(query, content_type) @@ -125,7 +125,7 @@ def fetch_lite(): try: res.extend(lite_future.result()) except Exception as error: - from helm.core.rss_fetcher import SourceOutcome, source_status + from helm.search.rss_fetcher import SourceOutcome, source_status res.outcomes.append(SourceOutcome("Lite", source_status(error))) else: diff --git a/tests/conftest.py b/tests/conftest.py index fe55ab2..31ba52c 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -13,7 +13,7 @@ def pytest_runtest_setup(item): # The secret manager caches the contents of secrets.env; make sure a cached # value from a previous test's temp dir never leaks into the next test. - import helm.core.secret_manager as sm + import helm.config.secret_manager as sm sm._invalidate_cache() import sys diff --git a/tests/test_benchmark.py b/tests/test_benchmark.py index de4de0f..68dbf2c 100644 --- a/tests/test_benchmark.py +++ b/tests/test_benchmark.py @@ -6,7 +6,7 @@ import pytest -from helm.core import benchmark +from helm.benchmarks import benchmark def fake_proc(root, pid, parent, name, pss): @@ -168,7 +168,7 @@ def test_published_raw_samples_have_valid_phases_and_checksums(filename): def test_benchmark_deadline_stops_worker(monkeypatch): - from helm.core import search_runner + from helm.search import search_runner process = Mock() process.poll.return_value = None diff --git a/tests/test_bittorrented_plugin.py b/tests/test_bittorrented_plugin.py index 4ef51da..811a9fc 100644 --- a/tests/test_bittorrented_plugin.py +++ b/tests/test_bittorrented_plugin.py @@ -8,7 +8,7 @@ import bittorrented # noqa: E402 import novaprinter # noqa: E402 -from helm.core.lite_plugin_loader import load_plugins # noqa: E402 +from helm.search.lite_plugin_loader import load_plugins # noqa: E402 BUNDLED_PLUGINS = os.path.abspath(os.path.join(os.path.dirname(__file__), "../src/helm/plugins")) API_URL = "https://bittorrented.com/api/search/torrents" diff --git a/tests/test_cli.py b/tests/test_cli.py index a0e2935..7da4fde 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -1,11 +1,14 @@ import json +import os import sys import tempfile import pytest import helm.cli -from helm.core.settings import Settings +import helm.cli.commands.session +import helm.cli.deps +from helm.config.settings import Settings class FakeItem: @@ -41,9 +44,9 @@ def test_search_json_output_is_machine_readable(monkeypatch, capsys): with tempfile.TemporaryDirectory() as tmp: monkeypatch.setenv("HELM_CONFIG_DIR", tmp) monkeypatch.setenv("JACKETT_API_KEY", "testkey") - monkeypatch.setattr(helm.cli, "ensure_config", lambda: None) + monkeypatch.setattr(helm.cli.deps, "ensure_config", lambda: None) monkeypatch.setattr( - helm.cli, + helm.cli.deps, "animated_search", lambda query, content_type, lite_mode=False, show_spinner=True: (_make_items(), True), ) @@ -67,9 +70,9 @@ def test_search_with_no_results_exits_one(monkeypatch, capsys): with tempfile.TemporaryDirectory() as tmp: monkeypatch.setenv("HELM_CONFIG_DIR", tmp) monkeypatch.setenv("JACKETT_API_KEY", "testkey") - monkeypatch.setattr(helm.cli, "ensure_config", lambda: None) + monkeypatch.setattr(helm.cli.deps, "ensure_config", lambda: None) monkeypatch.setattr( - helm.cli, + helm.cli.deps, "animated_search", lambda query, content_type, lite_mode=False, show_spinner=True: ([], False), ) @@ -95,7 +98,7 @@ def fake_search(query, content_type, lite_mode=False, show_spinner=True): captured["lite_mode"] = lite_mode return (_make_items(), lite_mode) - monkeypatch.setattr(helm.cli, "animated_search", fake_search) + monkeypatch.setattr(helm.cli.deps, "animated_search", fake_search) monkeypatch.setattr(sys, "argv", ["helm-torrent", "search", "--json", "ubuntu"]) with pytest.raises(SystemExit) as exc_info: @@ -122,8 +125,8 @@ def test_search_rejects_blank_query(monkeypatch, capsys, query): @pytest.mark.parametrize("has_raw_results", [False, True]) def test_empty_search_explains_sources_or_filters(monkeypatch, capsys, has_raw_results): items = _make_items() if has_raw_results else [] - monkeypatch.setattr(helm.cli, "animated_search", lambda *a, **kw: (items, True)) - monkeypatch.setattr(helm.cli, "load_settings", lambda: Settings.from_legacy({"min_seeds": 1000})) + monkeypatch.setattr(helm.cli.deps, "animated_search", lambda *a, **kw: (items, True)) + monkeypatch.setattr(helm.cli.deps, "load_settings", lambda: Settings.from_legacy({"min_seeds": 1000})) monkeypatch.setattr(sys, "argv", ["helm-torrent", "search", "--lite", "ubuntu"]) with pytest.raises(SystemExit) as exc_info: helm.cli.main() @@ -138,7 +141,7 @@ def test_empty_search_explains_sources_or_filters(monkeypatch, capsys, has_raw_r def test_lite_downloader_without_libtorrent_shows_magnet(monkeypatch, capsys): - from helm.core.lite_downloader import download_magnet + from helm.torrents.lite_downloader import download_magnet monkeypatch.setitem(sys.modules, "libtorrent", None) magnet = "magnet:?xt=urn:btih:cafe" @@ -153,7 +156,7 @@ def test_lite_downloader_without_legacy_dht_router_api(monkeypatch, tmp_path, ca from types import SimpleNamespace from unittest.mock import Mock - from helm.core import lite_downloader + from helm.torrents import lite_downloader # Match bindings that expose session settings but no add_dht_router method. session = Mock(spec=["add_torrent", "pause"]) @@ -197,13 +200,13 @@ def sleep(seconds): def test_bug_report_omits_unredactable_config(monkeypatch, tmp_path, capsys): import zipfile - from helm.core import config_manager, secret_manager + from helm.config import config_manager, secret_manager config_file = tmp_path / "config.json" config_file.write_text('{"JACKETT_API_KEY": "must-stay-private"}') monkeypatch.setattr(config_manager, "get_config_file", lambda: str(config_file)) monkeypatch.setattr(config_manager, "get_log_dir", lambda: str(tmp_path / "logs")) - monkeypatch.setattr(helm.cli.os.path, "expanduser", lambda path: str(tmp_path)) + monkeypatch.setattr(os.path, "expanduser", lambda path: str(tmp_path)) def failed_redaction(config): raise ValueError("Cannot redact") @@ -223,7 +226,7 @@ def test_search_rejects_invalid_options_before_setup(monkeypatch, capsys, argume from unittest.mock import Mock setup = Mock(side_effect=AssertionError("Validation must precede setup")) - monkeypatch.setattr(helm.cli, "load_settings", setup) + monkeypatch.setattr(helm.cli.deps, "load_settings", setup) monkeypatch.setattr(sys, "argv", ["helm-torrent", "search", "ubuntu"] + arguments) with pytest.raises(SystemExit) as error: helm.cli.main() @@ -235,7 +238,7 @@ def test_search_rejects_invalid_options_before_setup(monkeypatch, capsys, argume def test_cli_normalizes_content_type(monkeypatch): captured = [] monkeypatch.setattr( - helm.cli, "animated_search", lambda query, category, **kw: captured.append(category) or ([], True) + helm.cli.deps, "animated_search", lambda query, category, **kw: captured.append(category) or ([], True) ) monkeypatch.setattr(sys, "argv", ["helm-torrent", "search", "ubuntu", "--lite", "--json", "--type", "MUSIC"]) with pytest.raises(SystemExit) as error: @@ -248,14 +251,14 @@ def test_cli_normalizes_content_type(monkeypatch): def test_lite_oneshot_never_starts_or_stops_containers(monkeypatch, explicit_lite): from unittest.mock import Mock - from helm.core import oneshot + from helm.stack import oneshot start = Mock() stop = Mock() monkeypatch.setattr(oneshot, "spin_up_oneshot", start) monkeypatch.setattr(oneshot, "teardown_oneshot", stop) - monkeypatch.setattr(helm.cli, "load_settings", lambda: Settings.from_legacy({"LITE_MODE_ONLY": True})) - monkeypatch.setattr(helm.cli, "animated_search", lambda *a, **kw: (_make_items(), True)) + monkeypatch.setattr(helm.cli.deps, "load_settings", lambda: Settings.from_legacy({"LITE_MODE_ONLY": True})) + monkeypatch.setattr(helm.cli.deps, "animated_search", lambda *a, **kw: (_make_items(), True)) arguments = ["helm-torrent", "search", "ubuntu", "--oneshot", "--json"] monkeypatch.setattr(sys, "argv", arguments + (["--lite"] if explicit_lite else [])) with pytest.raises(SystemExit) as error: @@ -280,12 +283,12 @@ def test_lite_oneshot_never_starts_or_stops_containers(monkeypatch, explicit_lit ], ) def test_oneshot_cleans_up_once_on_every_exit(monkeypatch, outcome): - from helm.core import oneshot + from helm.stack import oneshot events = [] monkeypatch.setenv("JACKETT_API_KEY", "testkey") - monkeypatch.setattr(helm.cli, "ensure_config", lambda: None) - monkeypatch.setattr(helm.cli, "load_settings", lambda: Settings.from_legacy({"min_seeds": 3})) + monkeypatch.setattr(helm.cli.deps, "ensure_config", lambda: None) + monkeypatch.setattr(helm.cli.deps, "load_settings", lambda: Settings.from_legacy({"min_seeds": 3})) def start(): events.append("start") @@ -312,9 +315,9 @@ def wait(): monkeypatch.setattr(oneshot, "spin_up_oneshot", start) monkeypatch.setattr(oneshot, "teardown_oneshot", lambda: events.append("stop")) - monkeypatch.setattr(helm.cli, "animated_search", search) - monkeypatch.setattr(helm.cli, "_send_magnet", send) - monkeypatch.setattr(helm.cli, "wait_for_download", wait) + monkeypatch.setattr(helm.cli.deps, "animated_search", search) + monkeypatch.setattr(helm.cli.commands.session, "send_magnet", send) + monkeypatch.setattr(helm.cli.deps, "wait_for_download", wait) monkeypatch.setattr( sys, "argv", @@ -352,7 +355,7 @@ def test_download_uses_cli_directory_override(monkeypatch, tmp_path): ), ) destination = tmp_path / "custom downloads" - monkeypatch.setattr(helm.cli, "animated_search", lambda *a, **kw: (_make_items(), True)) + monkeypatch.setattr(helm.cli.deps, "animated_search", lambda *a, **kw: (_make_items(), True)) monkeypatch.setattr( sys, "argv", ["helm-torrent", "search", "ubuntu", "--lite", "--auto", "--dl-dir", str(destination)] ) @@ -365,7 +368,7 @@ def test_download_uses_cli_directory_override(monkeypatch, tmp_path): def test_real_search_fallback_keeps_json_stdout_clean(monkeypatch, capsys): - from helm.core import lite_fetcher, rss_fetcher + from helm.search import lite_fetcher, rss_fetcher items = _make_items() results = rss_fetcher.SearchResults(items, [rss_fetcher.SourceOutcome("Nyaa", "timeout")]) @@ -374,8 +377,8 @@ def unavailable(*args, **kwargs): raise RuntimeError("indexer unavailable with private-token") monkeypatch.setenv("JACKETT_API_KEY", "testkey") - monkeypatch.setattr(helm.cli, "load_settings", lambda: Settings.from_legacy({"min_seeds": 3})) - monkeypatch.setattr(helm.cli, "ensure_config", lambda: None) + monkeypatch.setattr(helm.cli.deps, "load_settings", lambda: Settings.from_legacy({"min_seeds": 3})) + monkeypatch.setattr(helm.cli.deps, "ensure_config", lambda: None) monkeypatch.setattr(rss_fetcher, "search_indexers", unavailable) monkeypatch.setattr(lite_fetcher, "search_lite", lambda query, content_type: results) monkeypatch.setattr(sys, "argv", ["helm-torrent", "search", "ubuntu", "--json"]) @@ -392,12 +395,13 @@ def unavailable(*args, **kwargs): def test_indexer_exit_cleans_up_once(monkeypatch): from types import SimpleNamespace - from helm.core import indexer_manager, oneshot + from helm.search import indexer_manager + from helm.stack import oneshot events = [] monkeypatch.setenv("JACKETT_API_KEY", "testkey") - monkeypatch.setattr(helm.cli, "ensure_config", lambda: None) - monkeypatch.setattr(helm.cli, "load_settings", lambda: Settings.from_legacy({})) + monkeypatch.setattr(helm.cli.deps, "ensure_config", lambda: None) + monkeypatch.setattr(helm.cli.deps, "load_settings", lambda: Settings.from_legacy({})) monkeypatch.setattr(oneshot, "spin_up_oneshot", lambda: events.append("start")) monkeypatch.setattr(oneshot, "teardown_oneshot", lambda: events.append("stop")) monkeypatch.setattr(indexer_manager, "JackettManager", lambda: SimpleNamespace(get_all_indexers=lambda: [])) @@ -408,7 +412,7 @@ def exit_indexers(*args): def end_input(*args): raise EOFError - monkeypatch.setattr(helm.cli, "interactive_indexer_selector", exit_indexers) + monkeypatch.setattr(helm.cli.deps, "interactive_indexer_selector", exit_indexers) monkeypatch.setattr("builtins.input", end_input) monkeypatch.setattr(sys, "argv", ["helm-torrent", "indexers", "--oneshot"]) with pytest.raises(SystemExit) as error: @@ -420,7 +424,7 @@ def end_input(*args): def test_bug_report_streams_and_redacts_historical_logs(monkeypatch, tmp_path): import zipfile - from helm.core import config_manager + from helm.config import config_manager config = tmp_path / "config.json" config.write_text('{"nested": {"password": "nested-private"}}') @@ -431,7 +435,7 @@ def test_bug_report_streams_and_redacts_historical_logs(monkeypatch, tmp_path): ) monkeypatch.setattr(config_manager, "get_config_file", lambda: str(config)) monkeypatch.setattr(config_manager, "get_log_dir", lambda: str(logs)) - monkeypatch.setattr(helm.cli.os.path, "expanduser", lambda path: str(tmp_path)) + monkeypatch.setattr(os.path, "expanduser", lambda path: str(tmp_path)) monkeypatch.setattr(sys, "argv", ["helm-torrent", "bug-report"]) with pytest.raises(SystemExit) as error: helm.cli.main() @@ -449,7 +453,7 @@ def test_cli_worker_limit_overrides_environment(monkeypatch): seen = [] monkeypatch.setenv("HELM_LITE_WORKERS", "6") monkeypatch.setattr( - helm.cli, "animated_search", lambda *a, **kw: seen.append(os.environ["HELM_LITE_WORKERS"]) or ([], True) + helm.cli.deps, "animated_search", lambda *a, **kw: seen.append(os.environ["HELM_LITE_WORKERS"]) or ([], True) ) monkeypatch.setattr(sys, "argv", ["helm-torrent", "search", "generated", "--lite", "--json", "--lite-workers", "2"]) with pytest.raises(SystemExit) as error: diff --git a/tests/test_config_commands.py b/tests/test_config_commands.py index f33bb9d..a311857 100644 --- a/tests/test_config_commands.py +++ b/tests/test_config_commands.py @@ -10,8 +10,8 @@ import pytest -from helm.core.config_commands import DESCRIPTIONS, redact_url, render_template -from helm.core.settings import FIELDS, flatten, load_settings, parse_jsonc, read_file +from helm.config.config_commands import DESCRIPTIONS, redact_url, render_template +from helm.config.settings import FIELDS, flatten, load_settings, parse_jsonc, read_file SRC = str(Path(__file__).resolve().parents[1] / "src") SCRUBBED = {field.env for field in FIELDS if field.env} | { @@ -364,7 +364,7 @@ def test_redact_url_leaves_plain_urls_alone(): def run_in_process(arguments, capsys): from helm.cli import build_parser - from helm.core import config_commands + from helm.config import config_commands args = build_parser().parse_args(["config", *arguments]) code = config_commands.run(args) diff --git a/tests/test_config_manager.py b/tests/test_config_manager.py index 6b74ded..96660b4 100644 --- a/tests/test_config_manager.py +++ b/tests/test_config_manager.py @@ -1,4 +1,4 @@ -from helm.core.config_manager import CONTENT_PROFILES, NEGATIVE_KEYWORDS +from helm.config.config_manager import CONTENT_PROFILES, NEGATIVE_KEYWORDS def test_negative_keywords_derived_from_other_categories(): diff --git a/tests/test_device_profile.py b/tests/test_device_profile.py index e9eaf8b..fbe6f4b 100644 --- a/tests/test_device_profile.py +++ b/tests/test_device_profile.py @@ -3,9 +3,9 @@ import pytest -import helm.core.device_profile as device -from helm.core.benchmark import binding_version -from helm.core.device_profile import battery_adb, battery_sysfs, cleanup_probe, energy_delta +import helm.benchmarks.device_profile as device +from helm.benchmarks.benchmark import binding_version +from helm.benchmarks.device_profile import battery_adb, battery_sysfs, cleanup_probe, energy_delta DISCHARGING = {"status": 3, "Charge counter": 2000000, "voltage": 4000, "USB powered": False} diff --git a/tests/test_eztv_plugin.py b/tests/test_eztv_plugin.py index ce6a443..32d2da5 100644 --- a/tests/test_eztv_plugin.py +++ b/tests/test_eztv_plugin.py @@ -8,7 +8,7 @@ import novaprinter # noqa: E402 -from helm.core.lite_plugin_loader import load_plugins # noqa: E402 +from helm.search.lite_plugin_loader import load_plugins # noqa: E402 BUNDLED_PLUGINS = os.path.abspath(os.path.join(os.path.dirname(__file__), "../src/helm/plugins")) API_URL = "https://eztvx.to/api/get-torrents" diff --git a/tests/test_headless_cli.py b/tests/test_headless_cli.py index 13e528a..0b584e1 100644 --- a/tests/test_headless_cli.py +++ b/tests/test_headless_cli.py @@ -64,7 +64,7 @@ def wait_for_health(port, timeout=20): def test_heavy_modules_stay_out_of_light_commands(environment): code = ( "import sys, helm.cli\n" - "print(sorted(m for m in ('requests', 'bs4', 'helm.ui.tui', 'helm.core.config_wizard') if m in sys.modules))" + "print(sorted(m for m in ('requests', 'bs4', 'helm.ui.tui', 'helm.config.config_wizard') if m in sys.modules))" ) result = subprocess.run([sys.executable, "-c", code], env=environment, capture_output=True, text=True, check=True) assert result.stdout.strip() == "[]" diff --git a/tests/test_jobs.py b/tests/test_jobs.py index 4b3c82e..8ef7ec3 100644 --- a/tests/test_jobs.py +++ b/tests/test_jobs.py @@ -11,10 +11,10 @@ import pytest import responses -import helm.core.jobs as jobs -import helm.core.qbittorrent_client as client -from helm.core.config_manager import get_dl_dir -from helm.core.jobs import ( +import helm.services.jobs as jobs +import helm.torrents.qbittorrent_client as client +from helm.config.config_manager import get_dl_dir +from helm.services.jobs import ( JobStore, cancel_job, execute_job, @@ -198,7 +198,7 @@ def test_public_job_redacts_and_hides_internals(store, monkeypatch): def test_execute_job_outcomes(store, monkeypatch): - import helm.core.lite_downloader as downloader + import helm.torrents.lite_downloader as downloader job = store.enqueue(MAGNET, lite=True) assert execute_job(store, job["id"]) == 1 # Not claimed. @@ -227,8 +227,8 @@ def test_execute_job_submits_with_shared_and_job_tags(store, qbittorrent): def write_worker(tmp_path, body): - """Install a fake helm.core.jobs worker module found through PYTHONPATH.""" - package = tmp_path / "fake" / "helm" / "core" + """Install a fake helm.services.jobs worker module found through PYTHONPATH.""" + package = tmp_path / "fake" / "helm" / "services" package.mkdir(parents=True) (package.parent / "__init__.py").write_text("") (package / "__init__.py").write_text("") @@ -428,7 +428,7 @@ def test_orphaned_worker_exits_when_its_parent_dies(tmp_path): marker = tmp_path / "pid" child = ( "import os,threading,time\n" - "from helm.core.jobs import exit_with_parent\n" + "from helm.services.jobs import exit_with_parent\n" "threading.Thread(target=exit_with_parent,args=(os.getppid(),0.05),daemon=True).start()\n" f"open({str(marker)!r},'w').write(str(os.getpid()))\n" "time.sleep(30)\n" diff --git a/tests/test_lite_fetcher.py b/tests/test_lite_fetcher.py index 26f5194..41c3e20 100644 --- a/tests/test_lite_fetcher.py +++ b/tests/test_lite_fetcher.py @@ -3,15 +3,15 @@ import pytest import responses -from helm.core.lite_fetcher import search_all_plugins, search_lite +from helm.search.lite_fetcher import search_all_plugins, search_lite @pytest.fixture(autouse=True) def inline_sources_in_process(monkeypatch): # Parsing/HTTP unit tests execute synchronously; subprocess behavior has its # own integration tests with real workers and disposable fixture plugins. - from helm.core import lite_plugin_loader, search_runner - from helm.core.rss_fetcher import SearchResults + from helm.search import lite_plugin_loader, search_runner + from helm.search.rss_fetcher import SearchResults monkeypatch.setattr(lite_plugin_loader, "plugin_jobs", lambda directories: []) @@ -61,7 +61,7 @@ def run(jobs, query, content_type="video", **kwargs): @responses.activate def test_search_lite_aggregates_all_sources(monkeypatch): - monkeypatch.setattr("helm.core.lite_plugin_loader.run_plugins", lambda query, dirs: []) + monkeypatch.setattr("helm.search.lite_plugin_loader.run_plugins", lambda query, dirs: []) responses.add( responses.GET, @@ -101,10 +101,10 @@ def test_search_lite_aggregates_all_sources(monkeypatch): def test_search_all_plugins_delegates_to_search_lite(monkeypatch): - from helm.core.rss_fetcher import TorrentItem + from helm.search.rss_fetcher import TorrentItem item = TorrentItem("Ubuntu 24.04 ISO", "magnet:?xt=urn:btih:cafe", 42, 7, 999) - monkeypatch.setattr("helm.core.lite_fetcher.search_lite", lambda query, content_type: [item]) + monkeypatch.setattr("helm.search.lite_fetcher.search_lite", lambda query, content_type: [item]) result = asyncio.run(search_all_plugins("ubuntu", "video")) @@ -115,13 +115,15 @@ def test_search_lite_rejects_empty_queries_without_network(monkeypatch): def unexpected_search(query, content_type): raise AssertionError("Blank queries must not reach sources") - monkeypatch.setattr("helm.core.lite_fetcher._collect_all", unexpected_search) + monkeypatch.setattr("helm.search.lite_fetcher._collect_all", unexpected_search) assert search_lite(" \t\n") == [] def test_search_lite_trims_query(monkeypatch): queries = [] - monkeypatch.setattr("helm.core.lite_fetcher._collect_all", lambda query, content_type: queries.append(query) or []) + monkeypatch.setattr( + "helm.search.lite_fetcher._collect_all", lambda query, content_type: queries.append(query) or [] + ) assert search_lite(" ubuntu ") == [] assert queries == ["ubuntu"] @@ -130,7 +132,7 @@ def test_search_lite_trims_query(monkeypatch): def test_nyaa_timeout_preserves_other_source_results(monkeypatch): import requests - monkeypatch.setattr("helm.core.lite_plugin_loader.run_plugins", lambda query, dirs: []) + monkeypatch.setattr("helm.search.lite_plugin_loader.run_plugins", lambda query, dirs: []) responses.add(responses.GET, "https://apibay.org/q.php", json=[APITBAY_ITEM]) responses.add(responses.GET, "https://torrents-csv.com/service/search", json={"torrents": [CSV_ITEM]}) responses.add(responses.GET, "https://nyaa.si/", body=requests.exceptions.ConnectTimeout("Nyaa timed out")) @@ -139,7 +141,7 @@ def test_nyaa_timeout_preserves_other_source_results(monkeypatch): def test_search_uses_one_budget_for_inline_and_plugin_jobs(monkeypatch): - from helm.core import lite_plugin_loader, search_runner + from helm.search import lite_plugin_loader, search_runner jobs_seen = [] plugin = search_runner.SearchJob("Fixture", "plugin", "fixture.py") @@ -161,7 +163,7 @@ def run(jobs, query, content_type, timeout): def test_search_outcomes_distinguish_source_failures(monkeypatch): import requests - monkeypatch.setattr("helm.core.lite_plugin_loader.run_plugins", lambda query, dirs: []) + monkeypatch.setattr("helm.search.lite_plugin_loader.run_plugins", lambda query, dirs: []) responses.add(responses.GET, "https://apibay.org/q.php", json=[]) responses.add(responses.GET, "https://torrents-csv.com/service/search", status=503) responses.add(responses.GET, "https://nyaa.si/", body=requests.exceptions.ConnectTimeout("private URL")) @@ -176,7 +178,7 @@ def test_search_outcomes_distinguish_source_failures(monkeypatch): @responses.activate def test_parse_failure_keeps_successful_sources_and_counts(monkeypatch): - monkeypatch.setattr("helm.core.lite_plugin_loader.run_plugins", lambda query, dirs: []) + monkeypatch.setattr("helm.search.lite_plugin_loader.run_plugins", lambda query, dirs: []) responses.add(responses.GET, "https://apibay.org/q.php", json=[APITBAY_ITEM]) responses.add(responses.GET, "https://torrents-csv.com/service/search", body="not-json") responses.add(responses.GET, "https://nyaa.si/", body="broken XML") @@ -190,8 +192,8 @@ def test_parse_failure_keeps_successful_sources_and_counts(monkeypatch): def test_search_outcomes_do_not_leak_between_calls(monkeypatch): - from helm.core import lite_fetcher - from helm.core.rss_fetcher import SearchResults, SourceOutcome + from helm.search import lite_fetcher + from helm.search.rss_fetcher import SearchResults, SourceOutcome monkeypatch.setattr( lite_fetcher, "_fetch_apibay", lambda query: SearchResults([], [SourceOutcome("Apibay", query)]) diff --git a/tests/test_lite_plugin_loader.py b/tests/test_lite_plugin_loader.py index 19bbce5..72b8b86 100644 --- a/tests/test_lite_plugin_loader.py +++ b/tests/test_lite_plugin_loader.py @@ -12,7 +12,7 @@ import novaprinter # noqa: E402 -from helm.core.lite_plugin_loader import run_plugins # noqa: E402 +from helm.search.lite_plugin_loader import run_plugins # noqa: E402 # A dummy plugin script mimicking a qBittorrent plugin DUMMY_PLUGIN_CODE = """ @@ -114,7 +114,7 @@ def test_run_plugins_does_not_leak_between_runs(plugin_dir): def test_reused_worker_keeps_previous_plugin_results(): from concurrent.futures import ThreadPoolExecutor - from helm.core.lite_plugin_loader import _execute_plugin + from helm.search.lite_plugin_loader import _execute_plugin class Plugin: def search(self, query): @@ -132,7 +132,7 @@ def test_plugin_error_retains_partial_results_and_outcome(): import requests - from helm.core.lite_plugin_loader import _execute_plugin + from helm.search.lite_plugin_loader import _execute_plugin class Plugin: name = "Partial" diff --git a/tests/test_logger.py b/tests/test_logger.py index 4d92cde..ccf0325 100644 --- a/tests/test_logger.py +++ b/tests/test_logger.py @@ -4,7 +4,7 @@ sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "../src"))) -from helm.core.logger import FileOnlyFilter +from helm.logger import FileOnlyFilter def test_file_only_filter_drops_file_only_records(): @@ -58,7 +58,7 @@ def test_importing_logging_does_not_create_files(tmp_path): PYTHONPATH=root, HELM_CONFIG_DIR=str(tmp_path / "config"), HELM_STATE_DIR=str(tmp_path / "state") ) result = subprocess.run( - [sys.executable, "-c", "import helm.cli; import helm.core.lite_fetcher"], + [sys.executable, "-c", "import helm.cli; import helm.search.lite_fetcher"], env=environment, capture_output=True, text=True, @@ -69,7 +69,7 @@ def test_importing_logging_does_not_create_files(tmp_path): def test_logging_reconfigures_after_path_override(monkeypatch, tmp_path): - from helm.core.logger import configure_logging, get_logger + from helm.logger import configure_logging, get_logger first, second = tmp_path / "first", tmp_path / "second" monkeypatch.setenv("HELM_STATE_DIR", str(first)) @@ -84,7 +84,7 @@ def test_logging_reconfigures_after_path_override(monkeypatch, tmp_path): def test_formatters_redact_exception_and_structured_extras(monkeypatch): - from helm.core.logger import ConsoleFormatter, JSONFormatter, PlainTextFormatter + from helm.logger import ConsoleFormatter, JSONFormatter, PlainTextFormatter monkeypatch.setenv("JACKETT_API_KEY", "private-key-123") try: @@ -107,7 +107,7 @@ def test_formatters_redact_exception_and_structured_extras(monkeypatch): def test_tail_reads_only_bounded_suffix_and_redacts(tmp_path, monkeypatch): - from helm.core.logger import tail_log + from helm.logger import tail_log path = tmp_path / "large.log" path.write_text("old line\n" * 200000 + "apikey=old-unknown-secret\nlast line\n") @@ -120,7 +120,7 @@ def test_tail_reads_only_bounded_suffix_and_redacts(tmp_path, monkeypatch): def test_tail_handles_a_single_oversized_record(tmp_path): - from helm.core.logger import tail_log + from helm.logger import tail_log path = tmp_path / "huge.log" path.write_text("x" * 10000) diff --git a/tests/test_module_paths.py b/tests/test_module_paths.py new file mode 100644 index 0000000..ce7779f --- /dev/null +++ b/tests/test_module_paths.py @@ -0,0 +1,46 @@ +"""The package layout, and the old paths kept for Lite plugins.""" + +import importlib +import pkgutil +from pathlib import Path + +import helm + +PACKAGES = ("benchmarks", "cli", "config", "core", "net", "plugins", "search", "services", "stack", "torrents", "ui") + + +def test_old_plugin_paths_point_at_the_same_objects(): + from helm.core import http, logger, rss_fetcher + from helm.logger import get_logger + from helm.net.http import get_shared_session + from helm.search.rss_fetcher import TorrentItem, source_status + + assert http.get_shared_session is get_shared_session + assert logger.get_logger is get_logger + assert rss_fetcher.TorrentItem is TorrentItem + assert rss_fetcher.source_status is source_status + + +def test_core_keeps_only_the_plugin_modules(): + core = Path(helm.__file__).parent / "core" + assert sorted(p.stem for p in core.glob("*.py")) == ["__init__", "http", "logger", "rss_fetcher"] + + +def test_every_package_imports(): + root = Path(helm.__file__).parent + found = sorted(p.name for p in root.iterdir() if (p / "__init__.py").is_file()) + assert found == sorted(PACKAGES) + for package in PACKAGES: + if package == "plugins": + continue # plugins are loaded one by one in worker processes + module = importlib.import_module(f"helm.{package}") + for info in pkgutil.walk_packages(module.__path__, prefix=f"helm.{package}."): + if not info.name.endswith(".__main__"): + importlib.import_module(info.name) + + +def test_cli_has_one_module_per_command_group(): + import helm.cli.commands as commands + + names = sorted(info.name for info in pkgutil.iter_modules(commands.__path__)) + assert names == ["background", "banner", "headless", "indexers", "session", "status", "utility"] diff --git a/tests/test_prowlarr_manager.py b/tests/test_prowlarr_manager.py index 236b401..4073c8a 100644 --- a/tests/test_prowlarr_manager.py +++ b/tests/test_prowlarr_manager.py @@ -1,7 +1,7 @@ import pytest import responses -from helm.core.indexer_manager import ProwlarrManager +from helm.search.indexer_manager import ProwlarrManager @pytest.fixture(autouse=True) diff --git a/tests/test_qbittorrent_client.py b/tests/test_qbittorrent_client.py index 92b8365..6c5bb3a 100644 --- a/tests/test_qbittorrent_client.py +++ b/tests/test_qbittorrent_client.py @@ -3,8 +3,8 @@ import pytest import responses -import helm.core.qbittorrent_client as client -from helm.core.qbittorrent_client import add_magnet, delete_tagged, login_qbittorrent, qb_request +import helm.torrents.qbittorrent_client as client +from helm.torrents.qbittorrent_client import add_magnet, delete_tagged, login_qbittorrent, qb_request BASE = "http://localhost:8080" MAGNET = "magnet:?xt=urn:btih:" + "a" * 40 diff --git a/tests/test_rss_fetcher.py b/tests/test_rss_fetcher.py index c7ad348..5c83c49 100644 --- a/tests/test_rss_fetcher.py +++ b/tests/test_rss_fetcher.py @@ -1,5 +1,5 @@ -import helm.core.rss_fetcher as rf -from helm.core.rss_fetcher import TorrentItem, _parse_feed, search_jackett +import helm.search.rss_fetcher as rf +from helm.search.rss_fetcher import TorrentItem, _parse_feed, search_jackett TORZNAB_FEED = """ @@ -67,8 +67,9 @@ def test_search_jackett_returns_empty_without_api_key(monkeypatch): def test_search_indexers_falls_back_to_lite_when_manager_returns_nothing(monkeypatch): - from helm.core import lite_fetcher, settings - from helm.core.rss_fetcher import TorrentItem + from helm.config import settings + from helm.search import lite_fetcher + from helm.search.rss_fetcher import TorrentItem monkeypatch.setattr( settings, "load_settings", lambda: settings.Settings.from_legacy({"INDEXER_MANAGER": "jackett"}) @@ -85,8 +86,9 @@ def test_search_indexers_falls_back_to_lite_when_manager_returns_nothing(monkeyp def test_search_indexers_falls_back_to_lite_with_prowlarr_manager(monkeypatch): - from helm.core import lite_fetcher, settings - from helm.core.rss_fetcher import TorrentItem + from helm.config import settings + from helm.search import lite_fetcher + from helm.search.rss_fetcher import TorrentItem monkeypatch.setattr( settings, "load_settings", lambda: settings.Settings.from_legacy({"INDEXER_MANAGER": "prowlarr"}) diff --git a/tests/test_runtime.py b/tests/test_runtime.py index d2cab30..5d745ee 100644 --- a/tests/test_runtime.py +++ b/tests/test_runtime.py @@ -13,9 +13,9 @@ import pytest -import helm.core.runtime as runtime -from helm.core.config_manager import get_state_dir -from helm.core.runtime import ( +import helm.services.runtime as runtime +from helm.config.config_manager import get_state_dir +from helm.services.runtime import ( child_arguments, child_environment, daemon_records, diff --git a/tests/test_scraper_fixtures.py b/tests/test_scraper_fixtures.py index 8e25327..0430b84 100644 --- a/tests/test_scraper_fixtures.py +++ b/tests/test_scraper_fixtures.py @@ -7,7 +7,7 @@ import requests import responses -from helm.core.lite_plugin_loader import _execute_plugin, load_plugin, plugin_categories +from helm.search.lite_plugin_loader import _execute_plugin, load_plugin, plugin_categories PLUGIN_DIR = Path(__file__).resolve().parents[1] / "src" / "helm" / "plugins" sys.path.insert(0, str(PLUGIN_DIR)) @@ -132,7 +132,7 @@ def search(self, query, cat="all"): @responses.activate def test_unknown_subsplease_seeders_survive_filter(): - from helm.core.torrent_filter import filter_items + from helm.search.torrent_filter import filter_items plugin = load_plugin(str(PLUGIN_DIR / "subsplease.py")) responses.add( @@ -150,7 +150,7 @@ def test_unknown_subsplease_seeders_survive_filter(): def test_http_sessions_are_reused_per_thread_but_not_shared(): import threading - from helm.core.http import get_shared_session + from helm.net.http import get_shared_session main = get_shared_session() assert main is get_shared_session() diff --git a/tests/test_search_runner.py b/tests/test_search_runner.py index c50d646..4578405 100644 --- a/tests/test_search_runner.py +++ b/tests/test_search_runner.py @@ -7,7 +7,7 @@ import pytest -from helm.core.search_runner import SearchJob, run_searches +from helm.search.search_runner import SearchJob, run_searches def make_plugin(tmp_path, name, body): @@ -42,7 +42,7 @@ def test_stalled_worker_cannot_delay_process_exit(tmp_path): environment = os.environ.copy() environment["PYTHONPATH"] = str(Path(__file__).resolve().parents[1] / "src") code = """import json -from helm.core.search_runner import SearchJob, run_searches +from helm.search.search_runner import SearchJob, run_searches jobs = [SearchJob(**job) for job in json.loads(__import__('sys').argv[1])] result = run_searches(jobs, 'generated', timeout=1) print(json.dumps({'titles': [i.title for i in result], 'outcomes': [(o.source, o.status) for o in result.outcomes]})) @@ -98,7 +98,7 @@ def test_invalid_worker_limits(timeout, workers): def test_keyboard_interrupt_reaps_workers(monkeypatch, tmp_path): import concurrent.futures - import helm.core.search_runner as runner + import helm.search.search_runner as runner job = make_plugin(tmp_path, "stalled", "import time\ntime.sleep(20)") original = concurrent.futures.Future.result @@ -156,7 +156,7 @@ def test_windows_cleanup_uses_tree_termination(monkeypatch): from types import SimpleNamespace from unittest.mock import Mock - import helm.core.search_runner as runner + import helm.search.search_runner as runner process = Mock() process.pid = 123 @@ -177,7 +177,7 @@ def test_invalid_job_kind_reports_failure(tmp_path): def test_worker_limit_environment_and_explicit_override(monkeypatch): - from helm.core.search_runner import worker_count + from helm.search.search_runner import worker_count monkeypatch.setenv("HELM_LITE_WORKERS", "2") assert worker_count() == 2 @@ -190,7 +190,7 @@ def test_worker_limit_environment_and_explicit_override(monkeypatch): def test_worker_errors_reach_parent_log_with_secrets_redacted(monkeypatch, tmp_path): - from helm.core.logger import configure_logging + from helm.logger import configure_logging logs = tmp_path / "logs" monkeypatch.setenv("HELM_STATE_DIR", str(logs)) diff --git a/tests/test_secret_manager.py b/tests/test_secret_manager.py index c33a9cd..ef2ee73 100644 --- a/tests/test_secret_manager.py +++ b/tests/test_secret_manager.py @@ -1,7 +1,7 @@ import os import tempfile -from helm.core.secret_manager import ( +from helm.config.secret_manager import ( get_secret, get_secrets_file, load_secrets, @@ -97,7 +97,7 @@ def test_sanitize_link_leaves_magnets_alone(): def test_secrets_cache_follows_config_override(monkeypatch, tmp_path): - from helm.core import secret_manager + from helm.config import secret_manager first, second = tmp_path / "first", tmp_path / "second" first.mkdir() @@ -112,7 +112,7 @@ def test_secrets_cache_follows_config_override(monkeypatch, tmp_path): def test_redaction_handles_nested_config_and_encoded_secrets(monkeypatch): - from helm.core.secret_manager import redact_config, redact_text + from helm.config.secret_manager import redact_config, redact_text monkeypatch.setenv("QB_PASSWORD", "p@ss word") original = { diff --git a/tests/test_server.py b/tests/test_server.py index 9c9a33c..e393069 100644 --- a/tests/test_server.py +++ b/tests/test_server.py @@ -10,11 +10,11 @@ import pytest import requests -import helm.core.server as server_module -from helm.core.config_manager import get_dl_dir -from helm.core.jobs import JobStore -from helm.core.secret_manager import get_secret -from helm.core.server import byte_range, is_loopback, make_server, run_server +import helm.services.server as server_module +from helm.config.config_manager import get_dl_dir +from helm.config.secret_manager import get_secret +from helm.services.jobs import JobStore +from helm.services.server import byte_range, is_loopback, make_server, run_server TOKEN = "t" * 32 AUTH = {"Authorization": "Bearer " + TOKEN} diff --git a/tests/test_service_boundaries.py b/tests/test_service_boundaries.py index d0ef386..4fd5acf 100644 --- a/tests/test_service_boundaries.py +++ b/tests/test_service_boundaries.py @@ -9,11 +9,11 @@ import pytest -import helm.core.config_wizard as wizard -import helm.core.oneshot as oneshot -from helm.core.config_manager import get_state_dir -from helm.core.secret_manager import get_secret -from helm.core.settings import load_settings, remember +import helm.config.config_wizard as wizard +import helm.stack.oneshot as oneshot +from helm.config.config_manager import get_state_dir +from helm.config.secret_manager import get_secret +from helm.config.settings import load_settings, remember def install_engine(tmp_path, monkeypatch, status): diff --git a/tests/test_settings.py b/tests/test_settings.py index 7da34b7..3efe5da 100644 --- a/tests/test_settings.py +++ b/tests/test_settings.py @@ -7,9 +7,9 @@ import pytest -from helm.core import settings as settings_module -from helm.core.secret_manager import get_secret -from helm.core.settings import ( +from helm.config import settings as settings_module +from helm.config.secret_manager import get_secret +from helm.config.settings import ( BY_PATH, FIELDS, ConfigError, @@ -455,7 +455,7 @@ def test_config_worker_count_reaches_the_process(config_dir): ], ) def test_banner_and_theme_values_are_accepted(path, value, expected): - from helm.core.settings import check + from helm.config.settings import check assert check(BY_PATH[path], value) == expected @@ -481,7 +481,7 @@ def test_banner_and_theme_values_are_accepted(path, value, expected): ], ) def test_banner_and_theme_values_are_rejected(path, value, message): - from helm.core.settings import check + from helm.config.settings import check with pytest.raises(ValueError, match=message): check(BY_PATH[path], value) diff --git a/tests/test_setup_script.py b/tests/test_setup_script.py index 6b5530e..29b6be8 100644 --- a/tests/test_setup_script.py +++ b/tests/test_setup_script.py @@ -16,7 +16,7 @@ import pytest import yaml -from helm.core import compose, stack_setup +from helm.stack import compose, stack_setup ROOT = Path(__file__).resolve().parents[1] SETUP = ROOT / "setup.sh" @@ -225,7 +225,7 @@ def test_docker_compose_accepts_every_rendered_file(tmp_path): def test_template_ships_as_package_data(): - assert '"helm.core" = ["compose.template.yml"]' in (ROOT / "pyproject.toml").read_text() + assert '"helm.stack" = ["compose.template.yml"]' in (ROOT / "pyproject.toml").read_text() assert compose.TEMPLATE.is_file() diff --git a/tests/test_stack_benchmark.py b/tests/test_stack_benchmark.py index a545877..21d8350 100644 --- a/tests/test_stack_benchmark.py +++ b/tests/test_stack_benchmark.py @@ -12,8 +12,8 @@ import requests import responses -import helm.core.stack_benchmark as stack_benchmark -from helm.core.stack_benchmark import ( +import helm.benchmarks.stack_benchmark as stack_benchmark +from helm.benchmarks.stack_benchmark import ( DEFAULT_IMAGES, Stack, cgroup_path, @@ -23,7 +23,7 @@ scrub_logs, verify_limits, ) -from helm.core.torrent_links import metadata_source +from helm.torrents.torrent_links import metadata_source def test_default_images_cover_every_service(): diff --git a/tests/test_subsplease_plugin.py b/tests/test_subsplease_plugin.py index ac88855..549971d 100644 --- a/tests/test_subsplease_plugin.py +++ b/tests/test_subsplease_plugin.py @@ -8,7 +8,7 @@ import novaprinter # noqa: E402 import subsplease # noqa: E402 -from helm.core.lite_plugin_loader import load_plugins # noqa: E402 +from helm.search.lite_plugin_loader import load_plugins # noqa: E402 BUNDLED_PLUGINS = os.path.abspath(os.path.join(os.path.dirname(__file__), "../src/helm/plugins")) API_URL = "https://subsplease.org/api/" diff --git a/tests/test_terminal_codes.py b/tests/test_terminal_codes.py index 5f643db..7e3df4f 100644 --- a/tests/test_terminal_codes.py +++ b/tests/test_terminal_codes.py @@ -8,8 +8,10 @@ import pytest import helm.cli -from helm.core.settings import FIELDS -from helm.ui.ansi import CONTROLS, Terminal, sgr +import helm.cli.deps +from helm.cli.commands import banner as banner_command +from helm.config.settings import FIELDS +from helm.ui.ansi import CONTROLS, T, Terminal, sgr from helm.ui.banner import LOGOS from helm.ui.theme import PRESETS @@ -24,9 +26,9 @@ def home(tmp_path, monkeypatch): (tmp_path / "config").mkdir() for key in {field.env for field in FIELDS if field.env} | {"NO_COLOR", "FORCE_COLOR"}: monkeypatch.delenv(key, raising=False) - helm.cli.T.reset() + T.reset() yield tmp_path - helm.cli.T.reset() + T.reset() class Tty(io.StringIO): @@ -114,9 +116,9 @@ def items(): def test_json_stdout_stays_pure_with_colours_forced(home, monkeypatch, capsys, found): monkeypatch.setenv("FORCE_COLOR", "1") monkeypatch.setenv("JACKETT_API_KEY", "testkey") - monkeypatch.setattr(helm.cli, "ensure_config", lambda: None) + monkeypatch.setattr(helm.cli.deps, "ensure_config", lambda: None) monkeypatch.setattr( - helm.cli, + helm.cli.deps, "animated_search", lambda query, content_type, lite_mode=False, show_spinner=True: (items() if found else [], True), ) @@ -140,7 +142,7 @@ def args(**values): def test_ui_header_shows_banner_when_enabled(home, capsys): (home / "config" / "config.toml").write_text('[banner]\nmodules = ["mode"]\n') - helm.cli._print_header(args(lite=True), "THE HELM - Torrent automation MVP") + banner_command.print_header(args(lite=True), "THE HELM - Torrent automation MVP") out = capsys.readouterr().out assert LOGOS["helm"][0] in out assert re.search(r"Mode\s+lite", out) @@ -150,7 +152,7 @@ def test_ui_header_shows_banner_when_enabled(home, capsys): def test_ui_header_shows_plain_wordmark_when_disabled(home, capsys): (home / "config" / "config.toml").write_text("[banner]\nenabled = false\n") - helm.cli._print_header(args(oneshot=True), "subtitle") + banner_command.print_header(args(oneshot=True), "subtitle") out = capsys.readouterr().out assert LOGOS["helm"][0] in out assert "Mode" not in out @@ -158,6 +160,6 @@ def test_ui_header_shows_plain_wordmark_when_disabled(home, capsys): def test_banner_mode_context(home): - assert helm.cli._banner_context(args(lite=True)) == {"mode": "lite"} - assert helm.cli._banner_context(args(oneshot=True)) == {"mode": "one-shot"} - assert helm.cli._banner_context(args()) == {} + assert banner_command.banner_context(args(lite=True)) == {"mode": "lite"} + assert banner_command.banner_context(args(oneshot=True)) == {"mode": "one-shot"} + assert banner_command.banner_context(args()) == {} diff --git a/tests/test_theme_banner.py b/tests/test_theme_banner.py index 14b2318..373eb26 100644 --- a/tests/test_theme_banner.py +++ b/tests/test_theme_banner.py @@ -10,7 +10,7 @@ import pytest -from helm.core.settings import BY_PATH, COLOR_NAMES, FIELDS, HEX_COLOR, THEMES, Settings, check +from helm.config.settings import BY_PATH, COLOR_NAMES, FIELDS, HEX_COLOR, THEMES, Settings, check from helm.ui.ansi import color_enabled, render_banner, sgr, visible_width from helm.ui.banner import ( LOGOS, @@ -256,7 +256,7 @@ def test_mode_follows_context_and_manager(home): def test_jobs_module_counts_active_jobs(home): - from helm.core.jobs import JobStore + from helm.services.jobs import JobStore store = JobStore() magnets = [f"magnet:?xt=urn:btih:{str(index) * 40}" for index in range(4)] diff --git a/tests/test_torrent_filter.py b/tests/test_torrent_filter.py index 959426f..d817585 100644 --- a/tests/test_torrent_filter.py +++ b/tests/test_torrent_filter.py @@ -3,7 +3,7 @@ sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "../src"))) -from helm.core.torrent_filter import dedupe, filter_items +from helm.search.torrent_filter import dedupe, filter_items class MockItem: diff --git a/tests/test_torrent_links.py b/tests/test_torrent_links.py index ee0d3b8..39788e5 100644 --- a/tests/test_torrent_links.py +++ b/tests/test_torrent_links.py @@ -6,8 +6,8 @@ import pytest -from helm.core import torrent_links -from helm.core.torrent_links import ( +from helm.torrents import torrent_links +from helm.torrents.torrent_links import ( TorrentSource, decode_metadata, info_hash, diff --git a/tests/test_watch.py b/tests/test_watch.py index e91485c..723b02f 100644 --- a/tests/test_watch.py +++ b/tests/test_watch.py @@ -4,9 +4,9 @@ import pytest -import helm.core.watch as watch -from helm.core.jobs import JobStore -from helm.core.watch import run_watch, safe_scan, scan_directory +import helm.services.watch as watch +from helm.services.jobs import JobStore +from helm.services.watch import run_watch, safe_scan, scan_directory MAGNET = "magnet:?xt=urn:btih:" + "a" * 40 OTHER = "magnet:?xt=urn:btih:" + "b" * 40 diff --git a/tests/test_x1337_plugin.py b/tests/test_x1337_plugin.py index 8295202..e1c5f05 100644 --- a/tests/test_x1337_plugin.py +++ b/tests/test_x1337_plugin.py @@ -9,7 +9,7 @@ import novaprinter # noqa: E402 import x1337 # noqa: E402 -from helm.core.lite_plugin_loader import load_plugins # noqa: E402 +from helm.search.lite_plugin_loader import load_plugins # noqa: E402 BUNDLED_PLUGINS = os.path.abspath(os.path.join(os.path.dirname(__file__), "../src/helm/plugins")) diff --git a/tests/test_yts_plugin.py b/tests/test_yts_plugin.py index 1d53e4f..d6bbef7 100644 --- a/tests/test_yts_plugin.py +++ b/tests/test_yts_plugin.py @@ -7,7 +7,7 @@ import novaprinter # noqa: E402 -from helm.core.lite_plugin_loader import load_plugins # noqa: E402 +from helm.search.lite_plugin_loader import load_plugins # noqa: E402 BUNDLED_PLUGINS = os.path.abspath(os.path.join(os.path.dirname(__file__), "../src/helm/plugins")) API_URL = "https://yts.lt/api/v2/list_movies.json" From 3298ae441473f94bfcb6f8a7c8af307634013ee3 Mon Sep 17 00:00:00 2001 From: Piratebird <141295458+Piratebird@users.noreply.github.com> Date: Tue, 3 Nov 2026 00:22:57 +0200 Subject: [PATCH 09/18] :shipit: fix(core): tagged one-shot waits, plain progress in logs, and daemon prune - Tag interactive submissions with helm and a per-run tag, and wait on that tag only - Run the wait through qb_request and the configured URL, and stop on missing credentials - Remove only this run's unfinished torrents on Ctrl+C - Add a Progress helper that writes plain, rate-limited lines when output is not a terminal - Raise QBittorrentAuthError for login failures and narrow the one-shot and cancel error handling - Add helm-torrent daemon prune for records of stopped daemons --- CHANGELOG.md | 4 + README.md | 1 + src/helm/cli/commands/background.py | 4 +- src/helm/cli/commands/session.py | 18 +- src/helm/cli/parser.py | 4 +- src/helm/services/jobs.py | 4 +- src/helm/services/runtime.py | 19 ++ src/helm/stack/oneshot.py | 89 ++++----- src/helm/torrents/lite_downloader.py | 11 +- src/helm/torrents/qbittorrent_client.py | 29 ++- src/helm/ui/ansi.py | 36 ++++ tests/test_cli.py | 3 +- tests/test_reliability.py | 254 ++++++++++++++++++++++++ 13 files changed, 403 insertions(+), 73 deletions(-) create mode 100644 tests/test_reliability.py diff --git a/CHANGELOG.md b/CHANGELOG.md index a7b8eac..f541cbf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,7 @@ All notable changes to this project will be documented in this file. - Respect the configured download directory and reject unknown flags, blank queries, and invalid content types. ### Added +- `helm-torrent daemon prune` deletes the records and logs of daemons that have stopped. - Theme presets (`helm`, `tokyo-night`, `nord`, `catppuccin-mocha`) with single-colour overrides, and `helm-torrent banner [--json]`. Banner modules and logo sources (built-in, file, command) run under one time limit, so a slow or failing part cannot break or delay the banner. - `helm-torrent config init`, `edit`, `doctor` and `show --origin`. They run even when the config file is broken. `doctor` checks syntax, values, unknown keys, ignored files, `secrets.env` permissions, writable directories and service reachability, and never prints secrets. - Layered settings from `config.toml` or `config.jsonc`, with validation and a shared JSON Schema. Existing `config.json` values migrate once, and the original file stays in place. If both new files exist, `config.toml` is used. @@ -30,6 +31,9 @@ All notable changes to this project will be documented in this file. - Standalone `uninstall.sh` for raw GitHub execution, with preview-by-default, selective removal and unit tests. ### Fixed +- One-shot waits now watch only the torrents this run sent (tagged `helm` plus a per-run `helm-ui-…` tag), so torrents added to qBittorrent by hand no longer hold up the teardown, and Ctrl+C removes only this run's unfinished torrents. The wait goes through the shared qBittorrent session and URL instead of its own `QB_WEBUI` default, and a missing password now stops it instead of retrying forever. +- Progress lines from the Lite downloader and the one-shot wait are plain text, at most one per whole percent or 30 seconds, when output is not a terminal, so job logs no longer fill with escape codes. +- qBittorrent login failures raise `QBittorrentAuthError` (a `ConnectionError`), and one-shot startup, readiness checks and teardown catch only the subprocess and HTTP errors they expect. - Setup: detect an existing Jackett or Prowlarr container before writing the compose and env files, so the detected one is used instead of a second copy. - Setup: mount the config directory into the CLI container and set `HELM_CONFIG_DIR`; the old `/app/config.json` mount was never read. - Setup: use the published `ghcr.io/piratebird/helm` image on Podman instead of a `mini-helm` image nothing built. diff --git a/README.md b/README.md index b570d29..c1b57af 100644 --- a/README.md +++ b/README.md @@ -266,6 +266,7 @@ helm-torrent --daemon serve --port 8765 # List or stop background commands helm-torrent daemon status helm-torrent daemon stop +helm-torrent daemon prune # forget daemons that have stopped # Start a tmux UI that survives SSH disconnects, then reconnect to it helm-torrent --session main diff --git a/src/helm/cli/commands/background.py b/src/helm/cli/commands/background.py index 90a2ff7..6a0c04b 100644 --- a/src/helm/cli/commands/background.py +++ b/src/helm/cli/commands/background.py @@ -14,10 +14,12 @@ def dispatch_background(args, parser): attach_session(args.name) return True if args.command == "daemon": - from helm.services.runtime import daemon_records, stop_daemon + from helm.services.runtime import daemon_records, prune_daemons, stop_daemon if args.action == "status": print(json.dumps(daemon_records(), indent=2)) + elif args.action == "prune": + print(json.dumps({"pruned": prune_daemons()})) elif not args.id: parser.error("daemon stop requires an id") else: diff --git a/src/helm/cli/commands/session.py b/src/helm/cli/commands/session.py index beb4bd8..c0b5a0f 100644 --- a/src/helm/cli/commands/session.py +++ b/src/helm/cli/commands/session.py @@ -11,7 +11,7 @@ from helm.ui.ansi import T -def send_magnet(selected, lite_mode, json_mode=False, success_msg="Torrent sent successfully :)"): +def send_magnet(selected, lite_mode, json_mode=False, success_msg="Torrent sent successfully :)", tag=None): """Send a torrent to qBittorrent, falling back to the built-in downloader if it is unavailable.""" if lite_mode: from helm.torrents.lite_downloader import download_magnet @@ -19,7 +19,7 @@ def send_magnet(selected, lite_mode, json_mode=False, success_msg="Torrent sent return download_magnet(selected.link) try: - deps.add_magnet(selected.link) + deps.add_magnet(selected.link, tag=f"helm,{tag}" if tag else "helm") if not json_mode: print(f"{T.TEXT}{success_msg}{T.RST}") except Exception as e: @@ -37,7 +37,10 @@ def run(args, teardown_oneshot): if args.command == "indexers": manage_indexers(args) + from helm.torrents.qbittorrent_client import session_tag + mode_str = " (ONE-SHOT MODE)" if args.oneshot else "" + tag = session_tag() # marks this run's torrents, so the wait ignores everyone else's if not args.json and not args.query: print_header(args, f"THE HELM - Torrent automation MVP{mode_str}") @@ -167,10 +170,13 @@ def run(args, teardown_oneshot): if args.auto: selected = filtered[0] - if send_magnet(selected, args.lite, args.json, success_msg="Top torrent sent successfully :)") is False: + if ( + send_magnet(selected, args.lite, args.json, success_msg="Top torrent sent successfully :)", tag=tag) + is False + ): raise SystemExit(1) if args.oneshot and not args.lite: - deps.wait_for_download() + deps.wait_for_download(tag) raise SystemExit(0) from None state = "RESULTS" @@ -192,10 +198,10 @@ def run(args, teardown_oneshot): continue print() - if send_magnet(selected, args.lite, args.json) is False: + if send_magnet(selected, args.lite, args.json, tag=tag) is False: raise SystemExit(1) if (args.oneshot or do_teardown) and not args.lite: - deps.wait_for_download() + deps.wait_for_download(tag) if not args.oneshot: teardown_oneshot() break diff --git a/src/helm/cli/parser.py b/src/helm/cli/parser.py index ef7685a..c4f7d68 100644 --- a/src/helm/cli/parser.py +++ b/src/helm/cli/parser.py @@ -130,9 +130,9 @@ def build_parser(): attach_parser = subparsers.add_parser("attach", help="Reconnect to a named tmux UI", parents=[base_parser]) attach_parser.add_argument("name", nargs="?", default="main") daemon_parser = subparsers.add_parser( - "daemon", help="List or stop managed background commands", parents=[base_parser] + "daemon", help="List, stop or prune managed background commands", parents=[base_parser] ) - daemon_parser.add_argument("action", choices=["status", "stop"]) + daemon_parser.add_argument("action", choices=["status", "stop", "prune"]) daemon_parser.add_argument("id", nargs="?") subparsers.add_parser("banner", help="Print the banner, even when banner.enabled is false", parents=[base_parser]) diff --git a/src/helm/services/jobs.py b/src/helm/services/jobs.py index e42f186..59c4ae7 100644 --- a/src/helm/services/jobs.py +++ b/src/helm/services/jobs.py @@ -245,7 +245,7 @@ def cancel_job(store, identifier): try: delete_tagged(job_tag(identifier)) - except Exception: + except (OSError, ValueError): # network and login errors are OSErrors; ValueError is bad JSON get_logger(__name__).warning("Cannot remove cancelled job %s from qBittorrent", identifier, exc_info=True) return changed @@ -357,7 +357,7 @@ def queue_loop(store, stop, reconcile_every=5): next_reconcile = time.monotonic() + reconcile_every try: reconcile_qbittorrent(store) - except Exception: + except Exception: # like the job loop above: the service must keep running logger.debug("Cannot reconcile qBittorrent jobs", exc_info=True) if not busy: stop.wait(0.5) diff --git a/src/helm/services/runtime.py b/src/helm/services/runtime.py index 47fa180..9190b69 100644 --- a/src/helm/services/runtime.py +++ b/src/helm/services/runtime.py @@ -142,6 +142,25 @@ def daemon_records(): return records +def prune_daemons(): + """Delete the records (and logs) of daemons that are no longer running; return their ids.""" + directory = Path(get_state_dir()) / "daemons" + removed = [] + for record in daemon_records(): + if record["running"]: + continue + identifier = record.get("id") + if not identifier or not re.fullmatch(r"[a-f0-9]{12}", identifier): + continue + for path in (directory / f"{identifier}.json", directory / f"{identifier}.log"): + try: + path.unlink() + except FileNotFoundError: + pass + removed.append(identifier) + return removed + + def stop_daemon(identifier, timeout=5): if not re.fullmatch(r"[a-f0-9]{12}", identifier): raise ValueError("Invalid daemon id") diff --git a/src/helm/stack/oneshot.py b/src/helm/stack/oneshot.py index cde8204..bf3db85 100644 --- a/src/helm/stack/oneshot.py +++ b/src/helm/stack/oneshot.py @@ -6,7 +6,7 @@ import requests -from helm.ui.ansi import T +from helm.ui.ansi import Progress, T def print(*args, **kwargs): @@ -52,7 +52,7 @@ def spin_up_oneshot(): + ["up", "-d", "--remove-orphans", "jackett", "prowlarr", "qbittorrent", "flaresolverr"], check=False, ) - except Exception: + except OSError: pass def check_container_status(service_name, timeout=45): @@ -78,7 +78,7 @@ def check_container_status(service_name, timeout=45): for svc in CONTAINER_SERVICES: _docker_run(["stop", _container_name(svc)], capture_output=True) sys.exit(1) - except Exception: + except (OSError, subprocess.SubprocessError): pass time.sleep(5) elapsed += 5 @@ -100,7 +100,7 @@ def check_container_status(service_name, timeout=45): if r.status_code in [200, 401]: jackett_ready = True break - except Exception: + except requests.RequestException: pass time.sleep(2) @@ -116,7 +116,7 @@ def check_container_status(service_name, timeout=45): if "ready" in r.text.lower() or r.status_code == 200: flaresolverr_ready = True break - except Exception: + except requests.RequestException: pass time.sleep(2) @@ -137,62 +137,55 @@ def teardown_oneshot(): except KeyboardInterrupt: pass print(f"{T.BOLD}{T.SUCCESS}All containers stopped cleanly. Your RAM is free!{T.RST}") - except Exception as e: + except (OSError, subprocess.SubprocessError) as e: print(f"{T.ERROR}Could not tear down docker-compose stack: {e}{T.RST}") -def wait_for_download(): - print(f"\n{T.INFO}Waiting for download to complete before tearing down the stack...{T.RST}") - print(f"{T.ITALIC}(Press Ctrl+C to cancel, or Ctrl+P then Ctrl+Q to detach and run in background){T.RST}") +def _unfinished(torrents): + return [t for t in torrents if t.get("progress", 0.0) < 1.0] + + +def wait_for_download(tag=None, poll=3.0, settle=5.0): + """Wait until every torrent with ``tag`` finishes; Ctrl+C removes the unfinished ones. + Only Helm's torrents are watched (the run's own tag, or every ``helm`` tag), + so torrents someone added to qBittorrent by hand never hold up the teardown. + """ import helm.torrents.qbittorrent_client as qbc - # temporarily inject webui for the wait functionality - qb_webui = os.environ.get("QB_WEBUI", "http://qbittorrent:18080") - session = qbc.login_qbittorrent() - time.sleep(5) # give qbittorrent time to parse the magnet metadata + tag = tag or qbc.SHARED_TAG + print(f"\n{T.INFO}Waiting for download to complete before tearing down the stack...{T.RST}") + print(f"{T.ITALIC}(Press Ctrl+C to cancel, or Ctrl+P then Ctrl+Q to detach and run in background){T.RST}") + time.sleep(settle) # give qBittorrent time to parse the magnet metadata + progress = Progress(sys.stderr) # like every message here, so --json stdout stays clean try: while True: try: - r = session.get(f"{qb_webui}/api/v2/torrents/info", timeout=15) - if r.status_code == 200: - torrents = r.json() - if not torrents: - time.sleep(3) - continue - - all_done = True - for t in torrents: - progress = t.get("progress", 0.0) - name = t.get("name", "Unknown") - if progress < 1.0: - all_done = False - print(f"\r{T.WARNING}Downloading '{name[:40]}...' ({progress * 100:.1f}%) {T.RST}", end="") - sys.stdout.flush() - - if all_done: - print(f"\n{T.BOLD}{T.SUCCESS}Download(s) 100% complete!{T.RST}") - break - except Exception: - pass - - time.sleep(3) + torrents = qbc.tagged_torrents(tag) + except (requests.RequestException, ValueError): + # qBittorrent restarting or briefly unreachable: keep waiting. + time.sleep(poll) + continue + pending = _unfinished(torrents) + if torrents and not pending: + print(f"\n{T.BOLD}{T.SUCCESS}Download(s) 100% complete!{T.RST}") + return + for torrent in pending: + percent = torrent.get("progress", 0.0) * 100 + name = torrent.get("name", "Unknown") + progress.update(percent, f"{T.WARNING}Downloading '{name[:40]}...' ({percent:.1f}%) {T.RST}") + time.sleep(poll) except KeyboardInterrupt: print(f"\n{T.ERROR}Download cancelled by user!{T.RST}") print(f"{T.ITALIC}Removing unfinished torrents from qBittorrent...{T.RST}") try: - r = session.get(f"{qb_webui}/api/v2/torrents/info", timeout=15) - if r.status_code == 200: - torrents = r.json() - hashes_to_delete = [t.get("hash") for t in torrents if t.get("progress", 0.0) < 1.0] - if hashes_to_delete: - # delete torrent and downloaded data - session.post( - f"{qb_webui}/api/v2/torrents/delete", - data={"hashes": "|".join(hashes_to_delete), "deleteFiles": "true"}, - timeout=15, - ) - except Exception: + hashes = [t["hash"] for t in _unfinished(qbc.tagged_torrents(tag))] + if hashes: + # delete torrent and downloaded data + qbc.qb_request( + "POST", "/api/v2/torrents/delete", data={"hashes": "|".join(hashes), "deleteFiles": "true"} + ) + except (requests.RequestException, ValueError, KeyError, ConnectionError): pass raise diff --git a/src/helm/torrents/lite_downloader.py b/src/helm/torrents/lite_downloader.py index 0d4f508..d20499e 100644 --- a/src/helm/torrents/lite_downloader.py +++ b/src/helm/torrents/lite_downloader.py @@ -2,7 +2,7 @@ import sys import time -from helm.ui.ansi import T +from helm.ui.ansi import Progress, T def download_magnet(magnet_link, save_path=None, on_complete=None): @@ -70,6 +70,7 @@ def download_magnet(magnet_link, save_path=None, on_complete=None): print("\nMetadata downloaded. Starting torrent download...") print(f"Saving to: {T.BOLD}{os.path.abspath(save_path)}{T.RST}\n") + progress = Progress() while handle.status().state != lt.torrent_status.seeding: s = handle.status() @@ -83,13 +84,13 @@ def download_magnet(magnet_link, save_path=None, on_complete=None): "allocating", ] - sys.stdout.write( - f"\r{T.EOL}{T.BOLD}{s.progress * 100:.2f}%{T.RST} complete " + progress.update( + s.progress * 100, + f"{T.BOLD}{s.progress * 100:.2f}%{T.RST} complete " f"(down: {T.SUCCESS}{s.download_rate / 1000:.1f} kB/s{T.RST} | " f"up: {T.ERROR}{s.upload_rate / 1000:.1f} kB/s{T.RST} | " - f"peers: {s.num_peers}) [{state_str[s.state]}]" + f"peers: {s.num_peers}) [{state_str[s.state]}]", ) - sys.stdout.flush() alerts = ses.pop_alerts() for a in alerts: diff --git a/src/helm/torrents/qbittorrent_client.py b/src/helm/torrents/qbittorrent_client.py index 9e3431a..5747171 100644 --- a/src/helm/torrents/qbittorrent_client.py +++ b/src/helm/torrents/qbittorrent_client.py @@ -7,6 +7,7 @@ """ +import secrets import threading import requests @@ -21,6 +22,16 @@ # Applied to every Helm job so reconciliation needs one list call per pass. SHARED_TAG = "helm" + +class QBittorrentAuthError(ConnectionError): + """qBittorrent refused Helm's credentials, or none are configured.""" + + +def session_tag(): + """A tag that marks the torrents one interactive run submits.""" + return f"helm-ui-{secrets.token_hex(6)}" + + _session = None _session_key = None _session_lock = threading.Lock() @@ -39,7 +50,7 @@ def login_qbittorrent(force=False): if _session is not None and _session_key == key and not force: return _session if not qb_password: - raise Exception("Please set QB_PASSWORD in .env file !!") + raise QBittorrentAuthError("Please set QB_PASSWORD in .env file !!") session = requests.Session() @@ -51,7 +62,7 @@ def login_qbittorrent(force=False): logger.info("qBittorrent subnet authentication accepted") _session, _session_key = session, key return session - except Exception: + except requests.RequestException: pass login_url = f"{qb_webui}/api/v2/auth/login" @@ -60,15 +71,17 @@ def login_qbittorrent(force=False): if r.status_code == 200 or r.status_code == 204: # Verify authentication by making a secondary request + prefix = "Failed to verify qbittorrent authentication" try: r_verify = session.get(version_url, timeout=10) - if r_verify.status_code != 200: - raise ConnectionError("Secondary verification request failed, authentication was not successful.") - except Exception as e: - # catching errors like pokemons - raise ConnectionError(f"Failed to verify qbittorrent authentication: {e}") # noqa: B904 + except requests.RequestException as e: + raise ConnectionError(f"{prefix}: {e}") from e + if r_verify.status_code != 200: + raise QBittorrentAuthError( + f"{prefix}: Secondary verification request failed, authentication was not successful." + ) else: - raise ConnectionError(f"Failed to login to qbittorrent: HTTP {r.status_code} {r.text}") + raise QBittorrentAuthError(f"Failed to login to qbittorrent: HTTP {r.status_code} {r.text}") logger.info("qBittorrent authentication accepted") _session, _session_key = session, key diff --git a/src/helm/ui/ansi.py b/src/helm/ui/ansi.py index 75ed783..e0f21d4 100644 --- a/src/helm/ui/ansi.py +++ b/src/helm/ui/ansi.py @@ -2,6 +2,7 @@ import os import sys +import time import unicodedata from helm.ui.banner import SGR @@ -161,3 +162,38 @@ def reset(self): T = Terminal() + + +class Progress: + """One progress line: redrawn in place on a terminal, plain lines elsewhere. + + Job logs and pipes get a new line only when the whole-number percentage + changes, or every ``interval`` seconds, and never carry escape codes. + """ + + def __init__(self, stream=None, interval=30.0, clock=None): + self.stream = stream + self.interval = interval + self.clock = clock or time.monotonic + self._last_percent = None + self._last_time = None + + def _out(self): + return self.stream or sys.stdout + + def update(self, percent, text): + """Show ``text`` for ``percent`` (0 to 100); ``text`` may contain T codes.""" + out = self._out() + isatty = getattr(out, "isatty", None) + if isatty and isatty(): + out.write(f"\r{EOL}{text}") + out.flush() + return + now = self.clock() + whole = int(percent) + due = self._last_time is None or now - self._last_time >= self.interval + if whole == self._last_percent and not due: + return + self._last_percent, self._last_time = whole, now + out.write(SGR.sub("", text) + "\n") + out.flush() diff --git a/tests/test_cli.py b/tests/test_cli.py index 7da4fde..a4745b3 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -308,7 +308,8 @@ def send(*args, **kwargs): raise RuntimeError("download failed") return outcome != "send_failure" - def wait(): + def wait(tag=None): + assert tag and tag.startswith("helm-ui-") events.append("wait") if outcome == "wait_failure": raise RuntimeError("wait failed") diff --git a/tests/test_reliability.py b/tests/test_reliability.py new file mode 100644 index 0000000..e88447f --- /dev/null +++ b/tests/test_reliability.py @@ -0,0 +1,254 @@ +"""Progress output, the tagged one-shot wait, qBittorrent errors and daemon pruning.""" + +import io +import json +import os +import subprocess +import sys + +import pytest +import requests +import responses + +import helm.stack.oneshot as oneshot +import helm.torrents.qbittorrent_client as qbc +from helm.services import runtime +from helm.ui.ansi import Progress + + +class Pipe(io.StringIO): + def isatty(self): + return False + + +class Tty(io.StringIO): + def isatty(self): + return True + + +# ---------------------------------------------------------------- Progress + + +def test_progress_redraws_in_place_on_a_terminal(): + out = Tty() + progress = Progress(out) + progress.update(1, "\033[1m1%\033[0m") + progress.update(1, "\033[1m1%\033[0m") + assert out.getvalue() == "\r\033[K\033[1m1%\033[0m" * 2 + + +def test_progress_writes_plain_lines_once_per_percent_elsewhere(): + now = [0.0] + out = Pipe() + progress = Progress(out, interval=30, clock=lambda: now[0]) + for percent in (0.1, 0.5, 0.9, 1.0, 1.5, 2.2): + progress.update(percent, f"\033[33m{percent}%\033[0m") + assert out.getvalue().splitlines() == ["0.1%", "1.0%", "2.2%"] + + now[0] = 31.0 # no new percentage, but the interval passed + progress.update(2.3, "still 2.3%") + now[0] = 32.0 + progress.update(2.4, "quiet") + assert out.getvalue().splitlines()[-1] == "still 2.3%" + assert "\033" not in out.getvalue() and "\r" not in out.getvalue() + + +# ---------------------------------------------------------------- wait_for_download + + +def torrent(name, progress, digest="a"): + return {"name": name, "progress": progress, "hash": digest} + + +@pytest.fixture +def quiet_wait(monkeypatch, capsys): + """No sleeping; output is read with capsys, which is not a terminal.""" + monkeypatch.setattr(oneshot.time, "sleep", lambda seconds: None) + return capsys + + +def test_wait_watches_only_the_given_tag(monkeypatch, quiet_wait): + seen = [] + replies = iter([[], [torrent("mine", 0.5)], [torrent("mine", 1.0)]]) + + def tagged(tag): + seen.append(tag) + return next(replies) + + monkeypatch.setattr(qbc, "tagged_torrents", tagged) + oneshot.wait_for_download("helm-ui-abc", poll=0, settle=0) + assert seen == ["helm-ui-abc"] * 3 + captured = quiet_wait.readouterr() + assert "Downloading 'mine...' (50.0%)" in captured.err + assert "100% complete" in captured.err + assert captured.out == "" + assert "\r" not in captured.err + + +def test_wait_defaults_to_every_helm_torrent(monkeypatch, quiet_wait): + seen = [] + monkeypatch.setattr(qbc, "tagged_torrents", lambda tag: seen.append(tag) or [torrent("x", 1.0)]) + oneshot.wait_for_download(poll=0, settle=0) + assert seen == ["helm"] + + +def test_wait_keeps_going_through_transient_errors(monkeypatch, quiet_wait): + replies = [requests.ConnectionError("restarting"), ValueError("bad json"), [torrent("x", 1.0)]] + + def tagged(tag): + reply = replies.pop(0) + if isinstance(reply, Exception): + raise reply + return reply + + monkeypatch.setattr(qbc, "tagged_torrents", tagged) + oneshot.wait_for_download("t", poll=0, settle=0) + assert replies == [] + + +def test_wait_stops_on_missing_credentials(monkeypatch, quiet_wait): + def tagged(tag): + raise qbc.QBittorrentAuthError("Please set QB_PASSWORD") + + monkeypatch.setattr(qbc, "tagged_torrents", tagged) + with pytest.raises(qbc.QBittorrentAuthError): + oneshot.wait_for_download("t", poll=0, settle=0) + + +def test_ctrl_c_removes_only_unfinished_torrents_of_the_tag(monkeypatch, quiet_wait): + calls = [] + state = {"interrupted": False} + + def tagged(tag): + calls.append(("list", tag)) + if not state["interrupted"]: + state["interrupted"] = True + raise KeyboardInterrupt + return [torrent("done", 1.0, "d1"), torrent("half", 0.5, "h1"), torrent("new", 0.0, "n1")] + + monkeypatch.setattr(qbc, "tagged_torrents", tagged) + monkeypatch.setattr(qbc, "qb_request", lambda method, path, **kw: calls.append((method, path, kw["data"]))) + with pytest.raises(KeyboardInterrupt): + oneshot.wait_for_download("helm-ui-1", poll=0, settle=0) + assert calls[-1] == ("POST", "/api/v2/torrents/delete", {"hashes": "h1|n1", "deleteFiles": "true"}) + assert all(call[1] == "helm-ui-1" for call in calls if call[0] == "list") + + +def test_ctrl_c_cleanup_survives_an_unreachable_qbittorrent(monkeypatch, quiet_wait): + def tagged(tag): + if not tagged.calls: + tagged.calls = 1 + raise KeyboardInterrupt + raise requests.ConnectionError("gone") + + tagged.calls = 0 + monkeypatch.setattr(qbc, "tagged_torrents", tagged) + with pytest.raises(KeyboardInterrupt): + oneshot.wait_for_download("t", poll=0, settle=0) + + +# ---------------------------------------------------------------- qBittorrent client + + +def test_session_tags_are_unique_and_recognisable(): + tags = {qbc.session_tag() for _ in range(50)} + assert len(tags) == 50 and all(tag.startswith("helm-ui-") and len(tag) == 20 for tag in tags) + + +def test_send_magnet_tags_the_torrent(monkeypatch): + from helm.cli import deps + from helm.cli.commands import session + + sent = [] + monkeypatch.setattr(deps, "add_magnet", lambda link, tag=None: sent.append((link, tag))) + item = type("Item", (), {"link": "magnet:?xt=urn:btih:" + "a" * 40})() + assert session.send_magnet(item, lite_mode=False, json_mode=True, tag="helm-ui-1") is True + assert session.send_magnet(item, lite_mode=False, json_mode=True) is True + assert [tag for _link, tag in sent] == ["helm,helm-ui-1", "helm"] + + +@pytest.fixture +def qb_settings(monkeypatch, tmp_path): + monkeypatch.setenv("HELM_CONFIG_DIR", str(tmp_path)) + monkeypatch.setenv("QB_WEBUI", "http://qb.test") + monkeypatch.setattr(qbc, "_session", None) + monkeypatch.setattr(qbc, "_session_key", None) + + +def test_missing_password_is_an_auth_error(monkeypatch, qb_settings): + monkeypatch.setattr(qbc, "get_secret", lambda key: "") + with pytest.raises(qbc.QBittorrentAuthError, match="QB_PASSWORD"): + qbc.login_qbittorrent() + assert issubclass(qbc.QBittorrentAuthError, ConnectionError) + + +@responses.activate +def test_rejected_login_is_an_auth_error(monkeypatch, qb_settings): + monkeypatch.setattr(qbc, "get_secret", lambda key: "pw") + responses.add(responses.GET, "http://qb.test/api/v2/app/version", status=403) + responses.add(responses.POST, "http://qb.test/api/v2/auth/login", status=401, body="Fails.") + with pytest.raises(qbc.QBittorrentAuthError, match="HTTP 401"): + qbc.login_qbittorrent() + + +@responses.activate +def test_failed_verification_keeps_its_message(monkeypatch, qb_settings): + monkeypatch.setattr(qbc, "get_secret", lambda key: "pw") + responses.add(responses.GET, "http://qb.test/api/v2/app/version", status=403) + responses.add(responses.POST, "http://qb.test/api/v2/auth/login", status=200, body="Ok.") + responses.add(responses.GET, "http://qb.test/api/v2/app/version", status=403) + with pytest.raises(qbc.QBittorrentAuthError, match="Failed to verify qbittorrent authentication: Secondary"): + qbc.login_qbittorrent() + + +@responses.activate +def test_unreachable_verification_is_a_connection_error(monkeypatch, qb_settings): + monkeypatch.setattr(qbc, "get_secret", lambda key: "pw") + responses.add(responses.GET, "http://qb.test/api/v2/app/version", status=403) + responses.add(responses.POST, "http://qb.test/api/v2/auth/login", status=200, body="Ok.") + responses.add(responses.GET, "http://qb.test/api/v2/app/version", body=requests.ConnectionError("down")) + with pytest.raises(ConnectionError, match="Failed to verify qbittorrent authentication: down") as error: + qbc.login_qbittorrent() + assert not isinstance(error.value, qbc.QBittorrentAuthError) + + +# ---------------------------------------------------------------- daemon pruning + + +def write_record(directory, identifier, pid, identity): + directory.mkdir(parents=True, exist_ok=True) + (directory / f"{identifier}.json").write_text(json.dumps({"id": identifier, "pid": pid, "identity": identity})) + (directory / f"{identifier}.log").write_text("log") + + +def test_prune_removes_only_stopped_daemons(monkeypatch, tmp_path): + monkeypatch.setenv("HELM_STATE_DIR", str(tmp_path)) + directory = tmp_path / "daemons" + alive = "a" * 12 + dead = "b" * 12 + write_record(directory, alive, os.getpid(), runtime.process_start(os.getpid())) + write_record(directory, dead, 2**22 + 7, "gone") + (directory / "notes.json").write_text("not a record") + (directory / "cccccccccccc.json").write_text(json.dumps({"id": "../escape", "pid": 2**22 + 8, "identity": "x"})) + + assert runtime.prune_daemons() == [dead] + assert sorted(p.name for p in directory.iterdir()) == sorted( + [f"{alive}.json", f"{alive}.log", "notes.json", "cccccccccccc.json"] + ) + assert runtime.prune_daemons() == [] + + +def test_daemon_prune_command(tmp_path): + src = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "src") + env = { + **os.environ, + "PYTHONPATH": src, + "HELM_STATE_DIR": str(tmp_path), + "HELM_CONFIG_DIR": str(tmp_path / "config"), + } + write_record(tmp_path / "daemons", "d" * 12, 2**22 + 9, "gone") + result = subprocess.run( + [sys.executable, "-m", "helm.cli", "daemon", "prune"], env=env, capture_output=True, text=True, check=False + ) + assert result.returncode == 0, result.stderr + assert json.loads(result.stdout) == {"pruned": ["d" * 12]} From cb8f859992df6143c1cdbfc64ed52d05012baaaa Mon Sep 17 00:00:00 2001 From: Piratebird <141295458+Piratebird@users.noreply.github.com> Date: Tue, 3 Nov 2026 00:30:09 +0200 Subject: [PATCH 10/18] :shipit: test(ci): wizard automation, CLI command tests, and tmux and libtorrent in CI - Test the wizard's full-automation prompts against a local fake Jackett, Prowlarr and qBittorrent - Cover status, indexer management and the interactive session in process - Install tmux and try libtorrent in CI, and list skipped tests - Drop the redundant requirements.txt install from CI and keep the file equal to pyproject.toml --- .github/workflows/ci.yml | 8 +- CHANGELOG.md | 1 + requirements.txt | 3 + tests/test_cli_commands.py | 277 ++++++++++++++++++++++++++++++++ tests/test_project_files.py | 29 ++++ tests/test_wizard_automation.py | 203 +++++++++++++++++++++++ 6 files changed, 519 insertions(+), 2 deletions(-) create mode 100644 tests/test_cli_commands.py create mode 100644 tests/test_project_files.py create mode 100644 tests/test_wizard_automation.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2746f91..83b4843 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -37,11 +37,15 @@ jobs: python-version: ${{ matrix.python-version }} cache: "pip" + - name: Install tmux + run: sudo apt-get update && sudo apt-get install -y tmux + - name: Install Dependencies run: | python -m pip install --upgrade pip - if [ -f requirements.txt ]; then pip install -r requirements.txt; fi pip install -e .[dev] ruff mypy + # libtorrent ships wheels for most, not all, of these Pythons; its tests skip without it. + pip install "libtorrent>=2.0.0,<2.1.0" || echo "::notice::No libtorrent wheel for Python ${{ matrix.python-version }}" - name: Lint and Format with Ruff run: | @@ -54,7 +58,7 @@ jobs: - name: Run Pytest run: | - if [ -d "tests" ]; then pytest tests/ --cov=src/helm --cov-report=xml; fi + if [ -d "tests" ]; then pytest tests/ -rs --cov=src/helm --cov-report=xml; fi docker-build: name: Build Docker Image diff --git a/CHANGELOG.md b/CHANGELOG.md index f541cbf..07df20e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,7 @@ All notable changes to this project will be documented in this file. - Respect the configured download directory and reject unknown flags, blank queries, and invalid content types. ### Added +- Tests for the setup wizard's full-automation prompts against a local HTTP server that acts like Jackett, Prowlarr and qBittorrent, and in-process tests for `status`, indexer management and the interactive session. CI now installs tmux and tries libtorrent, so those tests run there instead of skipping, and lists any skips. - `helm-torrent daemon prune` deletes the records and logs of daemons that have stopped. - Theme presets (`helm`, `tokyo-night`, `nord`, `catppuccin-mocha`) with single-colour overrides, and `helm-torrent banner [--json]`. Banner modules and logo sources (built-in, file, command) run under one time limit, so a slow or failing part cannot break or delay the banner. - `helm-torrent config init`, `edit`, `doctor` and `show --origin`. They run even when the config file is broken. `doctor` checks syntax, values, unknown keys, ignored files, `secrets.env` permissions, writable directories and service reachability, and never prints secrets. diff --git a/requirements.txt b/requirements.txt index cc8e74d..9e96352 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,3 +1,6 @@ +# Mirror of the [project] dependencies in pyproject.toml, which is the source of truth. +# The Dockerfile installs this file first so the dependency layer stays cached; +# tests/test_project_files.py keeps the two equal. requests>=2.31.0 python-dotenv>=1.0.0 beautifulsoup4>=4.12.0 diff --git a/tests/test_cli_commands.py b/tests/test_cli_commands.py new file mode 100644 index 0000000..62eadfc --- /dev/null +++ b/tests/test_cli_commands.py @@ -0,0 +1,277 @@ +"""In-process tests for helm.cli.commands: status, indexer management and the interactive session.""" + +import builtins +from types import SimpleNamespace + +import pytest + +import helm.ui.tui as tui +from helm.cli import deps +from helm.cli.commands import indexers, session, status +from helm.config.settings import Settings + +# ---------------------------------------------------------------- status + + +@pytest.fixture +def plain_settings(monkeypatch): + monkeypatch.setattr(deps, "load_settings", lambda: Settings.from_legacy({})) + + +def test_status_without_an_engine(monkeypatch, plain_settings, capsys): + monkeypatch.setattr(status.shutil, "which", lambda name: None) + status.run() + out = capsys.readouterr().out + assert "Native Mode - No containers running." in out + assert "Jackett: http://localhost:19117" in out + + +def test_status_lists_only_helm_containers_and_marks_missing_services(monkeypatch, plain_settings, capsys): + monkeypatch.setattr(status.shutil, "which", lambda name: "/usr/bin/podman" if name == "podman" else None) + calls = [] + + def run(cmd, **kwargs): + calls.append(cmd) + return SimpleNamespace(stdout="helm-jackett: Up 2 minutes\nother-db: Up\nhelm-qbittorrent: Up\n") + + monkeypatch.setattr(status.subprocess, "run", run) + status.run() + out = capsys.readouterr().out + assert calls[0][0] == "podman" + assert "helm-jackett: Up 2 minutes" in out and "other-db" not in out + assert "Prowlarr: not running" in out + assert "qBittorrent: http://localhost:18080" in out + + +def test_status_survives_a_failing_engine(monkeypatch, plain_settings, capsys): + monkeypatch.setattr(status.shutil, "which", lambda name: "/usr/bin/docker") + + def run(cmd, **kwargs): + raise OSError("daemon down") + + monkeypatch.setattr(status.subprocess, "run", run) + status.run() + out = capsys.readouterr().out + assert "Failed to run docker ps." in out and "Prowlarr: http://localhost:19696" in out + + +def test_status_with_no_helm_containers(monkeypatch, plain_settings, capsys): + monkeypatch.setattr(status.shutil, "which", lambda name: "/usr/bin/docker") + monkeypatch.setattr(status.subprocess, "run", lambda cmd, **kw: SimpleNamespace(stdout="db: Up\n")) + status.run() + assert "No helm containers found." in capsys.readouterr().out + + +# ---------------------------------------------------------------- indexers + + +class Manager: + url = "http://jackett.test" + + def __init__(self, fail_add=None): + self.fail_add = fail_add + self.log = [] + + def get_all_indexers(self): + return [ + {"id": "a", "title": "Alpha", "configured": True, "type": "public"}, + {"id": "b", "title": "Beta", "configured": False, "type": "private"}, + {"id": "c", "title": "Gamma", "configured": False, "type": "public"}, + ] + + def remove_indexer(self, identifier): + self.log.append(("remove", identifier)) + + def add_indexer(self, identifier): + self.log.append(("add", identifier)) + if self.fail_add: + raise RuntimeError(self.fail_add) + + +def indexer_args(**kw): + return SimpleNamespace(**{"lite": False, "prowlarr": False, "jackett": False, **kw}) + + +@pytest.fixture +def indexer_env(monkeypatch): + monkeypatch.setattr(deps, "ensure_config", lambda: None) + monkeypatch.setattr(deps, "load_settings", lambda: Settings.from_legacy({"INDEXER_MANAGER": "jackett"})) + monkeypatch.setattr(indexers.time, "sleep", lambda seconds: None) + + def setup(manager, picks, reply="n"): + import helm.search.indexer_manager as managers + + monkeypatch.setattr(managers, "JackettManager", lambda: manager) + monkeypatch.setattr(managers, "ProwlarrManager", lambda: manager) + queue = list(picks) + + def pick(all_indexers): + item = queue.pop(0) + if item is KeyboardInterrupt: + raise KeyboardInterrupt + return next(i for i in all_indexers if i["id"] == item) if item else None + + monkeypatch.setattr(deps, "interactive_indexer_selector", pick) + monkeypatch.setattr(builtins, "input", lambda prompt="": reply) + + return setup + + +def test_indexers_add_remove_and_refuse_private(indexer_env, capsys): + manager = Manager() + indexer_env(manager, ["a", "b", "c", None, KeyboardInterrupt]) + with pytest.raises(SystemExit) as stop: + indexers.manage_indexers(indexer_args()) + assert stop.value.code == 0 + assert manager.log == [("remove", "a"), ("add", "c")] + out = capsys.readouterr().out + assert "Removing Alpha" in out and "Adding Gamma" in out + assert "Cannot add private trackers via CLI" in out and "http://jackett.test" in out + + +def test_indexers_explain_a_jackett_500(indexer_env, capsys): + indexer_env(Manager(fail_add="HTTP 500 Server Error"), ["c", KeyboardInterrupt]) + with pytest.raises(SystemExit): + indexers.manage_indexers(indexer_args(prowlarr=True)) + assert "Jackett rejected the default config" in capsys.readouterr().out + + +def test_indexers_continue_to_search_when_asked(indexer_env): + indexer_env(Manager(), [KeyboardInterrupt], reply="y") + # Answering yes returns to the caller, which then starts the search session. + with pytest.raises(IndexError): + indexers.manage_indexers(indexer_args(jackett=True)) + + +def test_indexers_refuse_lite_mode_and_report_manager_errors(monkeypatch, indexer_env, capsys): + with pytest.raises(SystemExit) as stop: + indexers.manage_indexers(indexer_args(lite=True)) + assert stop.value.code == 1 and "Lite Mode" in capsys.readouterr().err + + import helm.search.indexer_manager as managers + + def broken(): + raise RuntimeError("no API key") + + monkeypatch.setattr(managers, "JackettManager", broken) + with pytest.raises(SystemExit) as stop: + indexers.manage_indexers(indexer_args()) + assert stop.value.code == 1 and "no API key" in capsys.readouterr().err + + +# ---------------------------------------------------------------- interactive session + + +def item(title="Ubuntu 24.04"): + return SimpleNamespace(title=title, link="magnet:?xt=urn:btih:" + "a" * 40, seeders=10, indexer="test") + + +def session_args(**kw): + base = {"command": "ui", "query": None, "json": False, "lite": True, "oneshot": False, "auto": False} + return SimpleNamespace(**{**base, "type": "video", **kw}) + + +@pytest.fixture +def ui(monkeypatch): + monkeypatch.setattr(session, "print_header", lambda args, subtitle: None) + monkeypatch.setattr(deps, "load_settings", lambda: Settings.from_legacy({})) + monkeypatch.setattr(deps, "dedupe", lambda items: items) + monkeypatch.setattr(deps, "filter_items", lambda items, *a, **kw: items) + events = [] + + def setup(inputs, checkboxes, results, picks): + inputs, checkboxes, results, picks = map(list, (inputs, checkboxes, results, picks)) + + def fake_input(prompt=""): + events.append(("input", prompt)) + reply = inputs.pop(0) + if reply is EOFError: + raise EOFError + return reply + + def search(query, categories, **kw): + events.append(("search", query, categories)) + return results.pop(0), kw.get("lite_mode", True) + + monkeypatch.setattr(builtins, "input", fake_input) + monkeypatch.setattr(tui, "interactive_checkbox_selector", lambda options, title: checkboxes.pop(0)) + monkeypatch.setattr(deps, "animated_search", search) + monkeypatch.setattr(deps, "interactive_selector", lambda found, *a, **kw: picks.pop(0)) + monkeypatch.setattr(session, "send_magnet", lambda chosen, *a, **kw: events.append(("send", chosen.title))) + return events + + return setup + + +def test_prompt_back_then_books_strips_punctuation(ui): + events = ui(["ubuntu", "dune: part one!"], ["BACK", ["books"]], [[item("Dune")]], [(item("Dune"), False)]) + session.run(session_args(), teardown_oneshot=lambda: None) + assert ("search", "dune part one", "books") in events + assert events[-1] == ("send", "Dune") + + +def test_empty_query_is_asked_again(ui): + events = ui(["", "linux"], [["software", "video"]], [[item()]], [(item(), False)]) + session.run(session_args(), teardown_oneshot=lambda: None) + assert ("search", "linux", "software,video") in events + + +def test_no_results_returns_to_the_prompt(ui, capsys): + ui(["missing", "", EOFError], [["video"]], [[]], []) + with pytest.raises(SystemExit) as stop: + session.run(session_args(), teardown_oneshot=lambda: None) + assert stop.value.code == 0 + err = capsys.readouterr().err + assert "No torrents were found" in err and "Lite sources may be unreachable" in err + + +def test_back_from_results_goes_to_the_prompt_or_exits_for_a_query(ui): + events = ui(["first", "second"], [["video"], ["video"]], [[item()], [item("Second")]], [ + (None, "BACK"), + (item("Second"), False), + ]) # fmt: skip + session.run(session_args(), teardown_oneshot=lambda: None) + assert [e for e in events if e[0] == "search"] == [("search", "first", "video"), ("search", "second", "video")] + + ui([], [], [[item()]], [(None, "BACK")]) + with pytest.raises(SystemExit) as stop: + session.run(session_args(query="ubuntu"), teardown_oneshot=lambda: None) + assert stop.value.code == 0 + + +def test_teardown_choice_waits_and_stops_a_permanent_stack(ui, monkeypatch): + events = ui([], [], [[item()]], [(item(), True)]) + monkeypatch.setattr(deps, "wait_for_download", lambda tag: events.append(("wait", tag[:8]))) + session.run(session_args(query="ubuntu", lite=False), teardown_oneshot=lambda: events.append(("teardown",))) + assert events[-2:] == [("wait", "helm-ui-"), ("teardown",)] + + +def test_ctrl_c_in_results_tears_down_only_when_asked(ui, monkeypatch): + events = ui([], [], [[item()]], []) + + def interrupt(*a, **kw): + raise KeyboardInterrupt + + monkeypatch.setattr(deps, "interactive_selector", interrupt) + with pytest.raises(SystemExit): + session.run(session_args(query="ubuntu", lite=False), teardown_oneshot=lambda: events.append("teardown")) + assert "teardown" not in events + + +def test_lite_send_uses_the_built_in_downloader(monkeypatch): + import helm.torrents.lite_downloader as downloader + + monkeypatch.setattr(downloader, "download_magnet", lambda link: f"downloaded {link[:20]}") + assert session.send_magnet(item(), lite_mode=True) == "downloaded magnet:?xt=urn:btih:" + + +def test_send_falls_back_to_lite_when_qbittorrent_fails(monkeypatch, capsys): + import helm.torrents.lite_downloader as downloader + + def refuse(link, tag=None): + raise ConnectionError("refused") + + monkeypatch.setattr(deps, "add_magnet", refuse) + monkeypatch.setattr(downloader, "download_magnet", lambda link: True) + assert session.send_magnet(item(), lite_mode=False) is True + assert "Falling back to LITE MODE" in capsys.readouterr().err diff --git a/tests/test_project_files.py b/tests/test_project_files.py new file mode 100644 index 0000000..7fee8bc --- /dev/null +++ b/tests/test_project_files.py @@ -0,0 +1,29 @@ +"""Project files that repeat each other must stay in step.""" + +import re +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] + + +def pyproject_dependencies(): + text = (ROOT / "pyproject.toml").read_text() + block = re.search(r"^dependencies = \[(.*?)^\]", text, re.S | re.M).group(1) + return [line.strip().strip(",").strip('"') for line in block.splitlines() if line.strip()] + + +def test_requirements_txt_matches_pyproject(): + """The Dockerfile installs requirements.txt first to cache that layer; pyproject.toml is the source.""" + requirements = [ + line.strip() + for line in (ROOT / "requirements.txt").read_text().splitlines() + if line.strip() and not line.startswith("#") + ] + assert requirements == pyproject_dependencies() + + +def test_ci_installs_tmux_and_tries_libtorrent(): + ci = (ROOT / ".github" / "workflows" / "ci.yml").read_text() + assert "apt-get install -y tmux" in ci + assert 'pip install "libtorrent>=2.0.0,<2.1.0" ||' in ci + assert "requirements.txt" not in ci # pyproject's [dev] extra already pulls everything in diff --git a/tests/test_wizard_automation.py b/tests/test_wizard_automation.py new file mode 100644 index 0000000..a2da432 --- /dev/null +++ b/tests/test_wizard_automation.py @@ -0,0 +1,203 @@ +"""The setup wizard's full-automation prompts, against a real local HTTP server. + +The server acts like Jackett, Prowlarr and qBittorrent closely enough for the +wizard's checks: API keys, the Jackett admin password, and qBittorrent's SID cookie. +""" + +import builtins +import threading +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from urllib.parse import parse_qs, urlparse + +import pytest + +import helm.config.config_wizard as wizard +from helm.config.secret_manager import get_secret +from helm.config.settings import load_settings + +JACKETT_KEY = "jackett-key-123456" +PROWLARR_KEY = "prowlarr-key-123456" +ADMIN_PASSWORD = "admin-pass" +QB_USER, QB_PASSWORD = "admin", "qb-pass" + + +class Fake(BaseHTTPRequestHandler): + def log_message(self, *args): + pass + + def reply(self, status, body="", headers=None): + data = body.encode() + self.send_response(status) + for name, value in (headers or {}).items(): + self.send_header(name, value) + self.send_header("Content-Length", str(len(data))) + self.end_headers() + self.wfile.write(data) + + def form(self): + length = int(self.headers.get("Content-Length") or 0) + return {key: values[0] for key, values in parse_qs(self.rfile.read(length).decode()).items()} + + def do_GET(self): + url = urlparse(self.path) + query = {key: values[0] for key, values in parse_qs(url.query).items()} + cookie = self.headers.get("Cookie", "") + if url.path == "/api/v2.0/indexers/all/results/torznab/api": + return self.reply(200 if query.get("apikey") == JACKETT_KEY else 401, "") + if url.path == "/api/v2.0/indexers/3dtorrents/config": + return self.reply(200, "[]" if "Jackett=ok" in cookie else "login") + if url.path == "/UI/Dashboard": + return self.reply(200, "dashboard") + if url.path == "/api/v1/indexer": + return self.reply(200 if self.headers.get("X-Api-Key") == PROWLARR_KEY else 401, "[]") + if url.path == "/api/v2/app/version": + return self.reply(200 if "SID=good" in cookie else 403, "v5.0.0") + return self.reply(404) + + def do_POST(self): + form = self.form() + if self.path == "/UI/Dashboard": + if form.get("password", "") == ADMIN_PASSWORD: + return self.reply(302, headers={"Set-Cookie": "Jackett=ok; Path=/", "Location": "/UI/Dashboard"}) + return self.reply(200, "login") + if self.path == "/api/v2/auth/login": + if (form.get("username"), form.get("password")) == (QB_USER, QB_PASSWORD): + return self.reply(200, "Ok.", {"Set-Cookie": "SID=good; Path=/"}) + return self.reply(200, "Fails.") + return self.reply(404) + + +@pytest.fixture +def server(): + httpd = ThreadingHTTPServer(("127.0.0.1", 0), Fake) + thread = threading.Thread(target=httpd.serve_forever, daemon=True) + thread.start() + yield f"http://127.0.0.1:{httpd.server_address[1]}" + httpd.shutdown() + httpd.server_close() + + +@pytest.fixture +def answers(monkeypatch, tmp_path): + monkeypatch.setenv("HELM_CONFIG_DIR", str(tmp_path / "config")) + monkeypatch.setenv("HELM_STATE_DIR", str(tmp_path / "state")) + for key in ("JACKETT_API_KEY", "JACKETT_PASSWORD", "PROWLARR_API_KEY", "QB_PASSWORD", "QB_WEBUI", "JACKETT_URL"): + monkeypatch.delenv(key, raising=False) + prompts = [] + + def feed(*replies): + queue = list(replies) + + def fake_input(prompt=""): + prompts.append(prompt) + if not queue: + raise AssertionError(f"unexpected prompt: {prompt!r}") + return queue.pop(0) + + monkeypatch.setattr(builtins, "input", fake_input) + return prompts + + return feed + + +def test_jackett_and_qbittorrent_retry_until_they_validate(server, answers, capsys): + prompts = answers( + "y", + "1", + # Jackett: wrong key, then right key with a wrong password, then the right password + server, "bad-key", "", + "", JACKETT_KEY, "nope", + "", "", ADMIN_PASSWORD, + # qBittorrent: wrong password, then the right one + server, QB_USER, "wrong", + "", "", QB_PASSWORD, + ) # fmt: skip + wizard.run_wizard() + out = capsys.readouterr().out + assert "Jackett connection failed: HTTP 401" in out + assert "Admin Password appears to be incorrect" in out + assert "Jackett connection and authentication successful!" in out + assert "qBittorrent connection failed or auth rejected." in out + assert "qBittorrent connection successful!" in out + assert "Configuration saved!" in out + # The masked key is shown once it is known. + assert any(prompt.startswith("Jackett API Key [jack...3456]") for prompt in prompts) + + settings = load_settings() + assert settings.get("services.jackett") == server + assert settings.get("services.qbittorrent") == server + assert settings.get("search.indexer_manager") == "jackett" + assert settings.get("search.lite_only") is False + assert get_secret("JACKETT_API_KEY") == JACKETT_KEY + assert get_secret("JACKETT_PASSWORD") == ADMIN_PASSWORD + assert get_secret("QB_PASSWORD") == QB_PASSWORD + + +def test_prowlarr_path_saves_prowlarr_settings(server, answers, capsys): + answers("y", "2", server, "bad", "", PROWLARR_KEY, server, QB_USER, QB_PASSWORD) + wizard.run_wizard() + out = capsys.readouterr().out + assert "Prowlarr connection failed: HTTP 401" in out + assert "Prowlarr connection successful!" in out + settings = load_settings() + assert settings.get("services.prowlarr") == server + assert settings.get("search.indexer_manager") == "prowlarr" + assert get_secret("PROWLARR_API_KEY") == PROWLARR_KEY + + +def test_empty_keys_are_asked_again(server, answers, capsys): + answers("y", "1", server, "", "", "", JACKETT_KEY, ADMIN_PASSWORD, server, QB_USER, "", "", "", QB_PASSWORD) + wizard.run_wizard() + out = capsys.readouterr().out + assert "Jackett API key is required." in out + assert "qBittorrent password is required." in out + + +def test_unreachable_services_report_the_error(answers, capsys): + dead = "http://127.0.0.1:9" # discard port: nothing listens + answers("y", "2", dead, PROWLARR_KEY, "q") + with pytest.raises(SystemExit) as stop: + wizard.run_wizard() + assert stop.value.code == 0 + assert "Prowlarr connection failed:" in capsys.readouterr().out + assert get_secret("PROWLARR_API_KEY") is None + + +@pytest.mark.parametrize( + "replies", + [ + ("y", "1", "quit"), + ("y", "1", "", "exit"), + ("y", "1", "", JACKETT_KEY, "q"), + ("y", "2", "", "q"), + ], +) +def test_exit_words_abort_without_saving(server, answers, replies, capsys): + answers(*replies) + with pytest.raises(SystemExit) as stop: + wizard.run_wizard() + assert stop.value.code == 0 + assert load_settings().origin("search.lite_only") == "default" + assert get_secret("JACKETT_API_KEY") is None + + +@pytest.mark.parametrize("field", [0, 1, 2]) +def test_exit_words_in_qbittorrent_prompts(server, answers, field, capsys): + qb = [server, QB_USER, QB_PASSWORD] + qb[field] = "q" + answers("y", "2", server, PROWLARR_KEY, *qb[: field + 1]) + with pytest.raises(SystemExit): + wizard.run_wizard() + assert "Configuration aborted" in capsys.readouterr().out + assert get_secret("QB_PASSWORD") is None + + +def test_ctrl_c_aborts_cleanly(answers, monkeypatch, capsys): + def interrupt(prompt=""): + raise KeyboardInterrupt + + monkeypatch.setattr(builtins, "input", interrupt) + with pytest.raises(SystemExit) as stop: + wizard.run_wizard() + assert stop.value.code == 0 + assert "Configuration aborted" in capsys.readouterr().out From c5c23554f2039d39c612abe2ca1bc69b97cad5db Mon Sep 17 00:00:00 2001 From: Piratebird <141295458+Piratebird@users.noreply.github.com> Date: Tue, 3 Nov 2026 00:38:26 +0200 Subject: [PATCH 11/18] :shipit: chore(release): rename download_torrent, bump to 0.11.0, rerun benchmarks - Rename the Lite downloader's download_magnet to download_torrent, keeping the old name as an alias - Bump the version to 0.11.0 and head the release notes, leaving the date for the tag - Rerun the six- and two-worker loopback benchmarks on a clean tree so source hashes match the code --- CHANGELOG.md | 5 +- docs/BENCHMARK.md | 20 +- docs/benchmarks/local-loopback-workers2.json | 1058 ++++++++++-------- docs/benchmarks/local-loopback.json | 966 ++++++++-------- pyproject.toml | 2 +- src/helm/cli/commands/session.py | 8 +- src/helm/services/jobs.py | 4 +- src/helm/torrents/lite_downloader.py | 6 +- tests/test_cli.py | 6 +- tests/test_cli_commands.py | 4 +- tests/test_jobs.py | 4 +- tests/test_module_paths.py | 6 + 12 files changed, 1148 insertions(+), 941 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 07df20e..76db4f1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,8 +1,11 @@ # Changelog All notable changes to this project will be documented in this file. -## [Unreleased] +## [0.11.0] - Unreleased + +Headless services, layered TOML/JSONC settings with `config` commands, themes and the banner, a rebuilt setup that runs `helm-torrent init` inside the image, and a package restructure. Set the date when this is tagged. ### Changed +- Rename the Lite downloader's `download_magnet` to `download_torrent`, since it also takes `.torrent` URLs and files. `download_magnet` stays as an alias. - Split setup: `setup.sh` now only checks the host (engine, native installs, systemd) and runs `helm-torrent init` inside the Helm image as the current user. `init` writes the compose file, `.env.docker`, API keys and the launcher, and takes `--engine`, `--indexers`, `--run-mode`, `--workdir`, `--socket`, `--project`, `--mount-source` and `--skip-prompts`; it asks for whatever is missing and runs even when the config file is broken. It no longer activates Jackett and Prowlarr indexers through their APIs: Jackett gets the seeded indexer files, and Prowlarr seeds its defaults on first search. If the image cannot be pulled, setup uses a local copy. - Rewrite `setup.sh` as small functions with a short `main`, tested against fake Docker, Podman and systemctl binaries. `setup.sh` and `helm-torrent init` now render one compose template, `src/helm/core/compose.template.yml`, and `docker-compose.yml.example` is removed. Setup no longer edits `config.json`; the indexer choice goes into `.env.docker` as `INDEXER_MANAGER`. The container name prefix is `helm` (or `COMPOSE_PROJECT_NAME`) everywhere, instead of the directory name in `.env.docker`. An existing `qBittorrent.conf` is kept instead of overwritten. - Use the theme everywhere the UI, wizard, one-shot mode and Lite downloader print colour, and show the banner when the UI starts. Colours are now off when output is piped or `NO_COLOR` is set. Red messages that used the terminal's basic red now use the theme's error colour. diff --git a/docs/BENCHMARK.md b/docs/BENCHMARK.md index a936d0e..ad842e0 100644 --- a/docs/BENCHMARK.md +++ b/docs/BENCHMARK.md @@ -1,24 +1,22 @@ # Helm Resource Benchmarks -## Reproducible local workload (October 2026) +## Reproducible local workload (November 2026) The tested harness is [benchmark.py](../src/helm/benchmarks/benchmark.py). Its [raw samples](benchmarks/local-loopback.json) record three trials at six-worker concurrency, per-sample PSS, phase events, checksums, source SHA-256 fingerprints, the base Git revision and dirty-tree status, Python/kernel/CPU details, and whether engine overhead was included. -Measured environment: **11th Gen Intel(R) Core(TM) i5-1135G7 @ 2.40GHz**, 8 logical CPUs, Linux kernel `7.2.11`, Python `3.14.8`, libtorrent `2.0.11.0`. These measurements were taken from an uncommitted working tree; source hashes identify the measured implementation. - -These local figures predate later queue and client changes, so current source hashes do not match every file recorded in the report. +Measured environment: **11th Gen Intel(R) Core(TM) i5-1135G7 @ 2.40GHz**, 8 logical CPUs, Linux kernel `7.2.13`, Python `3.14.8`, libtorrent `2.0.11.0`. Both runs were taken from a clean tree at revision `a232b57` (the `chore/housekeeping` branch, after the package restructure). That revision will not survive the squash merge, so use the recorded source hashes to identify the measured code. The workload consists of a warm idle process, twelve offline search plugins emitting 100 generated results each (1,200 total) through the actual isolated worker pipeline, a real loopback BitTorrent transfer of a generated **4 MiB** payload, session teardown, and process exit. Public trackers, DHT, local discovery, UPnP, and NAT-PMP are disabled for the download. Every transfer is verified by SHA-256. | Phase | Complete samples | Median workload PSS (MiB) | Peak workload PSS (MiB) | | :--- | ---: | ---: | ---: | -| idle | 17 | 20.51 | 20.91 | -| search | 26 | 31.12 | 126.55 | -| download | 32 | 30.85 | 39.83 | -| teardown | 18 | 34.54 | 35.04 | +| idle | 16 | 20.90 | 21.27 | +| search | 23 | 22.97 | 125.83 | +| download | 30 | 32.02 | 40.77 | +| teardown | 19 | 35.94 | 35.97 | | exited | 3 | 0.00 | 0.00 | -Median twelve-job fixture search latency: **0.498 s**, range **0.487–0.524 s**. Median loopback download phase: **0.738 s**, range **0.699–0.740 s**. Download timing includes fixture generation, torrent/session setup, transfer, flushing, and checksum verification; it is not a pure network-throughput measurement. +Median twelve-job fixture search latency: **0.472 s**, range **0.463–0.497 s**. Median loopback download phase: **0.741 s**, range **0.697–0.746 s**. Download timing includes fixture generation, torrent/session setup, transfer, flushing, and checksum verification; it is not a pure network-throughput measurement. Teardown retains the Python process and loaded native libraries. Only the `exited` sample reflects the reaped workload; a zero there says nothing about whole-host RAM usage. Races with exiting processes are marked incomplete and excluded from median/peak calculations rather than counted as zero. @@ -28,8 +26,8 @@ The [two-worker samples](benchmarks/local-loopback-workers2.json) use the same t | Concurrent search workers | Median search latency (s) | Peak search workload PSS (MiB) | | ---: | ---: | ---: | -| 6 | 0.498 | 126.55 | -| 2 | 0.862 | 58.73 | +| 6 | 0.472 | 125.83 | +| 2 | 0.870 | 59.69 | Two workers reduced the observed peak memory at the cost of a longer fixture search. This host-only comparison does not establish an optimal Android setting. The CLI exposes `--lite-workers 2` (or `HELM_LITE_WORKERS=2`), with six as the default and a valid range of 1–12. The shared search deadline includes queueing, so fewer workers can leave more jobs unstarted when early sources stall; these are reported as `budget_exhausted`. diff --git a/docs/benchmarks/local-loopback-workers2.json b/docs/benchmarks/local-loopback-workers2.json index 7bc4b98..852967c 100644 --- a/docs/benchmarks/local-loopback-workers2.json +++ b/docs/benchmarks/local-loopback-workers2.json @@ -3,50 +3,84 @@ "mode": "local_fixture_search_and_loopback_bittorrent", "metric": "PSS bytes; same metric for every component", "environment": { - "platform": "Linux-7.2.11-200.fc44.x86_64-x86_64-with-glibc2.43", + "platform": "Linux-7.2.13-200.fc44.x86_64-x86_64-with-glibc2.43", "python": "3.14.8 (main, Oct 1 2026, 00:00:00) [GCC 16.2.1 20260819 (Red Hat 16.2.1-2)]", "cpu_count": 8, "cpu_model": "11th Gen Intel(R) Core(TM) i5-1135G7 @ 2.40GHz", "source_sha256": { "__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "cli.py": "1d826809006ec312575cc34d3e0876b50cfae043121e83a61bbb4d6446d475d9", - "core/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "core/benchmark.py": "d3b790f5f5f3e56bac21f60c64b8a245bfaed2c9387d2f9ae142f02dd4c51518", - "core/config_manager.py": "6f71069e1544145b5ab2c324326df1f7d75250ec4bba4d5361e60c8251e5686c", - "core/config_wizard.py": "d3303501145dad0e49dd19c6e6153c19a039b0e479a14f72ead24ededfb8f6c0", - "core/http.py": "3d36d9d66e954610b0b8e925251af38959d1c7e606ebdcdbfd5501ba03c6f344", - "core/indexer_manager.py": "1435e21114ff5de6da67e084a13103b8cd25bbe91367f118d75fb5c95c130472", - "core/init_env.py": "f8eab6975fc5c7ce2b6b86658eeb7eb3feb36bd70d95f0204cd285c5ae7f330c", - "core/lite_downloader.py": "064f39174a24d6113c1cfd56f064e247ed40642ae3d080640b4f35f565c6dc63", - "core/lite_fetcher.py": "dd7505d13c6107347ec962c7e1868b79112992800b8873d47691cfdb8dbe2e36", - "core/lite_plugin_loader.py": "419dea428158a28314a7a192cabd88e54b078d8542258db243bbad2c2f141b0d", - "core/logger.py": "fba54c1264da77f2faf8fa5b6fc3df66fecd5e01d6f8be52fdd4edca202106bf", - "core/oneshot.py": "e1ac659d8e95f39c11da837d3bc6cd101a8949a7c41cfe2b322c6f6b963dac8e", - "core/qbittorrent_client.py": "7a412585b4f0b056a43b4040cba95b00e12ba0de0ae395d91590aa0bb3a36276", - "core/rss_fetcher.py": "9b3f508ab7add45b99bba9526679ae21063d75fa04728eb97ba7a8cf82e426a7", - "core/search_runner.py": "782a28401bafd86e9e38b77afd8f50cd241c2f0d2f9f30371e08f3b2efcb96fd", - "core/secret_manager.py": "2d9a15ad2483fe3976c05dccc76f9814f6df0dbeb2e9cd943f47c85f17ec02ee", - "core/torrent_filter.py": "662daedbbafbb4197ac8e9aec68b033001f9317b8745aa92741d52e7da9934a0", + "benchmarks/__init__.py": "fc3ac8c8a6223d39b3624cdf421f4c0efa03791c4653691523a7c782588f631b", + "benchmarks/benchmark.py": "e49e85ba2fe5ec6384d8b62f38a658ead6c0521056d3ccb1f1237144bf22d11b", + "benchmarks/device_profile.py": "aa3cfeefba70f5f84eb43098f29c093e1cc4d5f07647af99218d177b3cc4820e", + "benchmarks/stack_benchmark.py": "fe2ec4cbf2499bd8301b4b002b64b838bf63db3fd69d28450dd73b3941c58019", + "cli/__init__.py": "2c240c4b6d2187f87323f2aadefb6caa9d9b29ae6580782e70f696ab2e8628dc", + "cli/__main__.py": "7d865e3f883b9a0fbecc11f6199aa359edcba74fe013ecd1f7d3656e482a4d0f", + "cli/app.py": "4dbfa3c53c32b7d067e64bd10e57d69ac6e17df5a14f0ec00ded77ea7e10b8ab", + "cli/commands/__init__.py": "8f60f64f201bed74d3881f0ee25e73408230a4c95d26b74363130cf7f5c7424c", + "cli/commands/background.py": "1d3345b8b7e04173e2bb89cfee6b00b8f0fa9c9fcebcacc9b1dc62a0493c24bd", + "cli/commands/banner.py": "1fc7225d888c2576670e614eb40260bb705898a30a2d3fca8239d81cc956c5e6", + "cli/commands/headless.py": "18808e7a9c5e6e7ccc0b8f5739469880c89168c2daba2917501b3fb0fe61de8d", + "cli/commands/indexers.py": "977caeb59da571a933ccae2905dc0ec64be01167d76676a4e2d55fd1455a9e94", + "cli/commands/session.py": "716c8a2f1bdb29dd229de9742eb2b261bc78e71626c03c6103241150fdbb455b", + "cli/commands/status.py": "edace4681910fdea8e3f1299197727d873d0274803ff0ec7212d14983c568f03", + "cli/commands/utility.py": "4d6ad72918b541fe2be60f8c588518c6080ae2ac85dad1e0108d80846223405c", + "cli/deps.py": "9ff2fb551f5f2c5fd3b2c2f49fa86741501ffc75a9d6de05cfcc68b65c91e6b6", + "cli/parser.py": "b8e9ec20ca30c48ea0770cae343e880f01203a60aa3bdc26c39176eb7133cae7", + "config/__init__.py": "3f1f275db788286c6c3ba3cb4b9ac9a57e30de2e91a84de5e70dd390ae801761", + "config/config_commands.py": "2699a907ec9d2edeb6960822043a2562c3d1bb8e4b66678bed5f4f49c571ab1b", + "config/config_manager.py": "17dab7f0234bde9202684600789f85b07e1f6bd5dcfc269293b732cda25f6b36", + "config/config_wizard.py": "fc67b530bf0701c9ac1b5be5475cdda2c9a4e002d9eee4d43ae22d875d8c24d1", + "config/secret_manager.py": "986f85bb888587808060817b485eca679ae3d6923c9286d1bda54b9710db30e3", + "config/settings.py": "3e6623c612d715c46e00f8e670726a22cdf3cd9bebc6ffad074a01575252bd66", + "core/__init__.py": "3708ab27751586375c25366dcd398e9f42ccffa63c6b488be960b29edf21f85e", + "core/http.py": "b6428bb3cb9f172d1a5dee1327dfcc58b5d419840f8fb47ac2f1f94cfe733b8d", + "core/logger.py": "bc333a1dda9fd9fd083df15803f6f3205ebc306758f6105c2414fab007255cfd", + "core/rss_fetcher.py": "64e843e22c6e78d3313f93ae56faa0beb26d91fbe6ebbbb7f2adcdedef0e8058", + "logger.py": "8c855cf485a29b2a9eb58f5b49c22d5d647e3df6c5efb96bcbc16db308db8c7a", + "net/__init__.py": "87f121e104cc83ae03d5b6a7e3aec85ba8966ea8ad747ccf9aeb13f616759fc8", + "net/http.py": "3d36d9d66e954610b0b8e925251af38959d1c7e606ebdcdbfd5501ba03c6f344", "plugins/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "plugins/bitsearch.py": "4a648f04b729a6556036ca5ee830c3db4a85b492a9d6e9524e7c38864a062a4f", - "plugins/bittorrented.py": "1077d397916be8c83471db61a2733426417119109bf53694bd2dd22b34fe9873", - "plugins/eztv.py": "8576d0f09636ef1da55024fcdab7212f4c9627d339fbc6657fce573823e6e6b0", - "plugins/helpers.py": "9af508d98875f399e98ee60428153cec41140b41a0bc8c2da23ca743a4e81556", + "plugins/bittorrented.py": "ae36b2665c46758cd4e91c2e5f016de1fcaadbf11042f4340cac110cf2c70e8c", + "plugins/eztv.py": "6e0c211102acbecc3fc7f2f556ac56c3c0d12113df1dd21bf4f0600c85551df9", + "plugins/helpers.py": "30d7ca263bee97bf68010dd1e0adc75cdd157f8a19903f11089b6faa0decd628", "plugins/limetorrents.py": "60f8f6321664108875accd2585a8d51e4fbf5fb5c88d63d3ec8733a6ad1aa68a", - "plugins/novaprinter.py": "a3193175bd64d9517d368ff4ba70d2c56d85011d18d8f196c82ff308e8cc685e", + "plugins/novaprinter.py": "5f083f8675cc22b194f0d8dd29d5c32d3bc63f7d4c4916be0e7af8bf22e286b3", "plugins/piratebay.py": "21f760eac8d931ac25dc05a79654f14313a30d48d81f878e857a25f4e226bc3f", - "plugins/subsplease.py": "4117d2cd8f58e9ace19c5d9287f1b2307fab0d32a6fc15898f3e6ef75c37f402", + "plugins/subsplease.py": "565e41b0cfd61918f4a62312196b3d878608720a943bab1e97141f6d3b19bea9", "plugins/torlock.py": "2d818ddda16c4e150878be63c0b0ff03f2e746bef73e8a86e38758366d235071", - "plugins/torrentproject.py": "1f8c5be60357f1d4baf4ba2722aa316e5bdd50324209f8b22aa902a6abad4c86", - "plugins/x1337.py": "29dbdd5c57b95e7750b20b5bd8cfdb324dc6e3db8cde5e9005e4f5295157b581", - "plugins/yts.py": "fdd2e0236aacf0e43cdf2a43abd16ee33fdb5f736de84ed357afb54a9c1df0fe", + "plugins/torrentproject.py": "0918e7ddd6369b76ba3dc9c007e79253ccde365d1b0716519cdbcf901432135c", + "plugins/x1337.py": "9945129ed2213e01d6f7f3fa607af02d131ac2da348b098b8ed3180b2fa338ca", + "plugins/yts.py": "3bf5fdd085d562023a51ba267a4ea43904bf93a9eca940aaa56594b89ee583aa", + "search/__init__.py": "77507206d32e57cd8de4ae48a889bd2399bd92691cb388d3bb702e0e3f67ce31", + "search/indexer_manager.py": "e2e2d780c3d4297ea6057244659cf1ee024b1b4168bcc56ffb1b63aefeac760d", + "search/lite_fetcher.py": "63dd593e8c6f58f4acd455b9638cb7e0c5e6f822b2f87670d6a6428cb6ec712c", + "search/lite_plugin_loader.py": "fea7e6f2049d62fdc8f3877eb26891bb6e78013c674c5ccaf6a24365c17fed35", + "search/rss_fetcher.py": "31d956e480537be4d5a2bc9a7db18da3eb0cc995a9dc27c8797708f9a39ffce6", + "search/search_runner.py": "9b10be4eb732ab3bf8763544512bdfabd99e102a967c4d21b418d2dbe74c4545", + "search/torrent_filter.py": "662daedbbafbb4197ac8e9aec68b033001f9317b8745aa92741d52e7da9934a0", + "services/__init__.py": "828c2c304f29d93f54a785175864752dd285e6585f0898d955764f371a798195", + "services/jobs.py": "c1b1c7489d10983f40544c10d379cb2d4414ce9750e238a737f00ece27d79af3", + "services/runtime.py": "2450c86d0c565222897d5d8aa2d6daef247fc10090e271078a9567ae3197cfc1", + "services/server.py": "a428ea6dd55dddb535313b2eb34815a92f00f92c1f8c78235728daea0ce9363e", + "services/watch.py": "e09c4e6102d7ad7aac38372cdf2d5d1e52a80cc5b8bf5142d4ec73f9cf803692", + "stack/__init__.py": "71f4313c5d8fa5faa2d75a7fdc743cf37b0260e4aa11e2755e5827ced6d975cf", + "stack/compose.py": "40a37373e83a63c4cf08ad8a7c740f065c6fc5a816ad6dd6435a6c7b1c7f5470", + "stack/oneshot.py": "211bda37474b3eb3f8c87c445d90ee6aba2cbcf5f3c7ac2e36002726b6390adc", + "stack/stack_setup.py": "b979c41a80bba3f1466f3c9330aebe63a7eb2147d332988b87f0ad07c07a06f7", + "torrents/__init__.py": "b15760d6997bbd9cc7cb8662f11d37355afdc68472a8f5429522806bee486ad8", + "torrents/lite_downloader.py": "8ce068844f3838b9ee5286be59a64768b69ffaaf7e4d4cc5a2a33adc9a4c93d5", + "torrents/qbittorrent_client.py": "4022444861679a2174c0b48370ffe193cd7f6d73de4c40d31e4aed55c0f632a5", + "torrents/torrent_links.py": "30c93436ce89489c803a26c632c957ec657d4b7cd1308a32f75bfe08d73ab7d1", "ui/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "ui/colors.py": "192984be5f757359e15eb93ce1cd71083d257538199d8567dd5d9501a7481f37", - "ui/tui.py": "06a59767dfdbfc55876866e2e18d471430e56055ca232a8fc7360a893ef2ee2e" + "ui/ansi.py": "66803be9c479200396ef5bfe183e5dce8ef95cc69076118a290ceab7eedfacc7", + "ui/banner.py": "083560dedbc23b9fb80c2c9348ed72b44c041880fbc4b1037fb4c6f9fbf2ab39", + "ui/theme.py": "9054413e71db83598200f022122e138569183eb17f7e2c8669868da7cb3cc540", + "ui/tui.py": "42227141d9efae94710a3a1e98663602c9f6e0f7b72b855b779637456ca7b1f7" }, "cgroup_version": 2, - "revision": "f61d816128b4c98ee012fb9981e441852b758f2d", - "dirty": true + "revision": "a232b57897605468d4ed4a2cb589825757bfa1ea", + "dirty": false }, "interval_seconds": 0.05, "payload_bytes": 4194304, @@ -66,380 +100,380 @@ { "samples": [ { - "elapsed_seconds": 0.06566078400283004, - "phase": "idle", + "elapsed_seconds": 0.09462384099970222, + "phase": "startup", "missing_pids": [], - "workload_pss_bytes": 21517312, + "workload_pss_bytes": 21901312, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 21517312, + "accounted_pss_bytes": 21901312, "complete": true }, { - "elapsed_seconds": 0.14384482900277362, + "elapsed_seconds": 0.12959981599851744, "phase": "idle", "missing_pids": [], - "workload_pss_bytes": 21517312, + "workload_pss_bytes": 21901312, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 21517312, + "accounted_pss_bytes": 21901312, "complete": true }, { - "elapsed_seconds": 0.22582816000067396, + "elapsed_seconds": 0.20454576399788493, "phase": "idle", "missing_pids": [], - "workload_pss_bytes": 21517312, + "workload_pss_bytes": 21901312, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 21517312, + "accounted_pss_bytes": 21901312, "complete": true }, { - "elapsed_seconds": 0.30568986000071163, + "elapsed_seconds": 0.30010085399771924, "phase": "idle", "missing_pids": [], - "workload_pss_bytes": 21517312, + "workload_pss_bytes": 21901312, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 21517312, + "accounted_pss_bytes": 21901312, "complete": true }, { - "elapsed_seconds": 0.38711015000080806, + "elapsed_seconds": 0.3798606659984216, "phase": "idle", "missing_pids": [], - "workload_pss_bytes": 21517312, + "workload_pss_bytes": 21901312, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 21517312, + "accounted_pss_bytes": 21901312, "complete": true }, { - "elapsed_seconds": 0.4667847540004004, + "elapsed_seconds": 0.461537438997766, "phase": "idle", "missing_pids": [], - "workload_pss_bytes": 21675008, + "workload_pss_bytes": 21901312, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 21675008, + "accounted_pss_bytes": 21901312, "complete": true }, { - "elapsed_seconds": 0.488049368999782, + "elapsed_seconds": 0.48515217999738525, "phase": "search", "missing_pids": [], - "workload_pss_bytes": 37730304, + "workload_pss_bytes": 22048768, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 37730304, + "accounted_pss_bytes": 22048768, "complete": true }, { - "elapsed_seconds": 0.5609896669993759, + "elapsed_seconds": 0.5564298059980501, "phase": "search", "missing_pids": [], - "workload_pss_bytes": 59568128, + "workload_pss_bytes": 58084352, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 59568128, + "accounted_pss_bytes": 58084352, "complete": true }, { - "elapsed_seconds": 0.6321623639996687, + "elapsed_seconds": 0.627465208999638, "phase": "search", "missing_pids": [], - "workload_pss_bytes": 37929984, + "workload_pss_bytes": 37680128, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 37929984, + "accounted_pss_bytes": 37680128, "complete": true }, { - "elapsed_seconds": 0.7036465870005486, + "elapsed_seconds": 0.7003965750009229, "phase": "search", "missing_pids": [], - "workload_pss_bytes": 61088768, + "workload_pss_bytes": 61101056, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 61088768, + "accounted_pss_bytes": 61101056, "complete": true }, { - "elapsed_seconds": 0.7745498700023745, + "elapsed_seconds": 0.7717582849982136, "phase": "search", "missing_pids": [], - "workload_pss_bytes": 37982208, + "workload_pss_bytes": 40170496, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 37982208, + "accounted_pss_bytes": 40170496, "complete": true }, { - "elapsed_seconds": 0.8464703499994357, + "elapsed_seconds": 0.844836005999241, "phase": "search", "missing_pids": [], - "workload_pss_bytes": 60766208, + "workload_pss_bytes": 62416896, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 60766208, + "accounted_pss_bytes": 62416896, "complete": true }, { - "elapsed_seconds": 0.933206911002344, + "elapsed_seconds": 0.9169016929990903, "phase": "search", "missing_pids": [], - "workload_pss_bytes": 42420224, + "workload_pss_bytes": 44382208, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 42420224, + "accounted_pss_bytes": 44382208, "complete": true }, { - "elapsed_seconds": 1.0073068990022875, + "elapsed_seconds": 0.9898763429991959, "phase": "search", "missing_pids": [], - "workload_pss_bytes": 61462528, + "workload_pss_bytes": 62547968, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 61462528, + "accounted_pss_bytes": 62547968, "complete": true }, { - "elapsed_seconds": 1.0795298459997866, + "elapsed_seconds": 1.0667993179995392, "phase": "search", "missing_pids": [], - "workload_pss_bytes": 44981248, + "workload_pss_bytes": 46258176, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 44981248, + "accounted_pss_bytes": 46258176, "complete": true }, { - "elapsed_seconds": 1.1537017440023192, + "elapsed_seconds": 1.140664056998503, "phase": "search", "missing_pids": [], - "workload_pss_bytes": 61583360, + "workload_pss_bytes": 60508160, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 61583360, + "accounted_pss_bytes": 60508160, "complete": true }, { - "elapsed_seconds": 1.2255593150002824, + "elapsed_seconds": 1.21302217199991, "phase": "search", "missing_pids": [], - "workload_pss_bytes": 47498240, + "workload_pss_bytes": 51657728, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 47498240, + "accounted_pss_bytes": 51657728, "complete": true }, { - "elapsed_seconds": 1.2989146540021466, + "elapsed_seconds": 1.2862824570001976, "phase": "search", "missing_pids": [], - "workload_pss_bytes": 42148864, + "workload_pss_bytes": 43005952, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 42148864, + "accounted_pss_bytes": 43005952, "complete": true }, { - "elapsed_seconds": 1.3280569700000342, + "elapsed_seconds": 1.3084886190008547, "phase": "search", "missing_pids": [], - "workload_pss_bytes": 22459392, + "workload_pss_bytes": 23097344, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 22459392, + "accounted_pss_bytes": 23097344, "complete": true }, { - "elapsed_seconds": 1.4080660350009566, + "elapsed_seconds": 1.3887539120005385, "phase": "search", "missing_pids": [], - "workload_pss_bytes": 22459392, + "workload_pss_bytes": 23097344, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 22459392, + "accounted_pss_bytes": 23097344, "complete": true }, { - "elapsed_seconds": 1.4884746140014613, + "elapsed_seconds": 1.470301090997964, "phase": "search", "missing_pids": [], - "workload_pss_bytes": 22459392, + "workload_pss_bytes": 23097344, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 22459392, + "accounted_pss_bytes": 23097344, "complete": true }, { - "elapsed_seconds": 1.5352750769998238, + "elapsed_seconds": 1.5131358289982018, "phase": "download", "missing_pids": [], - "workload_pss_bytes": 31659008, + "workload_pss_bytes": 32027648, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 31659008, + "accounted_pss_bytes": 32027648, "complete": true }, { - "elapsed_seconds": 1.610968277000211, + "elapsed_seconds": 1.5947332219984673, "phase": "download", "missing_pids": [], - "workload_pss_bytes": 31806464, + "workload_pss_bytes": 32695296, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 31806464, + "accounted_pss_bytes": 32695296, "complete": true }, { - "elapsed_seconds": 1.681868186002248, + "elapsed_seconds": 1.67595547000019, "phase": "download", "missing_pids": [], - "workload_pss_bytes": 31806464, + "workload_pss_bytes": 32695296, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 31806464, + "accounted_pss_bytes": 32695296, "complete": true }, { - "elapsed_seconds": 1.7548216030008916, + "elapsed_seconds": 1.7578508039987355, "phase": "download", "missing_pids": [], - "workload_pss_bytes": 31810560, + "workload_pss_bytes": 32695296, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 31810560, + "accounted_pss_bytes": 32695296, "complete": true }, { - "elapsed_seconds": 1.8302660000008473, + "elapsed_seconds": 1.839315147997695, "phase": "download", "missing_pids": [], - "workload_pss_bytes": 31810560, + "workload_pss_bytes": 32695296, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 31810560, + "accounted_pss_bytes": 32695296, "complete": true }, { - "elapsed_seconds": 1.9131214059998456, + "elapsed_seconds": 1.9111980679990666, "phase": "download", "missing_pids": [], - "workload_pss_bytes": 31810560, + "workload_pss_bytes": 32695296, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 31810560, + "accounted_pss_bytes": 32695296, "complete": true }, { - "elapsed_seconds": 1.9939416740016895, + "elapsed_seconds": 1.984329375998641, "phase": "download", "missing_pids": [], - "workload_pss_bytes": 31810560, + "workload_pss_bytes": 32695296, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 31810560, + "accounted_pss_bytes": 32695296, "complete": true }, { - "elapsed_seconds": 2.0745049489996745, + "elapsed_seconds": 2.0628332769992994, "phase": "download", "missing_pids": [], - "workload_pss_bytes": 36706304, + "workload_pss_bytes": 37601280, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 36706304, + "accounted_pss_bytes": 37601280, "complete": true }, { - "elapsed_seconds": 2.1542616030019417, + "elapsed_seconds": 2.138455272997817, "phase": "download", "missing_pids": [], - "workload_pss_bytes": 36706304, + "workload_pss_bytes": 37601280, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 36706304, + "accounted_pss_bytes": 37601280, "complete": true }, { - "elapsed_seconds": 2.227102229000593, + "elapsed_seconds": 2.2117357489987626, "phase": "download", "missing_pids": [], - "workload_pss_bytes": 35576832, + "workload_pss_bytes": 36470784, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 35576832, + "accounted_pss_bytes": 36470784, "complete": true }, { - "elapsed_seconds": 2.247419188002823, + "elapsed_seconds": 2.230755279000732, "phase": "teardown", "missing_pids": [], - "workload_pss_bytes": 35576832, + "workload_pss_bytes": 36470784, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 35576832, + "accounted_pss_bytes": 36470784, "complete": true }, { - "elapsed_seconds": 2.325937582001643, + "elapsed_seconds": 2.3119333129980078, "phase": "teardown", "missing_pids": [], - "workload_pss_bytes": 35576832, + "workload_pss_bytes": 36470784, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 35576832, + "accounted_pss_bytes": 36470784, "complete": true }, { - "elapsed_seconds": 2.4095515590015566, + "elapsed_seconds": 2.393137103998015, "phase": "teardown", "missing_pids": [], - "workload_pss_bytes": 35576832, + "workload_pss_bytes": 36470784, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 35576832, + "accounted_pss_bytes": 36470784, "complete": true }, { - "elapsed_seconds": 2.492360832002305, + "elapsed_seconds": 2.4757557269986137, "phase": "teardown", "missing_pids": [], - "workload_pss_bytes": 35576832, + "workload_pss_bytes": 36470784, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 35576832, + "accounted_pss_bytes": 36470784, "complete": true }, { - "elapsed_seconds": 2.5708922970006824, + "elapsed_seconds": 2.556733148998319, "phase": "teardown", "missing_pids": [], - "workload_pss_bytes": 35576832, + "workload_pss_bytes": 36470784, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 35576832, + "accounted_pss_bytes": 36470784, "complete": true }, { - "elapsed_seconds": 2.648385895001411, + "elapsed_seconds": 2.630611926000711, "phase": "teardown", "missing_pids": [], - "workload_pss_bytes": 35576832, + "workload_pss_bytes": 36475904, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 35576832, + "accounted_pss_bytes": 36475904, "complete": true }, { - "elapsed_seconds": 2.670051468001475, + "elapsed_seconds": 2.6517436709982576, "phase": "teardown", "missing_pids": [ - 487093 + 2546261 ], "workload_pss_bytes": 0, "attached_stack_pss_bytes": 0, @@ -448,7 +482,7 @@ "complete": false }, { - "elapsed_seconds": 2.670157680000557, + "elapsed_seconds": 2.651846213000681, "phase": "exited", "missing_pids": [], "workload_pss_bytes": 0, @@ -462,26 +496,44 @@ { "phase": "idle" }, + { + "phase": "idle", + "cpu_user_seconds": 4.999999999999449e-05, + "cpu_system_seconds": 0, + "cpu_seconds": 4.999999999999449e-05 + }, { "phase": "search" }, { "phase": "search", - "search_seconds": 0.8622720989988011, - "result_count": 1200 + "search_seconds": 0.8242024319988559, + "result_count": 1200, + "cpu_user_seconds": 1.438451, + "cpu_system_seconds": 0.18233799999999997, + "cpu_seconds": 1.6207889999999998 }, { "phase": "download" }, { "phase": "download", - "download_seconds": 0.7026336640010413, + "download_seconds": 0.705106440000236, "payload_bytes": 4194304, "sha256": "2b07811057df887086f06a67edc6ebf911de8b6741156e7a2eb1416a4b8b1b2e", - "libtorrent_version": "2.0.11.0" + "libtorrent_version": "2.0.11.0", + "cpu_user_seconds": 0.08651299999999984, + "cpu_system_seconds": 0.043697000000000014, + "cpu_seconds": 0.13020999999999985 }, { "phase": "teardown" + }, + { + "phase": "teardown", + "cpu_user_seconds": 0.005552000000000001, + "cpu_system_seconds": 0, + "cpu_seconds": 0.005552000000000001 } ], "summary": { @@ -489,8 +541,8 @@ "sample_count": 10, "incomplete_samples": 0, "workload_pss_bytes": { - "median": 31810560.0, - "peak": 36706304 + "median": 32695296.0, + "peak": 37601280 }, "attached_stack_pss_bytes": { "median": 0.0, @@ -501,8 +553,8 @@ "peak": 0 }, "accounted_pss_bytes": { - "median": 31810560.0, - "peak": 36706304 + "median": 32695296.0, + "peak": 37601280 } }, "exited": { @@ -526,31 +578,51 @@ } }, "idle": { - "sample_count": 6, + "sample_count": 5, "incomplete_samples": 0, "workload_pss_bytes": { - "median": 21517312.0, - "peak": 21675008 + "median": 21901312, + "peak": 21901312 }, "attached_stack_pss_bytes": { - "median": 0.0, + "median": 0, "peak": 0 }, "engine_pss_bytes": { - "median": 0.0, + "median": 0, "peak": 0 }, "accounted_pss_bytes": { - "median": 21517312.0, - "peak": 21675008 + "median": 21901312, + "peak": 21901312 } }, "search": { "sample_count": 15, "incomplete_samples": 0, "workload_pss_bytes": { - "median": 42420224, - "peak": 61583360 + "median": 44382208, + "peak": 62547968 + }, + "attached_stack_pss_bytes": { + "median": 0, + "peak": 0 + }, + "engine_pss_bytes": { + "median": 0, + "peak": 0 + }, + "accounted_pss_bytes": { + "median": 44382208, + "peak": 62547968 + } + }, + "startup": { + "sample_count": 1, + "incomplete_samples": 0, + "workload_pss_bytes": { + "median": 21901312, + "peak": 21901312 }, "attached_stack_pss_bytes": { "median": 0, @@ -561,16 +633,16 @@ "peak": 0 }, "accounted_pss_bytes": { - "median": 42420224, - "peak": 61583360 + "median": 21901312, + "peak": 21901312 } }, "teardown": { "sample_count": 7, "incomplete_samples": 1, "workload_pss_bytes": { - "median": 35576832.0, - "peak": 35576832 + "median": 36470784.0, + "peak": 36475904 }, "attached_stack_pss_bytes": { "median": 0.0, @@ -581,8 +653,8 @@ "peak": 0 }, "accounted_pss_bytes": { - "median": 35576832.0, - "peak": 35576832 + "median": 36470784.0, + "peak": 36475904 } } } @@ -590,392 +662,390 @@ { "samples": [ { - "elapsed_seconds": 0.0712286439993477, + "elapsed_seconds": 0.06938299700050266, "phase": "startup", "missing_pids": [], - "workload_pss_bytes": 15787008, + "workload_pss_bytes": 16095232, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 15787008, + "accounted_pss_bytes": 16095232, "complete": true }, { - "elapsed_seconds": 0.1286699199990835, + "elapsed_seconds": 0.1220554319988878, "phase": "idle", "missing_pids": [], - "workload_pss_bytes": 21502976, + "workload_pss_bytes": 21900288, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 21502976, + "accounted_pss_bytes": 21900288, "complete": true }, { - "elapsed_seconds": 0.2107391319987073, + "elapsed_seconds": 0.20346836099997745, "phase": "idle", "missing_pids": [], - "workload_pss_bytes": 21502976, + "workload_pss_bytes": 21900288, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 21502976, + "accounted_pss_bytes": 21900288, "complete": true }, { - "elapsed_seconds": 0.2818443729993305, + "elapsed_seconds": 0.284447750000254, "phase": "idle", "missing_pids": [], - "workload_pss_bytes": 21502976, + "workload_pss_bytes": 21900288, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 21502976, + "accounted_pss_bytes": 21900288, "complete": true }, { - "elapsed_seconds": 0.3602309689995309, + "elapsed_seconds": 0.3554697309991752, "phase": "idle", "missing_pids": [], - "workload_pss_bytes": 21502976, + "workload_pss_bytes": 21900288, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 21502976, + "accounted_pss_bytes": 21900288, "complete": true }, { - "elapsed_seconds": 0.4390003349981271, + "elapsed_seconds": 0.43044100599945523, "phase": "idle", "missing_pids": [], - "workload_pss_bytes": 21502976, + "workload_pss_bytes": 21900288, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 21502976, + "accounted_pss_bytes": 21900288, "complete": true }, { - "elapsed_seconds": 0.5200478749975446, + "elapsed_seconds": 0.5029799199983245, "phase": "idle", "missing_pids": [], - "workload_pss_bytes": 21651456, + "workload_pss_bytes": 21900288, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 21651456, + "accounted_pss_bytes": 21900288, "complete": true }, { - "elapsed_seconds": 0.5407644689985318, + "elapsed_seconds": 0.5401276830016286, "phase": "search", "missing_pids": [], - "workload_pss_bytes": 36822016, + "workload_pss_bytes": 22048768, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 36822016, + "accounted_pss_bytes": 22048768, "complete": true }, { - "elapsed_seconds": 0.6115623500008951, + "elapsed_seconds": 0.6287086330012244, "phase": "search", "missing_pids": [], - "workload_pss_bytes": 59002880, + "workload_pss_bytes": 58835968, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 59002880, + "accounted_pss_bytes": 58835968, "complete": true }, { - "elapsed_seconds": 0.6815234419991612, + "elapsed_seconds": 0.7088727810005366, "phase": "search", "missing_pids": [], - "workload_pss_bytes": 37175296, + "workload_pss_bytes": 30544896, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 37175296, + "accounted_pss_bytes": 30544896, "complete": true }, { - "elapsed_seconds": 0.7532711569983803, + "elapsed_seconds": 0.7871926269981486, "phase": "search", "missing_pids": [], - "workload_pss_bytes": 59341824, + "workload_pss_bytes": 56504320, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 59341824, + "accounted_pss_bytes": 56504320, "complete": true }, { - "elapsed_seconds": 0.8247592309999163, + "elapsed_seconds": 0.8600712609986658, "phase": "search", "missing_pids": [], - "workload_pss_bytes": 37870592, + "workload_pss_bytes": 30323712, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 37870592, + "accounted_pss_bytes": 30323712, "complete": true }, { - "elapsed_seconds": 0.8972130639995157, + "elapsed_seconds": 0.9345557820015529, "phase": "search", "missing_pids": [], - "workload_pss_bytes": 60341248, + "workload_pss_bytes": 59259904, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 60341248, + "accounted_pss_bytes": 59259904, "complete": true }, { - "elapsed_seconds": 0.9854637600001297, + "elapsed_seconds": 1.005641995001497, "phase": "search", "missing_pids": [], - "workload_pss_bytes": 42741760, + "workload_pss_bytes": 41312256, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 42741760, + "accounted_pss_bytes": 41312256, "complete": true }, { - "elapsed_seconds": 1.071560327000043, + "elapsed_seconds": 1.0791421889989579, "phase": "search", - "missing_pids": [ - 487289 - ], - "workload_pss_bytes": 41971712, + "missing_pids": [], + "workload_pss_bytes": 61602816, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 41971712, - "complete": false + "accounted_pss_bytes": 61602816, + "complete": true }, { - "elapsed_seconds": 1.145116486997722, + "elapsed_seconds": 1.1553013890006696, "phase": "search", "missing_pids": [], - "workload_pss_bytes": 46352384, + "workload_pss_bytes": 46799872, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 46352384, + "accounted_pss_bytes": 46799872, "complete": true }, { - "elapsed_seconds": 1.218326538997644, + "elapsed_seconds": 1.2282040899990534, "phase": "search", "missing_pids": [], - "workload_pss_bytes": 42038272, + "workload_pss_bytes": 42868736, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 42038272, + "accounted_pss_bytes": 42868736, "complete": true }, { - "elapsed_seconds": 1.2918193549994612, + "elapsed_seconds": 1.2999099730004673, "phase": "search", "missing_pids": [], - "workload_pss_bytes": 49635328, + "workload_pss_bytes": 49575936, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 49635328, + "accounted_pss_bytes": 49575936, "complete": true }, { - "elapsed_seconds": 1.3642784679977922, + "elapsed_seconds": 1.3740387830002874, "phase": "search", "missing_pids": [], - "workload_pss_bytes": 41114624, + "workload_pss_bytes": 38278144, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 41114624, + "accounted_pss_bytes": 38278144, "complete": true }, { - "elapsed_seconds": 1.3848024899998563, + "elapsed_seconds": 1.3940466700005345, "phase": "search", "missing_pids": [], - "workload_pss_bytes": 22443008, + "workload_pss_bytes": 23094272, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 22443008, + "accounted_pss_bytes": 23094272, "complete": true }, { - "elapsed_seconds": 1.458309019999433, + "elapsed_seconds": 1.4803985149992513, "phase": "search", "missing_pids": [], - "workload_pss_bytes": 22443008, + "workload_pss_bytes": 23094272, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 22443008, + "accounted_pss_bytes": 23094272, "complete": true }, { - "elapsed_seconds": 1.5376905169978272, + "elapsed_seconds": 1.5630456209983095, "phase": "search", "missing_pids": [], - "workload_pss_bytes": 22443008, + "workload_pss_bytes": 23094272, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 22443008, + "accounted_pss_bytes": 23094272, "complete": true }, { - "elapsed_seconds": 1.5910056610009633, + "elapsed_seconds": 1.5938274430009187, "phase": "download", "missing_pids": [], - "workload_pss_bytes": 31036416, + "workload_pss_bytes": 32078848, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 31036416, + "accounted_pss_bytes": 32078848, "complete": true }, { - "elapsed_seconds": 1.6700555950010312, + "elapsed_seconds": 1.6643717070001003, "phase": "download", "missing_pids": [], - "workload_pss_bytes": 31773696, + "workload_pss_bytes": 32746496, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 31773696, + "accounted_pss_bytes": 32746496, "complete": true }, { - "elapsed_seconds": 1.752809540997987, + "elapsed_seconds": 1.744672217999323, "phase": "download", "missing_pids": [], - "workload_pss_bytes": 31777792, + "workload_pss_bytes": 32746496, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 31777792, + "accounted_pss_bytes": 32746496, "complete": true }, { - "elapsed_seconds": 1.8338913269981276, + "elapsed_seconds": 1.8260370770003647, "phase": "download", "missing_pids": [], - "workload_pss_bytes": 31777792, + "workload_pss_bytes": 32746496, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 31777792, + "accounted_pss_bytes": 32746496, "complete": true }, { - "elapsed_seconds": 1.91650424099862, + "elapsed_seconds": 1.9077055029993062, "phase": "download", "missing_pids": [], - "workload_pss_bytes": 31777792, + "workload_pss_bytes": 32746496, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 31777792, + "accounted_pss_bytes": 32746496, "complete": true }, { - "elapsed_seconds": 1.9960613699986425, + "elapsed_seconds": 1.9883290180005133, "phase": "download", "missing_pids": [], - "workload_pss_bytes": 31777792, + "workload_pss_bytes": 32746496, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 31777792, + "accounted_pss_bytes": 32746496, "complete": true }, { - "elapsed_seconds": 2.074894839999615, + "elapsed_seconds": 2.0702041529984854, "phase": "download", "missing_pids": [], - "workload_pss_bytes": 31777792, + "workload_pss_bytes": 32746496, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 31777792, + "accounted_pss_bytes": 32746496, "complete": true }, { - "elapsed_seconds": 2.1458404479999444, + "elapsed_seconds": 2.1431606949990964, "phase": "download", "missing_pids": [], - "workload_pss_bytes": 36955136, + "workload_pss_bytes": 41550848, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 36955136, + "accounted_pss_bytes": 41550848, "complete": true }, { - "elapsed_seconds": 2.227262508000422, + "elapsed_seconds": 2.2211632289981935, "phase": "download", "missing_pids": [], - "workload_pss_bytes": 36955136, + "workload_pss_bytes": 37688320, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 36955136, + "accounted_pss_bytes": 37688320, "complete": true }, { - "elapsed_seconds": 2.284638929999346, + "elapsed_seconds": 2.3020287250001275, "phase": "download", "missing_pids": [], - "workload_pss_bytes": 35782656, + "workload_pss_bytes": 37688320, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 35782656, + "accounted_pss_bytes": 37688320, "complete": true }, { - "elapsed_seconds": 2.304537034000532, + "elapsed_seconds": 2.3316817359991546, "phase": "teardown", "missing_pids": [], - "workload_pss_bytes": 35782656, + "workload_pss_bytes": 36530176, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 35782656, + "accounted_pss_bytes": 36530176, "complete": true }, { - "elapsed_seconds": 2.384560872000293, + "elapsed_seconds": 2.4116204870006186, "phase": "teardown", "missing_pids": [], - "workload_pss_bytes": 35782656, + "workload_pss_bytes": 36530176, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 35782656, + "accounted_pss_bytes": 36530176, "complete": true }, { - "elapsed_seconds": 2.464561123000749, + "elapsed_seconds": 2.494116623998707, "phase": "teardown", "missing_pids": [], - "workload_pss_bytes": 35782656, + "workload_pss_bytes": 36530176, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 35782656, + "accounted_pss_bytes": 36530176, "complete": true }, { - "elapsed_seconds": 2.5440147490007803, + "elapsed_seconds": 2.5658641289992374, "phase": "teardown", "missing_pids": [], - "workload_pss_bytes": 35782656, + "workload_pss_bytes": 36530176, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 35782656, + "accounted_pss_bytes": 36530176, "complete": true }, { - "elapsed_seconds": 2.625217447999603, + "elapsed_seconds": 2.647526647000632, "phase": "teardown", "missing_pids": [], - "workload_pss_bytes": 35782656, + "workload_pss_bytes": 36530176, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 35782656, + "accounted_pss_bytes": 36530176, "complete": true }, { - "elapsed_seconds": 2.7036778529982257, + "elapsed_seconds": 2.7305998580013693, "phase": "teardown", "missing_pids": [], - "workload_pss_bytes": 35782656, + "workload_pss_bytes": 36530176, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 35782656, + "accounted_pss_bytes": 36530176, "complete": true }, { - "elapsed_seconds": 2.7262317659988184, + "elapsed_seconds": 2.7493143510000664, "phase": "teardown", "missing_pids": [ - 487276 + 2546424 ], "workload_pss_bytes": 0, "attached_stack_pss_bytes": 0, @@ -984,7 +1054,7 @@ "complete": false }, { - "elapsed_seconds": 2.7263362310004595, + "elapsed_seconds": 2.749410041000374, "phase": "exited", "missing_pids": [], "workload_pss_bytes": 0, @@ -998,26 +1068,44 @@ { "phase": "idle" }, + { + "phase": "idle", + "cpu_user_seconds": 3.500000000000725e-05, + "cpu_system_seconds": 3.999999999998796e-06, + "cpu_seconds": 3.9000000000006044e-05 + }, { "phase": "search" }, { "phase": "search", - "search_seconds": 0.857438140999875, - "result_count": 1200 + "search_seconds": 0.8700568870008283, + "result_count": 1200, + "cpu_user_seconds": 1.5160109999999998, + "cpu_system_seconds": 0.186613, + "cpu_seconds": 1.7026239999999997 }, { "phase": "download" }, { "phase": "download", - "download_seconds": 0.6978758050026954, + "download_seconds": 0.7379083729974809, "payload_bytes": 4194304, "sha256": "2b07811057df887086f06a67edc6ebf911de8b6741156e7a2eb1416a4b8b1b2e", - "libtorrent_version": "2.0.11.0" + "libtorrent_version": "2.0.11.0", + "cpu_user_seconds": 0.07276700000000003, + "cpu_system_seconds": 0.03925999999999999, + "cpu_seconds": 0.11202700000000002 }, { "phase": "teardown" + }, + { + "phase": "teardown", + "cpu_user_seconds": 0.005383000000000138, + "cpu_system_seconds": 0, + "cpu_seconds": 0.005383000000000138 } ], "summary": { @@ -1025,8 +1113,8 @@ "sample_count": 10, "incomplete_samples": 0, "workload_pss_bytes": { - "median": 31777792.0, - "peak": 36955136 + "median": 32746496.0, + "peak": 41550848 }, "attached_stack_pss_bytes": { "median": 0.0, @@ -1037,8 +1125,8 @@ "peak": 0 }, "accounted_pss_bytes": { - "median": 31777792.0, - "peak": 36955136 + "median": 32746496.0, + "peak": 41550848 } }, "exited": { @@ -1065,8 +1153,8 @@ "sample_count": 6, "incomplete_samples": 0, "workload_pss_bytes": { - "median": 21502976.0, - "peak": 21651456 + "median": 21900288.0, + "peak": 21900288 }, "attached_stack_pss_bytes": { "median": 0.0, @@ -1077,36 +1165,36 @@ "peak": 0 }, "accounted_pss_bytes": { - "median": 21502976.0, - "peak": 21651456 + "median": 21900288.0, + "peak": 21900288 } }, "search": { "sample_count": 15, - "incomplete_samples": 1, + "incomplete_samples": 0, "workload_pss_bytes": { - "median": 41576448.0, - "peak": 60341248 + "median": 41312256, + "peak": 61602816 }, "attached_stack_pss_bytes": { - "median": 0.0, + "median": 0, "peak": 0 }, "engine_pss_bytes": { - "median": 0.0, + "median": 0, "peak": 0 }, "accounted_pss_bytes": { - "median": 41576448.0, - "peak": 60341248 + "median": 41312256, + "peak": 61602816 } }, "startup": { "sample_count": 1, "incomplete_samples": 0, "workload_pss_bytes": { - "median": 15787008, - "peak": 15787008 + "median": 16095232, + "peak": 16095232 }, "attached_stack_pss_bytes": { "median": 0, @@ -1117,16 +1205,16 @@ "peak": 0 }, "accounted_pss_bytes": { - "median": 15787008, - "peak": 15787008 + "median": 16095232, + "peak": 16095232 } }, "teardown": { "sample_count": 7, "incomplete_samples": 1, "workload_pss_bytes": { - "median": 35782656.0, - "peak": 35782656 + "median": 36530176.0, + "peak": 36530176 }, "attached_stack_pss_bytes": { "median": 0.0, @@ -1137,8 +1225,8 @@ "peak": 0 }, "accounted_pss_bytes": { - "median": 35782656.0, - "peak": 35782656 + "median": 36530176.0, + "peak": 36530176 } } } @@ -1146,400 +1234,410 @@ { "samples": [ { - "elapsed_seconds": 0.07096441300018341, + "elapsed_seconds": 0.08048478999990039, "phase": "startup", "missing_pids": [], - "workload_pss_bytes": 15865856, + "workload_pss_bytes": 16281600, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 15865856, + "accounted_pss_bytes": 16281600, "complete": true }, { - "elapsed_seconds": 0.12601515500136884, + "elapsed_seconds": 0.15833229000054416, "phase": "idle", "missing_pids": [], - "workload_pss_bytes": 21513216, + "workload_pss_bytes": 21903360, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 21513216, + "accounted_pss_bytes": 21903360, "complete": true }, { - "elapsed_seconds": 0.20390585200220812, + "elapsed_seconds": 0.23017029599941452, "phase": "idle", "missing_pids": [], - "workload_pss_bytes": 21513216, + "workload_pss_bytes": 21903360, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 21513216, + "accounted_pss_bytes": 21903360, "complete": true }, { - "elapsed_seconds": 0.281711757001176, + "elapsed_seconds": 0.30229452599814977, "phase": "idle", "missing_pids": [], - "workload_pss_bytes": 21513216, + "workload_pss_bytes": 21903360, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 21513216, + "accounted_pss_bytes": 21903360, "complete": true }, { - "elapsed_seconds": 0.3600638220013934, + "elapsed_seconds": 0.3736442179979349, "phase": "idle", "missing_pids": [], - "workload_pss_bytes": 21513216, + "workload_pss_bytes": 21903360, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 21513216, + "accounted_pss_bytes": 21903360, "complete": true }, { - "elapsed_seconds": 0.4399710670004424, + "elapsed_seconds": 0.4548816099995747, "phase": "idle", "missing_pids": [], - "workload_pss_bytes": 21513216, + "workload_pss_bytes": 21903360, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 21513216, + "accounted_pss_bytes": 21903360, "complete": true }, { - "elapsed_seconds": 0.5165593929996248, + "elapsed_seconds": 0.5256298809981672, "phase": "idle", "missing_pids": [], - "workload_pss_bytes": 21657600, + "workload_pss_bytes": 21903360, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 21657600, + "accounted_pss_bytes": 21903360, "complete": true }, { - "elapsed_seconds": 0.537156127000344, + "elapsed_seconds": 0.550391568998748, "phase": "search", "missing_pids": [], - "workload_pss_bytes": 36843520, + "workload_pss_bytes": 22051840, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 36843520, + "accounted_pss_bytes": 22051840, "complete": true }, { - "elapsed_seconds": 0.6097267559998727, + "elapsed_seconds": 0.6248013100012031, "phase": "search", "missing_pids": [], - "workload_pss_bytes": 59238400, + "workload_pss_bytes": 56637440, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 59238400, + "accounted_pss_bytes": 56637440, "complete": true }, { - "elapsed_seconds": 0.6800862900017819, + "elapsed_seconds": 0.6989637660008157, "phase": "search", "missing_pids": [], - "workload_pss_bytes": 37471232, + "workload_pss_bytes": 30426112, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 37471232, + "accounted_pss_bytes": 30426112, "complete": true }, { - "elapsed_seconds": 0.7509184129994537, + "elapsed_seconds": 0.780428447000304, "phase": "search", "missing_pids": [], - "workload_pss_bytes": 60387328, + "workload_pss_bytes": 60181504, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 60387328, + "accounted_pss_bytes": 60181504, "complete": true }, { - "elapsed_seconds": 0.8214912969997386, + "elapsed_seconds": 0.8620718710008077, "phase": "search", "missing_pids": [], - "workload_pss_bytes": 38025216, + "workload_pss_bytes": 40770560, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 38025216, + "accounted_pss_bytes": 40770560, "complete": true }, { - "elapsed_seconds": 0.8937390210012381, + "elapsed_seconds": 0.9370325230011076, "phase": "search", "missing_pids": [], - "workload_pss_bytes": 60463104, + "workload_pss_bytes": 62448640, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 60463104, + "accounted_pss_bytes": 62448640, "complete": true }, { - "elapsed_seconds": 0.9684438229996886, + "elapsed_seconds": 1.0108282449982653, "phase": "search", "missing_pids": [], - "workload_pss_bytes": 39627776, + "workload_pss_bytes": 45357056, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 39627776, + "accounted_pss_bytes": 45357056, "complete": true }, { - "elapsed_seconds": 1.0406096680017072, + "elapsed_seconds": 1.1058457529979933, "phase": "search", "missing_pids": [], - "workload_pss_bytes": 61414400, + "workload_pss_bytes": 62543872, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 61414400, + "accounted_pss_bytes": 62543872, "complete": true }, { - "elapsed_seconds": 1.116629455002112, + "elapsed_seconds": 1.2034999030001927, "phase": "search", "missing_pids": [], - "workload_pss_bytes": 40635392, + "workload_pss_bytes": 50618368, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 40635392, + "accounted_pss_bytes": 50618368, "complete": true }, { - "elapsed_seconds": 1.1883584720017097, + "elapsed_seconds": 1.3047492900004727, "phase": "search", "missing_pids": [], - "workload_pss_bytes": 61379584, + "workload_pss_bytes": 62587904, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 61379584, + "accounted_pss_bytes": 62587904, "complete": true }, { - "elapsed_seconds": 1.2591324230015744, + "elapsed_seconds": 1.383777476999967, "phase": "search", "missing_pids": [], - "workload_pss_bytes": 39651328, + "workload_pss_bytes": 40495104, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 39651328, + "accounted_pss_bytes": 40495104, "complete": true }, { - "elapsed_seconds": 1.3320004100023652, + "elapsed_seconds": 1.4636361150005541, "phase": "search", "missing_pids": [], - "workload_pss_bytes": 60781568, + "workload_pss_bytes": 59644928, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 60781568, + "accounted_pss_bytes": 59644928, "complete": true }, { - "elapsed_seconds": 1.3883087400026852, + "elapsed_seconds": 1.5416388759986148, "phase": "search", "missing_pids": [], - "workload_pss_bytes": 22449152, + "workload_pss_bytes": 23101440, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 22449152, + "accounted_pss_bytes": 23101440, "complete": true }, { - "elapsed_seconds": 1.4665419110024231, + "elapsed_seconds": 1.5710890629998175, "phase": "search", "missing_pids": [], - "workload_pss_bytes": 22449152, + "workload_pss_bytes": 23101440, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 22449152, + "accounted_pss_bytes": 23101440, "complete": true }, { - "elapsed_seconds": 1.5471739000022353, + "elapsed_seconds": 1.6566171390004456, "phase": "search", "missing_pids": [], - "workload_pss_bytes": 22449152, + "workload_pss_bytes": 23101440, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 22449152, + "accounted_pss_bytes": 23101440, "complete": true }, { - "elapsed_seconds": 1.594360418002907, - "phase": "download", + "elapsed_seconds": 1.7274749710013566, + "phase": "search", "missing_pids": [], - "workload_pss_bytes": 30651392, + "workload_pss_bytes": 23101440, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 30651392, + "accounted_pss_bytes": 23101440, "complete": true }, { - "elapsed_seconds": 1.6751941920010722, + "elapsed_seconds": 1.751173426000605, "phase": "download", "missing_pids": [], - "workload_pss_bytes": 31759360, + "workload_pss_bytes": 32734208, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 31759360, + "accounted_pss_bytes": 32734208, "complete": true }, { - "elapsed_seconds": 1.755599036001513, + "elapsed_seconds": 1.8337478670000564, "phase": "download", "missing_pids": [], - "workload_pss_bytes": 31763456, + "workload_pss_bytes": 32734208, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 31763456, + "accounted_pss_bytes": 32734208, "complete": true }, { - "elapsed_seconds": 1.8347107610024977, + "elapsed_seconds": 1.906879153000773, "phase": "download", "missing_pids": [], - "workload_pss_bytes": 31763456, + "workload_pss_bytes": 32734208, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 31763456, + "accounted_pss_bytes": 32734208, "complete": true }, { - "elapsed_seconds": 1.915186303001974, + "elapsed_seconds": 1.9830756849987665, "phase": "download", "missing_pids": [], - "workload_pss_bytes": 31763456, + "workload_pss_bytes": 32734208, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 31763456, + "accounted_pss_bytes": 32734208, "complete": true }, { - "elapsed_seconds": 1.9958517410013883, + "elapsed_seconds": 2.054373062997911, "phase": "download", "missing_pids": [], - "workload_pss_bytes": 31763456, + "workload_pss_bytes": 32734208, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 31763456, + "accounted_pss_bytes": 32734208, "complete": true }, { - "elapsed_seconds": 2.0769097369993688, + "elapsed_seconds": 2.1281596529988747, "phase": "download", "missing_pids": [], - "workload_pss_bytes": 31763456, + "workload_pss_bytes": 32734208, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 31763456, + "accounted_pss_bytes": 32734208, "complete": true }, { - "elapsed_seconds": 2.1468129420027253, + "elapsed_seconds": 2.2021198750007898, "phase": "download", "missing_pids": [], - "workload_pss_bytes": 40639488, + "workload_pss_bytes": 32734208, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 40639488, + "accounted_pss_bytes": 32734208, "complete": true }, { - "elapsed_seconds": 2.2173203420024947, + "elapsed_seconds": 2.2789660609996645, "phase": "download", "missing_pids": [], - "workload_pss_bytes": 36772864, + "workload_pss_bytes": 42223616, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 36772864, + "accounted_pss_bytes": 42223616, "complete": true }, { - "elapsed_seconds": 2.295689038001001, + "elapsed_seconds": 2.3520874620007817, "phase": "download", "missing_pids": [], - "workload_pss_bytes": 36772864, + "workload_pss_bytes": 38373376, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 36772864, + "accounted_pss_bytes": 38373376, "complete": true }, { - "elapsed_seconds": 2.332615777999308, + "elapsed_seconds": 2.424759041998186, "phase": "download", "missing_pids": [], - "workload_pss_bytes": 35615744, + "workload_pss_bytes": 38373376, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 35615744, + "accounted_pss_bytes": 38373376, "complete": true }, { - "elapsed_seconds": 2.350792301000183, + "elapsed_seconds": 2.4863717279986304, "phase": "teardown", "missing_pids": [], - "workload_pss_bytes": 35615744, + "workload_pss_bytes": 37197824, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 35615744, + "accounted_pss_bytes": 37197824, "complete": true }, { - "elapsed_seconds": 2.429585579000559, + "elapsed_seconds": 2.5576605290007137, "phase": "teardown", "missing_pids": [], - "workload_pss_bytes": 35615744, + "workload_pss_bytes": 37197824, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 35615744, + "accounted_pss_bytes": 37197824, "complete": true }, { - "elapsed_seconds": 2.5002585100010037, + "elapsed_seconds": 2.629062954998517, "phase": "teardown", "missing_pids": [], - "workload_pss_bytes": 35615744, + "workload_pss_bytes": 37197824, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 35615744, + "accounted_pss_bytes": 37197824, "complete": true }, { - "elapsed_seconds": 2.5742764380011067, + "elapsed_seconds": 2.699458106999373, "phase": "teardown", "missing_pids": [], - "workload_pss_bytes": 35615744, + "workload_pss_bytes": 37197824, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 35615744, + "accounted_pss_bytes": 37197824, "complete": true }, { - "elapsed_seconds": 2.643604483000672, + "elapsed_seconds": 2.770206532000884, "phase": "teardown", "missing_pids": [], - "workload_pss_bytes": 35615744, + "workload_pss_bytes": 37197824, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 35615744, + "accounted_pss_bytes": 37197824, "complete": true }, { - "elapsed_seconds": 2.712455823999335, + "elapsed_seconds": 2.841151925000304, "phase": "teardown", "missing_pids": [], - "workload_pss_bytes": 35615744, + "workload_pss_bytes": 37197824, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 35615744, + "accounted_pss_bytes": 37197824, "complete": true }, { - "elapsed_seconds": 2.7651638070019544, + "elapsed_seconds": 2.8960228219984856, + "phase": "teardown", + "missing_pids": [], + "workload_pss_bytes": 37202944, + "attached_stack_pss_bytes": 0, + "engine_pss_bytes": 0, + "accounted_pss_bytes": 37202944, + "complete": true + }, + { + "elapsed_seconds": 2.9215083300005062, "phase": "teardown", "missing_pids": [ - 487330 + 2546684 ], "workload_pss_bytes": 0, "attached_stack_pss_bytes": 0, @@ -1548,7 +1646,7 @@ "complete": false }, { - "elapsed_seconds": 2.7652855010019266, + "elapsed_seconds": 2.9215990570010035, "phase": "exited", "missing_pids": [], "workload_pss_bytes": 0, @@ -1562,47 +1660,65 @@ { "phase": "idle" }, + { + "phase": "idle", + "cpu_user_seconds": 3.799999999999637e-05, + "cpu_system_seconds": 6.999999999996592e-06, + "cpu_seconds": 4.499999999999296e-05 + }, { "phase": "search" }, { "phase": "search", - "search_seconds": 0.8636252059986873, - "result_count": 1200 + "search_seconds": 0.9995746150016203, + "result_count": 1200, + "cpu_user_seconds": 1.744186, + "cpu_system_seconds": 0.20401599999999998, + "cpu_seconds": 1.948202 }, { "phase": "download" }, { "phase": "download", - "download_seconds": 0.7427955219973228, + "download_seconds": 0.7365457490013796, "payload_bytes": 4194304, "sha256": "2b07811057df887086f06a67edc6ebf911de8b6741156e7a2eb1416a4b8b1b2e", - "libtorrent_version": "2.0.11.0" + "libtorrent_version": "2.0.11.0", + "cpu_user_seconds": 0.03841300000000003, + "cpu_system_seconds": 0.03295200000000001, + "cpu_seconds": 0.07136500000000004 }, { "phase": "teardown" + }, + { + "phase": "teardown", + "cpu_user_seconds": 0.005549999999999944, + "cpu_system_seconds": 0, + "cpu_seconds": 0.005549999999999944 } ], "summary": { "download": { - "sample_count": 11, + "sample_count": 10, "incomplete_samples": 0, "workload_pss_bytes": { - "median": 31763456, - "peak": 40639488 + "median": 32734208.0, + "peak": 42223616 }, "attached_stack_pss_bytes": { - "median": 0, + "median": 0.0, "peak": 0 }, "engine_pss_bytes": { - "median": 0, + "median": 0.0, "peak": 0 }, "accounted_pss_bytes": { - "median": 31763456, - "peak": 40639488 + "median": 32734208.0, + "peak": 42223616 } }, "exited": { @@ -1629,8 +1745,8 @@ "sample_count": 6, "incomplete_samples": 0, "workload_pss_bytes": { - "median": 21513216.0, - "peak": 21657600 + "median": 21903360.0, + "peak": 21903360 }, "attached_stack_pss_bytes": { "median": 0.0, @@ -1641,36 +1757,36 @@ "peak": 0 }, "accounted_pss_bytes": { - "median": 21513216.0, - "peak": 21657600 + "median": 21903360.0, + "peak": 21903360 } }, "search": { - "sample_count": 15, + "sample_count": 16, "incomplete_samples": 0, "workload_pss_bytes": { - "median": 39651328, - "peak": 61414400 + "median": 43063808.0, + "peak": 62587904 }, "attached_stack_pss_bytes": { - "median": 0, + "median": 0.0, "peak": 0 }, "engine_pss_bytes": { - "median": 0, + "median": 0.0, "peak": 0 }, "accounted_pss_bytes": { - "median": 39651328, - "peak": 61414400 + "median": 43063808.0, + "peak": 62587904 } }, "startup": { "sample_count": 1, "incomplete_samples": 0, "workload_pss_bytes": { - "median": 15865856, - "peak": 15865856 + "median": 16281600, + "peak": 16281600 }, "attached_stack_pss_bytes": { "median": 0, @@ -1681,28 +1797,28 @@ "peak": 0 }, "accounted_pss_bytes": { - "median": 15865856, - "peak": 15865856 + "median": 16281600, + "peak": 16281600 } }, "teardown": { - "sample_count": 7, + "sample_count": 8, "incomplete_samples": 1, "workload_pss_bytes": { - "median": 35615744.0, - "peak": 35615744 + "median": 37197824, + "peak": 37202944 }, "attached_stack_pss_bytes": { - "median": 0.0, + "median": 0, "peak": 0 }, "engine_pss_bytes": { - "median": 0.0, + "median": 0, "peak": 0 }, "accounted_pss_bytes": { - "median": 35615744.0, - "peak": 35615744 + "median": 37197824, + "peak": 37202944 } } } diff --git a/docs/benchmarks/local-loopback.json b/docs/benchmarks/local-loopback.json index 951c146..b13785c 100644 --- a/docs/benchmarks/local-loopback.json +++ b/docs/benchmarks/local-loopback.json @@ -3,50 +3,84 @@ "mode": "local_fixture_search_and_loopback_bittorrent", "metric": "PSS bytes; same metric for every component", "environment": { - "platform": "Linux-7.2.11-200.fc44.x86_64-x86_64-with-glibc2.43", + "platform": "Linux-7.2.13-200.fc44.x86_64-x86_64-with-glibc2.43", "python": "3.14.8 (main, Oct 1 2026, 00:00:00) [GCC 16.2.1 20260819 (Red Hat 16.2.1-2)]", "cpu_count": 8, "cpu_model": "11th Gen Intel(R) Core(TM) i5-1135G7 @ 2.40GHz", "source_sha256": { "__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "cli.py": "1d826809006ec312575cc34d3e0876b50cfae043121e83a61bbb4d6446d475d9", - "core/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "core/benchmark.py": "d3b790f5f5f3e56bac21f60c64b8a245bfaed2c9387d2f9ae142f02dd4c51518", - "core/config_manager.py": "6f71069e1544145b5ab2c324326df1f7d75250ec4bba4d5361e60c8251e5686c", - "core/config_wizard.py": "d3303501145dad0e49dd19c6e6153c19a039b0e479a14f72ead24ededfb8f6c0", - "core/http.py": "3d36d9d66e954610b0b8e925251af38959d1c7e606ebdcdbfd5501ba03c6f344", - "core/indexer_manager.py": "1435e21114ff5de6da67e084a13103b8cd25bbe91367f118d75fb5c95c130472", - "core/init_env.py": "f8eab6975fc5c7ce2b6b86658eeb7eb3feb36bd70d95f0204cd285c5ae7f330c", - "core/lite_downloader.py": "064f39174a24d6113c1cfd56f064e247ed40642ae3d080640b4f35f565c6dc63", - "core/lite_fetcher.py": "dd7505d13c6107347ec962c7e1868b79112992800b8873d47691cfdb8dbe2e36", - "core/lite_plugin_loader.py": "419dea428158a28314a7a192cabd88e54b078d8542258db243bbad2c2f141b0d", - "core/logger.py": "fba54c1264da77f2faf8fa5b6fc3df66fecd5e01d6f8be52fdd4edca202106bf", - "core/oneshot.py": "e1ac659d8e95f39c11da837d3bc6cd101a8949a7c41cfe2b322c6f6b963dac8e", - "core/qbittorrent_client.py": "7a412585b4f0b056a43b4040cba95b00e12ba0de0ae395d91590aa0bb3a36276", - "core/rss_fetcher.py": "9b3f508ab7add45b99bba9526679ae21063d75fa04728eb97ba7a8cf82e426a7", - "core/search_runner.py": "782a28401bafd86e9e38b77afd8f50cd241c2f0d2f9f30371e08f3b2efcb96fd", - "core/secret_manager.py": "2d9a15ad2483fe3976c05dccc76f9814f6df0dbeb2e9cd943f47c85f17ec02ee", - "core/torrent_filter.py": "662daedbbafbb4197ac8e9aec68b033001f9317b8745aa92741d52e7da9934a0", + "benchmarks/__init__.py": "fc3ac8c8a6223d39b3624cdf421f4c0efa03791c4653691523a7c782588f631b", + "benchmarks/benchmark.py": "e49e85ba2fe5ec6384d8b62f38a658ead6c0521056d3ccb1f1237144bf22d11b", + "benchmarks/device_profile.py": "aa3cfeefba70f5f84eb43098f29c093e1cc4d5f07647af99218d177b3cc4820e", + "benchmarks/stack_benchmark.py": "fe2ec4cbf2499bd8301b4b002b64b838bf63db3fd69d28450dd73b3941c58019", + "cli/__init__.py": "2c240c4b6d2187f87323f2aadefb6caa9d9b29ae6580782e70f696ab2e8628dc", + "cli/__main__.py": "7d865e3f883b9a0fbecc11f6199aa359edcba74fe013ecd1f7d3656e482a4d0f", + "cli/app.py": "4dbfa3c53c32b7d067e64bd10e57d69ac6e17df5a14f0ec00ded77ea7e10b8ab", + "cli/commands/__init__.py": "8f60f64f201bed74d3881f0ee25e73408230a4c95d26b74363130cf7f5c7424c", + "cli/commands/background.py": "1d3345b8b7e04173e2bb89cfee6b00b8f0fa9c9fcebcacc9b1dc62a0493c24bd", + "cli/commands/banner.py": "1fc7225d888c2576670e614eb40260bb705898a30a2d3fca8239d81cc956c5e6", + "cli/commands/headless.py": "18808e7a9c5e6e7ccc0b8f5739469880c89168c2daba2917501b3fb0fe61de8d", + "cli/commands/indexers.py": "977caeb59da571a933ccae2905dc0ec64be01167d76676a4e2d55fd1455a9e94", + "cli/commands/session.py": "716c8a2f1bdb29dd229de9742eb2b261bc78e71626c03c6103241150fdbb455b", + "cli/commands/status.py": "edace4681910fdea8e3f1299197727d873d0274803ff0ec7212d14983c568f03", + "cli/commands/utility.py": "4d6ad72918b541fe2be60f8c588518c6080ae2ac85dad1e0108d80846223405c", + "cli/deps.py": "9ff2fb551f5f2c5fd3b2c2f49fa86741501ffc75a9d6de05cfcc68b65c91e6b6", + "cli/parser.py": "b8e9ec20ca30c48ea0770cae343e880f01203a60aa3bdc26c39176eb7133cae7", + "config/__init__.py": "3f1f275db788286c6c3ba3cb4b9ac9a57e30de2e91a84de5e70dd390ae801761", + "config/config_commands.py": "2699a907ec9d2edeb6960822043a2562c3d1bb8e4b66678bed5f4f49c571ab1b", + "config/config_manager.py": "17dab7f0234bde9202684600789f85b07e1f6bd5dcfc269293b732cda25f6b36", + "config/config_wizard.py": "fc67b530bf0701c9ac1b5be5475cdda2c9a4e002d9eee4d43ae22d875d8c24d1", + "config/secret_manager.py": "986f85bb888587808060817b485eca679ae3d6923c9286d1bda54b9710db30e3", + "config/settings.py": "3e6623c612d715c46e00f8e670726a22cdf3cd9bebc6ffad074a01575252bd66", + "core/__init__.py": "3708ab27751586375c25366dcd398e9f42ccffa63c6b488be960b29edf21f85e", + "core/http.py": "b6428bb3cb9f172d1a5dee1327dfcc58b5d419840f8fb47ac2f1f94cfe733b8d", + "core/logger.py": "bc333a1dda9fd9fd083df15803f6f3205ebc306758f6105c2414fab007255cfd", + "core/rss_fetcher.py": "64e843e22c6e78d3313f93ae56faa0beb26d91fbe6ebbbb7f2adcdedef0e8058", + "logger.py": "8c855cf485a29b2a9eb58f5b49c22d5d647e3df6c5efb96bcbc16db308db8c7a", + "net/__init__.py": "87f121e104cc83ae03d5b6a7e3aec85ba8966ea8ad747ccf9aeb13f616759fc8", + "net/http.py": "3d36d9d66e954610b0b8e925251af38959d1c7e606ebdcdbfd5501ba03c6f344", "plugins/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "plugins/bitsearch.py": "4a648f04b729a6556036ca5ee830c3db4a85b492a9d6e9524e7c38864a062a4f", - "plugins/bittorrented.py": "1077d397916be8c83471db61a2733426417119109bf53694bd2dd22b34fe9873", - "plugins/eztv.py": "8576d0f09636ef1da55024fcdab7212f4c9627d339fbc6657fce573823e6e6b0", - "plugins/helpers.py": "9af508d98875f399e98ee60428153cec41140b41a0bc8c2da23ca743a4e81556", + "plugins/bittorrented.py": "ae36b2665c46758cd4e91c2e5f016de1fcaadbf11042f4340cac110cf2c70e8c", + "plugins/eztv.py": "6e0c211102acbecc3fc7f2f556ac56c3c0d12113df1dd21bf4f0600c85551df9", + "plugins/helpers.py": "30d7ca263bee97bf68010dd1e0adc75cdd157f8a19903f11089b6faa0decd628", "plugins/limetorrents.py": "60f8f6321664108875accd2585a8d51e4fbf5fb5c88d63d3ec8733a6ad1aa68a", - "plugins/novaprinter.py": "a3193175bd64d9517d368ff4ba70d2c56d85011d18d8f196c82ff308e8cc685e", + "plugins/novaprinter.py": "5f083f8675cc22b194f0d8dd29d5c32d3bc63f7d4c4916be0e7af8bf22e286b3", "plugins/piratebay.py": "21f760eac8d931ac25dc05a79654f14313a30d48d81f878e857a25f4e226bc3f", - "plugins/subsplease.py": "4117d2cd8f58e9ace19c5d9287f1b2307fab0d32a6fc15898f3e6ef75c37f402", + "plugins/subsplease.py": "565e41b0cfd61918f4a62312196b3d878608720a943bab1e97141f6d3b19bea9", "plugins/torlock.py": "2d818ddda16c4e150878be63c0b0ff03f2e746bef73e8a86e38758366d235071", - "plugins/torrentproject.py": "1f8c5be60357f1d4baf4ba2722aa316e5bdd50324209f8b22aa902a6abad4c86", - "plugins/x1337.py": "29dbdd5c57b95e7750b20b5bd8cfdb324dc6e3db8cde5e9005e4f5295157b581", - "plugins/yts.py": "fdd2e0236aacf0e43cdf2a43abd16ee33fdb5f736de84ed357afb54a9c1df0fe", + "plugins/torrentproject.py": "0918e7ddd6369b76ba3dc9c007e79253ccde365d1b0716519cdbcf901432135c", + "plugins/x1337.py": "9945129ed2213e01d6f7f3fa607af02d131ac2da348b098b8ed3180b2fa338ca", + "plugins/yts.py": "3bf5fdd085d562023a51ba267a4ea43904bf93a9eca940aaa56594b89ee583aa", + "search/__init__.py": "77507206d32e57cd8de4ae48a889bd2399bd92691cb388d3bb702e0e3f67ce31", + "search/indexer_manager.py": "e2e2d780c3d4297ea6057244659cf1ee024b1b4168bcc56ffb1b63aefeac760d", + "search/lite_fetcher.py": "63dd593e8c6f58f4acd455b9638cb7e0c5e6f822b2f87670d6a6428cb6ec712c", + "search/lite_plugin_loader.py": "fea7e6f2049d62fdc8f3877eb26891bb6e78013c674c5ccaf6a24365c17fed35", + "search/rss_fetcher.py": "31d956e480537be4d5a2bc9a7db18da3eb0cc995a9dc27c8797708f9a39ffce6", + "search/search_runner.py": "9b10be4eb732ab3bf8763544512bdfabd99e102a967c4d21b418d2dbe74c4545", + "search/torrent_filter.py": "662daedbbafbb4197ac8e9aec68b033001f9317b8745aa92741d52e7da9934a0", + "services/__init__.py": "828c2c304f29d93f54a785175864752dd285e6585f0898d955764f371a798195", + "services/jobs.py": "c1b1c7489d10983f40544c10d379cb2d4414ce9750e238a737f00ece27d79af3", + "services/runtime.py": "2450c86d0c565222897d5d8aa2d6daef247fc10090e271078a9567ae3197cfc1", + "services/server.py": "a428ea6dd55dddb535313b2eb34815a92f00f92c1f8c78235728daea0ce9363e", + "services/watch.py": "e09c4e6102d7ad7aac38372cdf2d5d1e52a80cc5b8bf5142d4ec73f9cf803692", + "stack/__init__.py": "71f4313c5d8fa5faa2d75a7fdc743cf37b0260e4aa11e2755e5827ced6d975cf", + "stack/compose.py": "40a37373e83a63c4cf08ad8a7c740f065c6fc5a816ad6dd6435a6c7b1c7f5470", + "stack/oneshot.py": "211bda37474b3eb3f8c87c445d90ee6aba2cbcf5f3c7ac2e36002726b6390adc", + "stack/stack_setup.py": "b979c41a80bba3f1466f3c9330aebe63a7eb2147d332988b87f0ad07c07a06f7", + "torrents/__init__.py": "b15760d6997bbd9cc7cb8662f11d37355afdc68472a8f5429522806bee486ad8", + "torrents/lite_downloader.py": "8ce068844f3838b9ee5286be59a64768b69ffaaf7e4d4cc5a2a33adc9a4c93d5", + "torrents/qbittorrent_client.py": "4022444861679a2174c0b48370ffe193cd7f6d73de4c40d31e4aed55c0f632a5", + "torrents/torrent_links.py": "30c93436ce89489c803a26c632c957ec657d4b7cd1308a32f75bfe08d73ab7d1", "ui/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "ui/colors.py": "192984be5f757359e15eb93ce1cd71083d257538199d8567dd5d9501a7481f37", - "ui/tui.py": "06a59767dfdbfc55876866e2e18d471430e56055ca232a8fc7360a893ef2ee2e" + "ui/ansi.py": "66803be9c479200396ef5bfe183e5dce8ef95cc69076118a290ceab7eedfacc7", + "ui/banner.py": "083560dedbc23b9fb80c2c9348ed72b44c041880fbc4b1037fb4c6f9fbf2ab39", + "ui/theme.py": "9054413e71db83598200f022122e138569183eb17f7e2c8669868da7cb3cc540", + "ui/tui.py": "42227141d9efae94710a3a1e98663602c9f6e0f7b72b855b779637456ca7b1f7" }, "cgroup_version": 2, - "revision": "f61d816128b4c98ee012fb9981e441852b758f2d", - "dirty": true + "revision": "a232b57897605468d4ed4a2cb589825757bfa1ea", + "dirty": false }, "interval_seconds": 0.05, "payload_bytes": 4194304, @@ -66,332 +100,322 @@ { "samples": [ { - "elapsed_seconds": 0.07038233800267335, - "phase": "idle", + "elapsed_seconds": 0.08078916600061348, + "phase": "startup", "missing_pids": [], - "workload_pss_bytes": 21508096, + "workload_pss_bytes": 21914624, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 21508096, + "accounted_pss_bytes": 21914624, "complete": true }, { - "elapsed_seconds": 0.14778174499952001, + "elapsed_seconds": 0.10049756100124796, "phase": "idle", "missing_pids": [], - "workload_pss_bytes": 21508096, + "workload_pss_bytes": 21914624, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 21508096, + "accounted_pss_bytes": 21914624, "complete": true }, { - "elapsed_seconds": 0.2286627169996791, + "elapsed_seconds": 0.1808924040014972, "phase": "idle", "missing_pids": [], - "workload_pss_bytes": 21508096, + "workload_pss_bytes": 21914624, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 21508096, + "accounted_pss_bytes": 21914624, "complete": true }, { - "elapsed_seconds": 0.3003016780021426, + "elapsed_seconds": 0.2620562369993422, "phase": "idle", "missing_pids": [], - "workload_pss_bytes": 21508096, + "workload_pss_bytes": 21914624, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 21508096, + "accounted_pss_bytes": 21914624, "complete": true }, { - "elapsed_seconds": 0.37721200099986163, + "elapsed_seconds": 0.3424455560016213, "phase": "idle", "missing_pids": [], - "workload_pss_bytes": 21508096, + "workload_pss_bytes": 21914624, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 21508096, + "accounted_pss_bytes": 21914624, "complete": true }, { - "elapsed_seconds": 0.4655202920002921, + "elapsed_seconds": 0.4240162890018837, "phase": "idle", "missing_pids": [], - "workload_pss_bytes": 21920768, + "workload_pss_bytes": 21914624, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 21920768, + "accounted_pss_bytes": 21914624, "complete": true }, { - "elapsed_seconds": 0.5093156809998618, + "elapsed_seconds": 0.49777017700034776, "phase": "search", "missing_pids": [], - "workload_pss_bytes": 73128960, + "workload_pss_bytes": 22300672, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 73128960, + "accounted_pss_bytes": 22300672, "complete": true }, { - "elapsed_seconds": 0.6065068900024926, + "elapsed_seconds": 0.593112074999226, "phase": "search", "missing_pids": [], - "workload_pss_bytes": 130493440, + "workload_pss_bytes": 119952384, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 130493440, + "accounted_pss_bytes": 119952384, "complete": true }, { - "elapsed_seconds": 0.7007851300004404, + "elapsed_seconds": 0.6891306460020132, "phase": "search", "missing_pids": [ - 486800 + 2544878 ], - "workload_pss_bytes": 70177792, + "workload_pss_bytes": 70057984, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 70177792, + "accounted_pss_bytes": 70057984, "complete": false }, { - "elapsed_seconds": 0.8104036229997291, + "elapsed_seconds": 0.7833868910020101, "phase": "search", "missing_pids": [], - "workload_pss_bytes": 97222656, + "workload_pss_bytes": 106416128, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 97222656, + "accounted_pss_bytes": 106416128, "complete": true }, { - "elapsed_seconds": 0.9141798080017907, + "elapsed_seconds": 0.8591635890006728, "phase": "search", "missing_pids": [], - "workload_pss_bytes": 120409088, + "workload_pss_bytes": 97166336, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 120409088, + "accounted_pss_bytes": 97166336, "complete": true }, { - "elapsed_seconds": 0.9873015400007716, + "elapsed_seconds": 0.9295211850003398, "phase": "search", "missing_pids": [], - "workload_pss_bytes": 23085056, + "workload_pss_bytes": 24077312, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 23085056, + "accounted_pss_bytes": 24077312, "complete": true }, { - "elapsed_seconds": 1.0085570660012309, + "elapsed_seconds": 0.9521953709991067, "phase": "search", "missing_pids": [], - "workload_pss_bytes": 23085056, + "workload_pss_bytes": 24077312, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 23085056, + "accounted_pss_bytes": 24077312, "complete": true }, { - "elapsed_seconds": 1.098545720000402, + "elapsed_seconds": 1.0354620079997403, "phase": "search", "missing_pids": [], - "workload_pss_bytes": 23085056, + "workload_pss_bytes": 24077312, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 23085056, + "accounted_pss_bytes": 24077312, "complete": true }, { - "elapsed_seconds": 1.1699812070000917, + "elapsed_seconds": 1.1138390820015047, "phase": "search", "missing_pids": [], - "workload_pss_bytes": 23085056, - "attached_stack_pss_bytes": 0, - "engine_pss_bytes": 0, - "accounted_pss_bytes": 23085056, - "complete": true - }, - { - "elapsed_seconds": 1.1900661630024842, - "phase": "download", - "missing_pids": [], - "workload_pss_bytes": 31170560, + "workload_pss_bytes": 24077312, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 31170560, + "accounted_pss_bytes": 24077312, "complete": true }, { - "elapsed_seconds": 1.2686971770017408, + "elapsed_seconds": 1.146119732002262, "phase": "download", "missing_pids": [], - "workload_pss_bytes": 32350208, + "workload_pss_bytes": 32964608, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 32350208, + "accounted_pss_bytes": 32964608, "complete": true }, { - "elapsed_seconds": 1.3493952540011378, + "elapsed_seconds": 1.2269408760002989, "phase": "download", "missing_pids": [], - "workload_pss_bytes": 32350208, + "workload_pss_bytes": 33558528, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 32350208, + "accounted_pss_bytes": 33558528, "complete": true }, { - "elapsed_seconds": 1.4320330030022888, + "elapsed_seconds": 1.2994008099994971, "phase": "download", "missing_pids": [], - "workload_pss_bytes": 32350208, + "workload_pss_bytes": 33558528, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 32350208, + "accounted_pss_bytes": 33558528, "complete": true }, { - "elapsed_seconds": 1.5117791539996688, + "elapsed_seconds": 1.37211633699917, "phase": "download", "missing_pids": [], - "workload_pss_bytes": 32350208, + "workload_pss_bytes": 33558528, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 32350208, + "accounted_pss_bytes": 33558528, "complete": true }, { - "elapsed_seconds": 1.590676130999782, + "elapsed_seconds": 1.4436948290021974, "phase": "download", "missing_pids": [], - "workload_pss_bytes": 32350208, + "workload_pss_bytes": 33558528, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 32350208, + "accounted_pss_bytes": 33558528, "complete": true }, { - "elapsed_seconds": 1.6699442130011448, + "elapsed_seconds": 1.5281340120018285, "phase": "download", "missing_pids": [], - "workload_pss_bytes": 32350208, + "workload_pss_bytes": 33558528, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 32350208, + "accounted_pss_bytes": 33558528, "complete": true }, { - "elapsed_seconds": 1.7409703260018432, + "elapsed_seconds": 1.6126453520009818, "phase": "download", "missing_pids": [], - "workload_pss_bytes": 41086976, + "workload_pss_bytes": 33558528, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 41086976, + "accounted_pss_bytes": 33558528, "complete": true }, { - "elapsed_seconds": 1.8116160410027078, + "elapsed_seconds": 1.6839710580024985, "phase": "download", "missing_pids": [], - "workload_pss_bytes": 37220352, + "workload_pss_bytes": 38901760, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 37220352, + "accounted_pss_bytes": 38901760, "complete": true }, { - "elapsed_seconds": 1.8904158920013288, + "elapsed_seconds": 1.7677223840000806, "phase": "download", "missing_pids": [], - "workload_pss_bytes": 37220352, + "workload_pss_bytes": 38901760, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 37220352, + "accounted_pss_bytes": 38901760, "complete": true }, { - "elapsed_seconds": 1.9299406019999878, + "elapsed_seconds": 1.8421711170012713, "phase": "download", "missing_pids": [], - "workload_pss_bytes": 36088832, + "workload_pss_bytes": 37720064, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 36088832, + "accounted_pss_bytes": 37720064, "complete": true }, { - "elapsed_seconds": 1.951109441000881, + "elapsed_seconds": 1.8616713890005485, "phase": "teardown", "missing_pids": [], - "workload_pss_bytes": 36088832, + "workload_pss_bytes": 37720064, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 36088832, + "accounted_pss_bytes": 37720064, "complete": true }, { - "elapsed_seconds": 2.0309728810025263, + "elapsed_seconds": 1.942245460999402, "phase": "teardown", "missing_pids": [], - "workload_pss_bytes": 36088832, + "workload_pss_bytes": 37720064, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 36088832, + "accounted_pss_bytes": 37720064, "complete": true }, { - "elapsed_seconds": 2.111628995000501, + "elapsed_seconds": 2.022453682999185, "phase": "teardown", "missing_pids": [], - "workload_pss_bytes": 36088832, + "workload_pss_bytes": 37720064, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 36088832, + "accounted_pss_bytes": 37720064, "complete": true }, { - "elapsed_seconds": 2.1824069489994145, + "elapsed_seconds": 2.1058112339997024, "phase": "teardown", "missing_pids": [], - "workload_pss_bytes": 36088832, + "workload_pss_bytes": 37720064, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 36088832, + "accounted_pss_bytes": 37720064, "complete": true }, { - "elapsed_seconds": 2.254395582000143, + "elapsed_seconds": 2.1798770499990496, "phase": "teardown", "missing_pids": [], - "workload_pss_bytes": 36088832, + "workload_pss_bytes": 37720064, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 36088832, + "accounted_pss_bytes": 37720064, "complete": true }, { - "elapsed_seconds": 2.3441446640026697, + "elapsed_seconds": 2.2614827060024254, "phase": "teardown", "missing_pids": [], - "workload_pss_bytes": 36088832, + "workload_pss_bytes": 37720064, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 36088832, + "accounted_pss_bytes": 37720064, "complete": true }, { - "elapsed_seconds": 2.3717891260021133, + "elapsed_seconds": 2.2823676459993294, "phase": "teardown", "missing_pids": [ - 486789 + 2544830 ], "workload_pss_bytes": 0, "attached_stack_pss_bytes": 0, @@ -400,7 +424,7 @@ "complete": false }, { - "elapsed_seconds": 2.3719078390022332, + "elapsed_seconds": 2.282484038001712, "phase": "exited", "missing_pids": [], "workload_pss_bytes": 0, @@ -414,47 +438,65 @@ { "phase": "idle" }, + { + "phase": "idle", + "cpu_user_seconds": 0.00011999999999999511, + "cpu_system_seconds": 2.2000000000001185e-05, + "cpu_seconds": 0.0001419999999999963 + }, { "phase": "search" }, { "phase": "search", - "search_seconds": 0.5238802590029081, - "result_count": 1200 + "search_seconds": 0.47182848500233376, + "result_count": 1200, + "cpu_user_seconds": 2.249055, + "cpu_system_seconds": 0.23929899999999996, + "cpu_seconds": 2.4883539999999997 }, { "phase": "download" }, { "phase": "download", - "download_seconds": 0.7401260299993737, + "download_seconds": 0.6974685880013567, "payload_bytes": 4194304, "sha256": "2b07811057df887086f06a67edc6ebf911de8b6741156e7a2eb1416a4b8b1b2e", - "libtorrent_version": "2.0.11.0" + "libtorrent_version": "2.0.11.0", + "cpu_user_seconds": 0.05514600000000014, + "cpu_system_seconds": 0.028542999999999985, + "cpu_seconds": 0.08368900000000012 }, { "phase": "teardown" + }, + { + "phase": "teardown", + "cpu_user_seconds": 0.006299000000000277, + "cpu_system_seconds": 0, + "cpu_seconds": 0.006299000000000277 } ], "summary": { "download": { - "sample_count": 11, + "sample_count": 10, "incomplete_samples": 0, "workload_pss_bytes": { - "median": 32350208, - "peak": 41086976 + "median": 33558528.0, + "peak": 38901760 }, "attached_stack_pss_bytes": { - "median": 0, + "median": 0.0, "peak": 0 }, "engine_pss_bytes": { - "median": 0, + "median": 0.0, "peak": 0 }, "accounted_pss_bytes": { - "median": 32350208, - "peak": 41086976 + "median": 33558528.0, + "peak": 38901760 } }, "exited": { @@ -478,31 +520,31 @@ } }, "idle": { - "sample_count": 6, + "sample_count": 5, "incomplete_samples": 0, "workload_pss_bytes": { - "median": 21508096.0, - "peak": 21920768 + "median": 21914624, + "peak": 21914624 }, "attached_stack_pss_bytes": { - "median": 0.0, + "median": 0, "peak": 0 }, "engine_pss_bytes": { - "median": 0.0, + "median": 0, "peak": 0 }, "accounted_pss_bytes": { - "median": 21508096.0, - "peak": 21920768 + "median": 21914624, + "peak": 21914624 } }, "search": { "sample_count": 9, "incomplete_samples": 1, "workload_pss_bytes": { - "median": 48107008.0, - "peak": 130493440 + "median": 24077312.0, + "peak": 119952384 }, "attached_stack_pss_bytes": { "median": 0.0, @@ -513,16 +555,36 @@ "peak": 0 }, "accounted_pss_bytes": { - "median": 48107008.0, - "peak": 130493440 + "median": 24077312.0, + "peak": 119952384 + } + }, + "startup": { + "sample_count": 1, + "incomplete_samples": 0, + "workload_pss_bytes": { + "median": 21914624, + "peak": 21914624 + }, + "attached_stack_pss_bytes": { + "median": 0, + "peak": 0 + }, + "engine_pss_bytes": { + "median": 0, + "peak": 0 + }, + "accounted_pss_bytes": { + "median": 21914624, + "peak": 21914624 } }, "teardown": { "sample_count": 7, "incomplete_samples": 1, "workload_pss_bytes": { - "median": 36088832.0, - "peak": 36088832 + "median": 37720064.0, + "peak": 37720064 }, "attached_stack_pss_bytes": { "median": 0.0, @@ -533,8 +595,8 @@ "peak": 0 }, "accounted_pss_bytes": { - "median": 36088832.0, - "peak": 36088832 + "median": 37720064.0, + "peak": 37720064 } } } @@ -542,330 +604,330 @@ { "samples": [ { - "elapsed_seconds": 0.07010188500134973, + "elapsed_seconds": 0.07077334700079518, "phase": "startup", "missing_pids": [], - "workload_pss_bytes": 15449088, + "workload_pss_bytes": 16311296, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 15449088, + "accounted_pss_bytes": 16311296, "complete": true }, { - "elapsed_seconds": 0.12448766200031969, + "elapsed_seconds": 0.12368079400039278, "phase": "idle", "missing_pids": [], - "workload_pss_bytes": 21510144, + "workload_pss_bytes": 21916672, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 21510144, + "accounted_pss_bytes": 21916672, "complete": true }, { - "elapsed_seconds": 0.20285765200242167, + "elapsed_seconds": 0.20566149099977338, "phase": "idle", "missing_pids": [], - "workload_pss_bytes": 21510144, + "workload_pss_bytes": 21916672, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 21510144, + "accounted_pss_bytes": 21916672, "complete": true }, { - "elapsed_seconds": 0.28321206500186236, + "elapsed_seconds": 0.2822286600021471, "phase": "idle", "missing_pids": [], - "workload_pss_bytes": 21510144, + "workload_pss_bytes": 21916672, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 21510144, + "accounted_pss_bytes": 21916672, "complete": true }, { - "elapsed_seconds": 0.36344261500198627, + "elapsed_seconds": 0.3550170980015537, "phase": "idle", "missing_pids": [], - "workload_pss_bytes": 21510144, + "workload_pss_bytes": 21916672, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 21510144, + "accounted_pss_bytes": 21916672, "complete": true }, { - "elapsed_seconds": 0.4448951960002887, + "elapsed_seconds": 0.4375135800000862, "phase": "idle", "missing_pids": [], - "workload_pss_bytes": 21510144, + "workload_pss_bytes": 21916672, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 21510144, + "accounted_pss_bytes": 21916672, "complete": true }, { - "elapsed_seconds": 0.5365223050030181, + "elapsed_seconds": 0.5300716570018267, "phase": "idle", "missing_pids": [], - "workload_pss_bytes": 21923840, + "workload_pss_bytes": 22305792, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 21923840, + "accounted_pss_bytes": 22305792, "complete": true }, { - "elapsed_seconds": 0.5775535070024489, + "elapsed_seconds": 0.5647180240011949, "phase": "search", "missing_pids": [], - "workload_pss_bytes": 76977152, + "workload_pss_bytes": 73652224, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 76977152, + "accounted_pss_bytes": 73652224, "complete": true }, { - "elapsed_seconds": 0.6747638400011056, + "elapsed_seconds": 0.6639382680004928, "phase": "search", "missing_pids": [], - "workload_pss_bytes": 132692992, + "workload_pss_bytes": 131946496, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 132692992, + "accounted_pss_bytes": 131946496, "complete": true }, { - "elapsed_seconds": 0.7694636670021282, + "elapsed_seconds": 0.7657968349994917, "phase": "search", "missing_pids": [], - "workload_pss_bytes": 42176512, + "workload_pss_bytes": 44535808, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 42176512, + "accounted_pss_bytes": 44535808, "complete": true }, { - "elapsed_seconds": 0.871314281001105, + "elapsed_seconds": 0.9067659870015632, "phase": "search", "missing_pids": [], - "workload_pss_bytes": 112283648, + "workload_pss_bytes": 106426368, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 112283648, + "accounted_pss_bytes": 106426368, "complete": true }, { - "elapsed_seconds": 0.9494304170002579, + "elapsed_seconds": 0.9817189679997682, "phase": "search", "missing_pids": [], - "workload_pss_bytes": 80750592, + "workload_pss_bytes": 44021760, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 80750592, + "accounted_pss_bytes": 44021760, "complete": true }, { - "elapsed_seconds": 1.0236169620002329, + "elapsed_seconds": 1.021028858001955, "phase": "search", "missing_pids": [], - "workload_pss_bytes": 23097344, + "workload_pss_bytes": 24073216, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 23097344, + "accounted_pss_bytes": 24073216, "complete": true }, { - "elapsed_seconds": 1.0431339720016695, + "elapsed_seconds": 1.117686171000969, "phase": "search", "missing_pids": [], - "workload_pss_bytes": 23097344, + "workload_pss_bytes": 24073216, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 23097344, + "accounted_pss_bytes": 24073216, "complete": true }, { - "elapsed_seconds": 1.1168462510031532, + "elapsed_seconds": 1.1988029340027424, "phase": "search", "missing_pids": [], - "workload_pss_bytes": 23097344, + "workload_pss_bytes": 24073216, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 23097344, + "accounted_pss_bytes": 24073216, "complete": true }, { - "elapsed_seconds": 1.194869633000053, - "phase": "search", + "elapsed_seconds": 1.229763647002983, + "phase": "download", "missing_pids": [], - "workload_pss_bytes": 23097344, + "workload_pss_bytes": 33566720, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 23097344, + "accounted_pss_bytes": 33566720, "complete": true }, { - "elapsed_seconds": 1.2263866339999367, + "elapsed_seconds": 1.3112399220008228, "phase": "download", "missing_pids": [], - "workload_pss_bytes": 32305152, + "workload_pss_bytes": 33566720, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 32305152, + "accounted_pss_bytes": 33566720, "complete": true }, { - "elapsed_seconds": 1.3050885000011476, + "elapsed_seconds": 1.392061325001123, "phase": "download", "missing_pids": [], - "workload_pss_bytes": 32305152, + "workload_pss_bytes": 33566720, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 32305152, + "accounted_pss_bytes": 33566720, "complete": true }, { - "elapsed_seconds": 1.3844323700031964, + "elapsed_seconds": 1.4691055370021786, "phase": "download", "missing_pids": [], - "workload_pss_bytes": 32305152, + "workload_pss_bytes": 33566720, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 32305152, + "accounted_pss_bytes": 33566720, "complete": true }, { - "elapsed_seconds": 1.4542761980010255, + "elapsed_seconds": 1.5511158110020915, "phase": "download", "missing_pids": [], - "workload_pss_bytes": 32305152, + "workload_pss_bytes": 33566720, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 32305152, + "accounted_pss_bytes": 33566720, "complete": true }, { - "elapsed_seconds": 1.5265426060032041, + "elapsed_seconds": 1.6306648400022823, "phase": "download", "missing_pids": [], - "workload_pss_bytes": 32305152, + "workload_pss_bytes": 33566720, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 32305152, + "accounted_pss_bytes": 33566720, "complete": true }, { - "elapsed_seconds": 1.5975691870007722, + "elapsed_seconds": 1.711436596000567, "phase": "download", "missing_pids": [], - "workload_pss_bytes": 32305152, + "workload_pss_bytes": 33566720, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 32305152, + "accounted_pss_bytes": 33566720, "complete": true }, { - "elapsed_seconds": 1.6748359630000778, + "elapsed_seconds": 1.782640347002598, "phase": "download", "missing_pids": [], - "workload_pss_bytes": 32305152, + "workload_pss_bytes": 42354688, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 32305152, + "accounted_pss_bytes": 42354688, "complete": true }, { - "elapsed_seconds": 1.7552270280029916, + "elapsed_seconds": 1.852732448001916, "phase": "download", "missing_pids": [], - "workload_pss_bytes": 37408768, + "workload_pss_bytes": 38488064, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 37408768, + "accounted_pss_bytes": 38488064, "complete": true }, { - "elapsed_seconds": 1.8357619930029614, + "elapsed_seconds": 1.9353510220025782, "phase": "download", "missing_pids": [], - "workload_pss_bytes": 37408768, + "workload_pss_bytes": 38488064, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 37408768, + "accounted_pss_bytes": 38488064, "complete": true }, { - "elapsed_seconds": 1.914940528000443, - "phase": "download", + "elapsed_seconds": 1.9688882430018566, + "phase": "teardown", "missing_pids": [], - "workload_pss_bytes": 36222976, + "workload_pss_bytes": 37317632, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 36222976, + "accounted_pss_bytes": 37317632, "complete": true }, { - "elapsed_seconds": 1.935444261001976, + "elapsed_seconds": 2.048800510001456, "phase": "teardown", "missing_pids": [], - "workload_pss_bytes": 36222976, + "workload_pss_bytes": 37317632, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 36222976, + "accounted_pss_bytes": 37317632, "complete": true }, { - "elapsed_seconds": 2.013886499000364, + "elapsed_seconds": 2.1307645340020827, "phase": "teardown", "missing_pids": [], - "workload_pss_bytes": 36222976, + "workload_pss_bytes": 37317632, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 36222976, + "accounted_pss_bytes": 37317632, "complete": true }, { - "elapsed_seconds": 2.085609989000659, + "elapsed_seconds": 2.212490105001052, "phase": "teardown", "missing_pids": [], - "workload_pss_bytes": 36222976, + "workload_pss_bytes": 37317632, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 36222976, + "accounted_pss_bytes": 37317632, "complete": true }, { - "elapsed_seconds": 2.1643509670029744, + "elapsed_seconds": 2.2921584930008976, "phase": "teardown", "missing_pids": [], - "workload_pss_bytes": 36222976, + "workload_pss_bytes": 37317632, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 36222976, + "accounted_pss_bytes": 37317632, "complete": true }, { - "elapsed_seconds": 2.244721937000577, + "elapsed_seconds": 2.3668779350009572, "phase": "teardown", "missing_pids": [], - "workload_pss_bytes": 36222976, + "workload_pss_bytes": 37317632, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 36222976, + "accounted_pss_bytes": 37317632, "complete": true }, { - "elapsed_seconds": 2.3160781920014415, + "elapsed_seconds": 2.3906567080011882, "phase": "teardown", "missing_pids": [], - "workload_pss_bytes": 36222976, + "workload_pss_bytes": 37317632, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 36222976, + "accounted_pss_bytes": 37317632, "complete": true }, { - "elapsed_seconds": 2.362616837002861, + "elapsed_seconds": 2.416484264002065, "phase": "teardown", "missing_pids": [ - 486862 + 2545046 ], "workload_pss_bytes": 0, "attached_stack_pss_bytes": 0, @@ -874,7 +936,7 @@ "complete": false }, { - "elapsed_seconds": 2.3627234490013507, + "elapsed_seconds": 2.416586706000089, "phase": "exited", "missing_pids": [], "workload_pss_bytes": 0, @@ -888,26 +950,44 @@ { "phase": "idle" }, + { + "phase": "idle", + "cpu_user_seconds": 4.699999999999149e-05, + "cpu_system_seconds": 5.999999999999062e-06, + "cpu_seconds": 5.2999999999990555e-05 + }, { "phase": "search" }, { "phase": "search", - "search_seconds": 0.4977558179998596, - "result_count": 1200 + "search_seconds": 0.49658820900003775, + "result_count": 1200, + "cpu_user_seconds": 2.341979, + "cpu_system_seconds": 0.24509599999999998, + "cpu_seconds": 2.5870749999999996 }, { "phase": "download" }, { "phase": "download", - "download_seconds": 0.6990966529992875, + "download_seconds": 0.7458211060002213, "payload_bytes": 4194304, "sha256": "2b07811057df887086f06a67edc6ebf911de8b6741156e7a2eb1416a4b8b1b2e", - "libtorrent_version": "2.0.11.0" + "libtorrent_version": "2.0.11.0", + "cpu_user_seconds": 0.07033299999999976, + "cpu_system_seconds": 0.02431, + "cpu_seconds": 0.09464299999999976 }, { "phase": "teardown" + }, + { + "phase": "teardown", + "cpu_user_seconds": 0.007864000000000093, + "cpu_system_seconds": 0, + "cpu_seconds": 0.007864000000000093 } ], "summary": { @@ -915,8 +995,8 @@ "sample_count": 10, "incomplete_samples": 0, "workload_pss_bytes": { - "median": 32305152.0, - "peak": 37408768 + "median": 33566720.0, + "peak": 42354688 }, "attached_stack_pss_bytes": { "median": 0.0, @@ -927,8 +1007,8 @@ "peak": 0 }, "accounted_pss_bytes": { - "median": 32305152.0, - "peak": 37408768 + "median": 33566720.0, + "peak": 42354688 } }, "exited": { @@ -955,8 +1035,8 @@ "sample_count": 6, "incomplete_samples": 0, "workload_pss_bytes": { - "median": 21510144.0, - "peak": 21923840 + "median": 21916672.0, + "peak": 22305792 }, "attached_stack_pss_bytes": { "median": 0.0, @@ -967,36 +1047,36 @@ "peak": 0 }, "accounted_pss_bytes": { - "median": 21510144.0, - "peak": 21923840 + "median": 21916672.0, + "peak": 22305792 } }, "search": { - "sample_count": 9, + "sample_count": 8, "incomplete_samples": 0, "workload_pss_bytes": { - "median": 42176512, - "peak": 132692992 + "median": 44278784.0, + "peak": 131946496 }, "attached_stack_pss_bytes": { - "median": 0, + "median": 0.0, "peak": 0 }, "engine_pss_bytes": { - "median": 0, + "median": 0.0, "peak": 0 }, "accounted_pss_bytes": { - "median": 42176512, - "peak": 132692992 + "median": 44278784.0, + "peak": 131946496 } }, "startup": { "sample_count": 1, "incomplete_samples": 0, "workload_pss_bytes": { - "median": 15449088, - "peak": 15449088 + "median": 16311296, + "peak": 16311296 }, "attached_stack_pss_bytes": { "median": 0, @@ -1007,28 +1087,28 @@ "peak": 0 }, "accounted_pss_bytes": { - "median": 15449088, - "peak": 15449088 + "median": 16311296, + "peak": 16311296 } }, "teardown": { - "sample_count": 7, + "sample_count": 8, "incomplete_samples": 1, "workload_pss_bytes": { - "median": 36222976.0, - "peak": 36222976 + "median": 37317632, + "peak": 37317632 }, "attached_stack_pss_bytes": { - "median": 0.0, + "median": 0, "peak": 0 }, "engine_pss_bytes": { - "median": 0.0, + "median": 0, "peak": 0 }, "accounted_pss_bytes": { - "median": 36222976.0, - "peak": 36222976 + "median": 37317632, + "peak": 37317632 } } } @@ -1036,340 +1116,322 @@ { "samples": [ { - "elapsed_seconds": 0.07060354400164215, + "elapsed_seconds": 0.08272569399923668, "phase": "startup", "missing_pids": [], - "workload_pss_bytes": 15432704, + "workload_pss_bytes": 14911488, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 15432704, + "accounted_pss_bytes": 14911488, "complete": true }, { - "elapsed_seconds": 0.14225364999947487, + "elapsed_seconds": 0.15991161499914597, "phase": "startup", "missing_pids": [], - "workload_pss_bytes": 21507072, + "workload_pss_bytes": 21922816, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 21507072, + "accounted_pss_bytes": 21922816, "complete": true }, { - "elapsed_seconds": 0.1611938169990026, + "elapsed_seconds": 0.18427200999940396, "phase": "idle", "missing_pids": [], - "workload_pss_bytes": 21507072, + "workload_pss_bytes": 21922816, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 21507072, + "accounted_pss_bytes": 21922816, "complete": true }, { - "elapsed_seconds": 0.24011351299850503, + "elapsed_seconds": 0.2608906429995841, "phase": "idle", "missing_pids": [], - "workload_pss_bytes": 21507072, + "workload_pss_bytes": 21922816, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 21507072, + "accounted_pss_bytes": 21922816, "complete": true }, { - "elapsed_seconds": 0.31859744200119167, + "elapsed_seconds": 0.34130294699934893, "phase": "idle", "missing_pids": [], - "workload_pss_bytes": 21507072, + "workload_pss_bytes": 21922816, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 21507072, + "accounted_pss_bytes": 21922816, "complete": true }, { - "elapsed_seconds": 0.39875572600067244, + "elapsed_seconds": 0.42110990099899936, "phase": "idle", "missing_pids": [], - "workload_pss_bytes": 21507072, + "workload_pss_bytes": 21922816, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 21507072, + "accounted_pss_bytes": 21922816, "complete": true }, { - "elapsed_seconds": 0.4728452859999379, + "elapsed_seconds": 0.49607157499849563, "phase": "idle", "missing_pids": [], - "workload_pss_bytes": 21507072, + "workload_pss_bytes": 21922816, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 21507072, - "complete": true - }, - { - "elapsed_seconds": 0.5540339610015508, - "phase": "search", - "missing_pids": [], - "workload_pss_bytes": 21916672, - "attached_stack_pss_bytes": 0, - "engine_pss_bytes": 0, - "accounted_pss_bytes": 21916672, + "accounted_pss_bytes": 21922816, "complete": true }, { - "elapsed_seconds": 0.6490613360001589, + "elapsed_seconds": 0.5794472689995018, "phase": "search", "missing_pids": [], - "workload_pss_bytes": 116733952, + "workload_pss_bytes": 22297600, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 116733952, + "accounted_pss_bytes": 22297600, "complete": true }, { - "elapsed_seconds": 0.7486974269995699, + "elapsed_seconds": 0.6772552219990757, "phase": "search", "missing_pids": [], - "workload_pss_bytes": 100445184, + "workload_pss_bytes": 126383104, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 100445184, + "accounted_pss_bytes": 126383104, "complete": true }, { - "elapsed_seconds": 0.8415411729984044, + "elapsed_seconds": 0.7780927349995181, "phase": "search", "missing_pids": [], - "workload_pss_bytes": 90210304, + "workload_pss_bytes": 100583424, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 90210304, + "accounted_pss_bytes": 100583424, "complete": true }, { - "elapsed_seconds": 0.9330257479996362, + "elapsed_seconds": 0.8743852629995672, "phase": "search", - "missing_pids": [], - "workload_pss_bytes": 113723392, + "missing_pids": [ + 2545423 + ], + "workload_pss_bytes": 90626048, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 113723392, - "complete": true + "accounted_pss_bytes": 90626048, + "complete": false }, { - "elapsed_seconds": 1.0092958610002825, + "elapsed_seconds": 0.9532858549973753, "phase": "search", "missing_pids": [], - "workload_pss_bytes": 23094272, + "workload_pss_bytes": 81639424, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 23094272, + "accounted_pss_bytes": 81639424, "complete": true }, { - "elapsed_seconds": 1.029161098998884, + "elapsed_seconds": 1.0188691049988847, "phase": "search", "missing_pids": [], - "workload_pss_bytes": 23094272, + "workload_pss_bytes": 24083456, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 23094272, + "accounted_pss_bytes": 24083456, "complete": true }, { - "elapsed_seconds": 1.127948691999336, + "elapsed_seconds": 1.1075831229973119, "phase": "search", "missing_pids": [], - "workload_pss_bytes": 23094272, + "workload_pss_bytes": 24083456, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 23094272, + "accounted_pss_bytes": 24083456, "complete": true }, { - "elapsed_seconds": 1.20429703300033, + "elapsed_seconds": 1.1886445049967733, "phase": "search", "missing_pids": [], - "workload_pss_bytes": 23094272, + "workload_pss_bytes": 24083456, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 23094272, + "accounted_pss_bytes": 24083456, "complete": true }, { - "elapsed_seconds": 1.2267869370007247, + "elapsed_seconds": 1.2199242119968403, "phase": "download", "missing_pids": [], - "workload_pss_bytes": 31071232, + "workload_pss_bytes": 32520192, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 31071232, + "accounted_pss_bytes": 32520192, "complete": true }, { - "elapsed_seconds": 1.3048600850015646, + "elapsed_seconds": 1.3009296749987698, "phase": "download", "missing_pids": [], - "workload_pss_bytes": 32319488, + "workload_pss_bytes": 33585152, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 32319488, + "accounted_pss_bytes": 33585152, "complete": true }, { - "elapsed_seconds": 1.3865046499995515, + "elapsed_seconds": 1.3828774629982945, "phase": "download", "missing_pids": [], - "workload_pss_bytes": 32319488, + "workload_pss_bytes": 33585152, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 32319488, + "accounted_pss_bytes": 33585152, "complete": true }, { - "elapsed_seconds": 1.4680904699998791, + "elapsed_seconds": 1.4650140140001895, "phase": "download", "missing_pids": [], - "workload_pss_bytes": 32319488, + "workload_pss_bytes": 33585152, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 32319488, + "accounted_pss_bytes": 33585152, "complete": true }, { - "elapsed_seconds": 1.5463095800005249, + "elapsed_seconds": 1.5425330999969447, "phase": "download", "missing_pids": [], - "workload_pss_bytes": 32319488, + "workload_pss_bytes": 33585152, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 32319488, + "accounted_pss_bytes": 33585152, "complete": true }, { - "elapsed_seconds": 1.623929590001353, + "elapsed_seconds": 1.6138100319985824, "phase": "download", "missing_pids": [], - "workload_pss_bytes": 32319488, + "workload_pss_bytes": 33585152, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 32319488, + "accounted_pss_bytes": 33585152, "complete": true }, { - "elapsed_seconds": 1.7037251610017847, + "elapsed_seconds": 1.6930637639998167, "phase": "download", "missing_pids": [], - "workload_pss_bytes": 32319488, + "workload_pss_bytes": 33585152, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 32319488, + "accounted_pss_bytes": 33585152, "complete": true }, { - "elapsed_seconds": 1.7736864590006007, + "elapsed_seconds": 1.76358611699834, "phase": "download", "missing_pids": [], - "workload_pss_bytes": 41765888, + "workload_pss_bytes": 42749952, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 41765888, + "accounted_pss_bytes": 42749952, "complete": true }, { - "elapsed_seconds": 1.8531221140001435, + "elapsed_seconds": 1.8401819139980944, "phase": "download", "missing_pids": [], - "workload_pss_bytes": 37915648, + "workload_pss_bytes": 38883328, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 37915648, + "accounted_pss_bytes": 38883328, "complete": true }, { - "elapsed_seconds": 1.9324016089994984, + "elapsed_seconds": 1.9226108539987763, "phase": "download", "missing_pids": [], - "workload_pss_bytes": 37915648, + "workload_pss_bytes": 38883328, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 37915648, + "accounted_pss_bytes": 38883328, "complete": true }, { - "elapsed_seconds": 1.9674805329996161, - "phase": "download", - "missing_pids": [], - "workload_pss_bytes": 36730880, - "attached_stack_pss_bytes": 0, - "engine_pss_bytes": 0, - "accounted_pss_bytes": 36730880, - "complete": true - }, - { - "elapsed_seconds": 1.9884941339987563, + "elapsed_seconds": 1.9614422599988757, "phase": "teardown", "missing_pids": [], - "workload_pss_bytes": 36730880, + "workload_pss_bytes": 37689344, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 36730880, + "accounted_pss_bytes": 37689344, "complete": true }, { - "elapsed_seconds": 2.0661351369999466, + "elapsed_seconds": 2.042734176997328, "phase": "teardown", "missing_pids": [], - "workload_pss_bytes": 36730880, + "workload_pss_bytes": 37689344, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 36730880, + "accounted_pss_bytes": 37689344, "complete": true }, { - "elapsed_seconds": 2.146109373999934, + "elapsed_seconds": 2.125473450996651, "phase": "teardown", "missing_pids": [], - "workload_pss_bytes": 36730880, + "workload_pss_bytes": 37689344, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 36730880, + "accounted_pss_bytes": 37689344, "complete": true }, { - "elapsed_seconds": 2.2254046730013215, + "elapsed_seconds": 2.2066593039999134, "phase": "teardown", "missing_pids": [], - "workload_pss_bytes": 36730880, + "workload_pss_bytes": 37689344, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 36730880, + "accounted_pss_bytes": 37689344, "complete": true }, { - "elapsed_seconds": 2.3056921679999505, + "elapsed_seconds": 2.2879358239988505, "phase": "teardown", "missing_pids": [], - "workload_pss_bytes": 36730880, + "workload_pss_bytes": 37689344, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 36730880, + "accounted_pss_bytes": 37689344, "complete": true }, { - "elapsed_seconds": 2.3870249559986405, + "elapsed_seconds": 2.371315156997298, "phase": "teardown", "missing_pids": [], - "workload_pss_bytes": 36741120, + "workload_pss_bytes": 37689344, "attached_stack_pss_bytes": 0, "engine_pss_bytes": 0, - "accounted_pss_bytes": 36741120, + "accounted_pss_bytes": 37689344, "complete": true }, { - "elapsed_seconds": 2.410034814998653, + "elapsed_seconds": 2.3904400519968476, "phase": "teardown", "missing_pids": [ - 486984 + 2545301 ], "workload_pss_bytes": 0, "attached_stack_pss_bytes": 0, @@ -1378,7 +1440,7 @@ "complete": false }, { - "elapsed_seconds": 2.4101275270004408, + "elapsed_seconds": 2.3905504340000334, "phase": "exited", "missing_pids": [], "workload_pss_bytes": 0, @@ -1392,47 +1454,65 @@ { "phase": "idle" }, + { + "phase": "idle", + "cpu_user_seconds": 0, + "cpu_system_seconds": 0.0005389999999999978, + "cpu_seconds": 0.0005389999999999978 + }, { "phase": "search" }, { "phase": "search", - "search_seconds": 0.487118360997556, - "result_count": 1200 + "search_seconds": 0.46335092799927224, + "result_count": 1200, + "cpu_user_seconds": 2.227102, + "cpu_system_seconds": 0.209618, + "cpu_seconds": 2.4367199999999998 }, { "phase": "download" }, { "phase": "download", - "download_seconds": 0.7380511730007129, + "download_seconds": 0.7411227969969332, "payload_bytes": 4194304, "sha256": "2b07811057df887086f06a67edc6ebf911de8b6741156e7a2eb1416a4b8b1b2e", - "libtorrent_version": "2.0.11.0" + "libtorrent_version": "2.0.11.0", + "cpu_user_seconds": 0.060805999999999916, + "cpu_system_seconds": 0.030437999999999993, + "cpu_seconds": 0.09124399999999991 }, { "phase": "teardown" + }, + { + "phase": "teardown", + "cpu_user_seconds": 0.007724000000000064, + "cpu_system_seconds": 0, + "cpu_seconds": 0.007724000000000064 } ], "summary": { "download": { - "sample_count": 11, + "sample_count": 10, "incomplete_samples": 0, "workload_pss_bytes": { - "median": 32319488, - "peak": 41765888 + "median": 33585152.0, + "peak": 42749952 }, "attached_stack_pss_bytes": { - "median": 0, + "median": 0.0, "peak": 0 }, "engine_pss_bytes": { - "median": 0, + "median": 0.0, "peak": 0 }, "accounted_pss_bytes": { - "median": 32319488, - "peak": 41765888 + "median": 33585152.0, + "peak": 42749952 } }, "exited": { @@ -1459,8 +1539,8 @@ "sample_count": 5, "incomplete_samples": 0, "workload_pss_bytes": { - "median": 21507072, - "peak": 21507072 + "median": 21922816, + "peak": 21922816 }, "attached_stack_pss_bytes": { "median": 0, @@ -1471,16 +1551,16 @@ "peak": 0 }, "accounted_pss_bytes": { - "median": 21507072, - "peak": 21507072 + "median": 21922816, + "peak": 21922816 } }, "search": { - "sample_count": 9, - "incomplete_samples": 0, + "sample_count": 8, + "incomplete_samples": 1, "workload_pss_bytes": { - "median": 23094272, - "peak": 116733952 + "median": 24083456, + "peak": 126383104 }, "attached_stack_pss_bytes": { "median": 0, @@ -1491,16 +1571,16 @@ "peak": 0 }, "accounted_pss_bytes": { - "median": 23094272, - "peak": 116733952 + "median": 24083456, + "peak": 126383104 } }, "startup": { "sample_count": 2, "incomplete_samples": 0, "workload_pss_bytes": { - "median": 18469888.0, - "peak": 21507072 + "median": 18417152.0, + "peak": 21922816 }, "attached_stack_pss_bytes": { "median": 0.0, @@ -1511,16 +1591,16 @@ "peak": 0 }, "accounted_pss_bytes": { - "median": 18469888.0, - "peak": 21507072 + "median": 18417152.0, + "peak": 21922816 } }, "teardown": { "sample_count": 7, "incomplete_samples": 1, "workload_pss_bytes": { - "median": 36730880.0, - "peak": 36741120 + "median": 37689344.0, + "peak": 37689344 }, "attached_stack_pss_bytes": { "median": 0.0, @@ -1531,8 +1611,8 @@ "peak": 0 }, "accounted_pss_bytes": { - "median": 36730880.0, - "peak": 36741120 + "median": 37689344.0, + "peak": 37689344 } } } diff --git a/pyproject.toml b/pyproject.toml index b23501e..2b3c697 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "helm-torrent" -version = "0.10.0" +version = "0.11.0" authors = [ { name="Piratebird" }, ] diff --git a/src/helm/cli/commands/session.py b/src/helm/cli/commands/session.py index c0b5a0f..c8dd3ed 100644 --- a/src/helm/cli/commands/session.py +++ b/src/helm/cli/commands/session.py @@ -14,9 +14,9 @@ def send_magnet(selected, lite_mode, json_mode=False, success_msg="Torrent sent successfully :)", tag=None): """Send a torrent to qBittorrent, falling back to the built-in downloader if it is unavailable.""" if lite_mode: - from helm.torrents.lite_downloader import download_magnet + from helm.torrents.lite_downloader import download_torrent - return download_magnet(selected.link) + return download_torrent(selected.link) try: deps.add_magnet(selected.link, tag=f"helm,{tag}" if tag else "helm") @@ -27,9 +27,9 @@ def send_magnet(selected, lite_mode, json_mode=False, success_msg="Torrent sent f"\n{T.WARNING}[!] qBittorrent not available ({e}). Falling back to LITE MODE downloader...{T.RST}\n", file=sys.stderr, ) - from helm.torrents.lite_downloader import download_magnet + from helm.torrents.lite_downloader import download_torrent - return download_magnet(selected.link) + return download_torrent(selected.link) return True diff --git a/src/helm/services/jobs.py b/src/helm/services/jobs.py index 59c4ae7..afac250 100644 --- a/src/helm/services/jobs.py +++ b/src/helm/services/jobs.py @@ -212,7 +212,7 @@ def job_tag(identifier): def execute_job(store, identifier): - from helm.torrents.lite_downloader import download_magnet + from helm.torrents.lite_downloader import download_torrent from helm.torrents.qbittorrent_client import SHARED_TAG, add_magnet job = store.get(identifier) @@ -220,7 +220,7 @@ def execute_job(store, identifier): return 1 try: if job["lite"]: - if not download_magnet(job["source"], on_complete=lambda paths: store.register_files(identifier, paths)): + if not download_torrent(job["source"], on_complete=lambda paths: store.register_files(identifier, paths)): raise RuntimeError("Built-in download did not complete") store.update(identifier, "succeeded", result="Download completed") else: diff --git a/src/helm/torrents/lite_downloader.py b/src/helm/torrents/lite_downloader.py index d20499e..fa82a4c 100644 --- a/src/helm/torrents/lite_downloader.py +++ b/src/helm/torrents/lite_downloader.py @@ -5,7 +5,7 @@ from helm.ui.ansi import Progress, T -def download_magnet(magnet_link, save_path=None, on_complete=None): +def download_torrent(magnet_link, save_path=None, on_complete=None): try: import libtorrent as lt except ImportError: @@ -116,3 +116,7 @@ def download_magnet(magnet_link, save_path=None, on_complete=None): ses.pause() return True + + +# The old name, from when only magnet links were accepted. Kept for plugins and scripts. +download_magnet = download_torrent diff --git a/tests/test_cli.py b/tests/test_cli.py index a4745b3..c2f99c3 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -141,11 +141,11 @@ def test_empty_search_explains_sources_or_filters(monkeypatch, capsys, has_raw_r def test_lite_downloader_without_libtorrent_shows_magnet(monkeypatch, capsys): - from helm.torrents.lite_downloader import download_magnet + from helm.torrents.lite_downloader import download_torrent monkeypatch.setitem(sys.modules, "libtorrent", None) magnet = "magnet:?xt=urn:btih:cafe" - assert download_magnet(magnet) is False + assert download_torrent(magnet) is False output = capsys.readouterr().out assert magnet in output assert "helm-torrent[download]" in output @@ -178,7 +178,7 @@ def sleep(seconds): magnet = "magnet:?xt=urn:btih:" + "a" * 40 destination = str(tmp_path / "downloads") - assert lite_downloader.download_magnet(magnet, destination) is (outcome == "complete") + assert lite_downloader.download_torrent(magnet, destination) is (outcome == "complete") settings = lt.session.call_args[0][0] assert settings["enable_dht"] is True assert "router.bittorrent.com:6881" in settings["dht_bootstrap_nodes"].split(",") diff --git a/tests/test_cli_commands.py b/tests/test_cli_commands.py index 62eadfc..fea305d 100644 --- a/tests/test_cli_commands.py +++ b/tests/test_cli_commands.py @@ -261,7 +261,7 @@ def interrupt(*a, **kw): def test_lite_send_uses_the_built_in_downloader(monkeypatch): import helm.torrents.lite_downloader as downloader - monkeypatch.setattr(downloader, "download_magnet", lambda link: f"downloaded {link[:20]}") + monkeypatch.setattr(downloader, "download_torrent", lambda link: f"downloaded {link[:20]}") assert session.send_magnet(item(), lite_mode=True) == "downloaded magnet:?xt=urn:btih:" @@ -272,6 +272,6 @@ def refuse(link, tag=None): raise ConnectionError("refused") monkeypatch.setattr(deps, "add_magnet", refuse) - monkeypatch.setattr(downloader, "download_magnet", lambda link: True) + monkeypatch.setattr(downloader, "download_torrent", lambda link: True) assert session.send_magnet(item(), lite_mode=False) is True assert "Falling back to LITE MODE" in capsys.readouterr().err diff --git a/tests/test_jobs.py b/tests/test_jobs.py index 8ef7ec3..fce90a2 100644 --- a/tests/test_jobs.py +++ b/tests/test_jobs.py @@ -203,14 +203,14 @@ def test_execute_job_outcomes(store, monkeypatch): job = store.enqueue(MAGNET, lite=True) assert execute_job(store, job["id"]) == 1 # Not claimed. store.claim() - monkeypatch.setattr(downloader, "download_magnet", lambda source, on_complete: False) + monkeypatch.setattr(downloader, "download_torrent", lambda source, on_complete: False) assert execute_job(store, job["id"]) == 1 assert store.get(job["id"])["status"] == "failed" store.release(job["id"]) store.enqueue(MAGNET, lite=True) store.claim() - monkeypatch.setattr(downloader, "download_magnet", lambda source, on_complete: on_complete([]) or True) + monkeypatch.setattr(downloader, "download_torrent", lambda source, on_complete: on_complete([]) or True) assert execute_job(store, job["id"]) == 0 assert store.get(job["id"])["status"] == "succeeded" diff --git a/tests/test_module_paths.py b/tests/test_module_paths.py index ce7779f..5b2d4c1 100644 --- a/tests/test_module_paths.py +++ b/tests/test_module_paths.py @@ -44,3 +44,9 @@ def test_cli_has_one_module_per_command_group(): names = sorted(info.name for info in pkgutil.iter_modules(commands.__path__)) assert names == ["background", "banner", "headless", "indexers", "session", "status", "utility"] + + +def test_download_magnet_is_kept_as_an_alias(): + from helm.torrents import lite_downloader + + assert lite_downloader.download_magnet is lite_downloader.download_torrent From dd3d699a53dd13b9d3521a29d58772d179552f24 Mon Sep 17 00:00:00 2001 From: Piratebird <141295458+Piratebird@users.noreply.github.com> Date: Tue, 3 Nov 2026 16:09:54 +0200 Subject: [PATCH 12/18] :shipit: fix(search): keep JSON publish dates and keep recovered search errors in the log - Read PublishDate from Jackett and publishDate from Prowlarr JSON results, keeping only the date part, and treat Jackett's 0001-01-01 as no date - Log the missing Prowlarr key and the JSON-to-Torznab fallbacks to helm.log only - Drop the redundant local get_secret import in search_prowlarr - Test the date parsing, both JSON paths and the file-only warning --- CHANGELOG.md | 2 ++ src/helm/search/rss_fetcher.py | 42 +++++++++++++++++++++++++++++----- tests/test_logger.py | 22 ++++++++++++++++++ tests/test_rss_fetcher.py | 41 +++++++++++++++++++++++++++++++++ 4 files changed, 101 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 76db4f1..d2da422 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -35,6 +35,8 @@ Headless services, layered TOML/JSONC settings with `config` commands, themes an - Standalone `uninstall.sh` for raw GitHub execution, with preview-by-default, selective removal and unit tests. ### Fixed +- Search results from the Jackett and Prowlarr JSON APIs now keep their publish date (only the Torznab XML fallback did before). Jackett's `0001-01-01` placeholder is treated as no date. +- A missing Prowlarr API key and a JSON search that falls back to Torznab are logged to `helm.log` only, not printed during searches. - One-shot waits now watch only the torrents this run sent (tagged `helm` plus a per-run `helm-ui-…` tag), so torrents added to qBittorrent by hand no longer hold up the teardown, and Ctrl+C removes only this run's unfinished torrents. The wait goes through the shared qBittorrent session and URL instead of its own `QB_WEBUI` default, and a missing password now stops it instead of retrying forever. - Progress lines from the Lite downloader and the one-shot wait are plain text, at most one per whole percent or 30 seconds, when output is not a terminal, so job logs no longer fill with escape codes. - qBittorrent login failures raise `QBittorrentAuthError` (a `ConnectionError`), and one-shot startup, readiness checks and teardown catch only the subprocess and HTTP errors they expect. diff --git a/src/helm/search/rss_fetcher.py b/src/helm/search/rss_fetcher.py index 11b18ae..616e28d 100644 --- a/src/helm/search/rss_fetcher.py +++ b/src/helm/search/rss_fetcher.py @@ -6,6 +6,7 @@ """ import email.utils +import re import urllib.error import xml.etree.ElementTree as ET from dataclasses import dataclass @@ -62,6 +63,22 @@ def __init__(self, title, link, seeders, leechers=0, size=0, pubdate=None, index self.indexer = indexer +ISO_DATE = re.compile(r"^\s*(\d{4})-(\d{2})-(\d{2})") + + +def iso_day(value): + """Return the YYYY-MM-DD of an ISO 8601 timestamp, or None. + + Jackett's PublishDate can carry seven fractional digits and Prowlarr's a + trailing Z, which datetime.fromisoformat rejects on older Pythons, so only + the date part is read. Jackett sends 0001-01-01 when a tracker has no date. + """ + match = ISO_DATE.match(value) if isinstance(value, str) else None + if not match or int(match.group(1)) < 1990: + return None + return "-".join(match.groups()) + + CATEGORY_MAP = {"video": "2000,5000", "games": "4000", "software": "4000", "books": "8000", "music": "3000"} @@ -153,14 +170,14 @@ def _fetch_aggregate(jackett_url, api_key, query, cat): def search_prowlarr(query, content_type="video"): - from helm.config.secret_manager import get_secret from helm.config.settings import load_settings prowlarr_url = load_settings().get("services.prowlarr") api_key = get_secret("PROWLARR_API_KEY") if not api_key or "your_prowlarr_api_key_here" in api_key.lower(): - logger.warning("Event: Prowlarr API key not configured or is placeholder.") + # Normal with search.indexer_manager = "both" and only Jackett set up; the banner shows it too. + logger.warning("Event: Prowlarr API key not configured or is placeholder.", extra={"file_only": True}) return [] # Seed default indexers on first use when none are configured. @@ -203,7 +220,7 @@ def search_prowlarr(query, content_type="video"): seeders, leechers, size, - pubdate=None, + pubdate=iso_day(item.get("publishDate")), indexer=f"Prowlarr ({indexer})", ) ) @@ -212,7 +229,9 @@ def search_prowlarr(query, content_type="video"): return sorted(results, key=lambda x: x.seeders, reverse=True) except Exception as e: - logger.error(f"Event: Prowlarr JSON search failed: {e}. Falling back to Torznab XML parsing.") + logger.error( + f"Event: Prowlarr JSON search failed: {e}. Falling back to Torznab XML parsing.", extra={"file_only": True} + ) cats = content_type.split(",") cat_ids = [] @@ -315,7 +334,15 @@ def search_jackett(query, content_type="video"): continue results.append( - TorrentItem(title, download_url, seeders, leechers, size, pubdate=None, indexer=f"Jackett ({indexer})") + TorrentItem( + title, + download_url, + seeders, + leechers, + size, + pubdate=iso_day(item.get("PublishDate")), + indexer=f"Jackett ({indexer})", + ) ) if results: @@ -323,7 +350,10 @@ def search_jackett(query, content_type="video"): return sorted(results, key=lambda x: x.seeders, reverse=True) except Exception as e: - logger.error(f"Event: Jackett JSON search failed: {e}. Falling back to ThreadPool Torznab XML parsing.") + logger.error( + f"Event: Jackett JSON search failed: {e}. Falling back to ThreadPool Torznab XML parsing.", + extra={"file_only": True}, + ) # 2) Hard fallback to XML Torznab Parsing cats = content_type.split(",") diff --git a/tests/test_logger.py b/tests/test_logger.py index ccf0325..31a5007 100644 --- a/tests/test_logger.py +++ b/tests/test_logger.py @@ -125,3 +125,25 @@ def test_tail_handles_a_single_oversized_record(tmp_path): path = tmp_path / "huge.log" path.write_text("x" * 10000) assert len(tail_log(path, max_bytes=64).encode()) <= 65 + + +def test_missing_prowlarr_key_goes_to_the_log_file_only(tmp_path, monkeypatch, capsys): + import logging + + from helm.logger import configure_logging + from helm.search import rss_fetcher + + monkeypatch.setenv("HELM_STATE_DIR", str(tmp_path)) + monkeypatch.setenv("HELM_CONFIG_DIR", str(tmp_path / "config")) + monkeypatch.delenv("PROWLARR_API_KEY", raising=False) + monkeypatch.delenv("HELM_VERBOSE", raising=False) + monkeypatch.setattr(rss_fetcher, "get_secret", lambda key: None) + configure_logging() + try: + assert rss_fetcher.search_prowlarr("ubuntu") == [] + finally: + for handler in logging.getLogger().handlers: + handler.flush() + assert "Prowlarr API key" not in capsys.readouterr().err + assert "Prowlarr API key not configured" in (tmp_path / "helm.log").read_text() + configure_logging(file_logging=False) diff --git a/tests/test_rss_fetcher.py b/tests/test_rss_fetcher.py index 5c83c49..c9bcc6c 100644 --- a/tests/test_rss_fetcher.py +++ b/tests/test_rss_fetcher.py @@ -1,3 +1,5 @@ +import responses + import helm.search.rss_fetcher as rf from helm.search.rss_fetcher import TorrentItem, _parse_feed, search_jackett @@ -103,3 +105,42 @@ def test_search_indexers_falls_back_to_lite_with_prowlarr_manager(monkeypatch): # Same list, deduped (no duplicates here). assert ret == [lite] + + +def test_iso_day_reads_jackett_and_prowlarr_timestamps(): + assert rf.iso_day("2019-07-02T12:34:56") == "2019-07-02" + assert rf.iso_day("2021-03-04T05:06:07.1234567+01:00") == "2021-03-04" # Jackett: 7 fractional digits + assert rf.iso_day("2024-12-08T16:53:15Z") == "2024-12-08" # Prowlarr + assert rf.iso_day("0001-01-01T00:00:00") is None # Jackett's "no date" + for missing in (None, "", "not a date", 20240101): + assert rf.iso_day(missing) is None + + +@responses.activate +def test_jackett_json_results_keep_their_dates(monkeypatch): + monkeypatch.setenv("JACKETT_URL", "http://jackett.test") + monkeypatch.setattr(rf, "get_secret", lambda key: "key") + results = [ + {"Title": "Dated", "Size": 1, "Seeders": 5, "Peers": 1, "Tracker": "YTS", + "MagnetUri": "magnet:?xt=urn:btih:" + "a" * 40, "PublishDate": "2019-07-02T12:34:56.1234567+00:00"}, + {"Title": "Undated", "Size": 2, "Seeders": 3, "Peers": 1, "Tracker": "TPB", + "MagnetUri": "magnet:?xt=urn:btih:" + "b" * 40, "PublishDate": "0001-01-01T00:00:00"}, + ] # fmt: skip + responses.add(responses.GET, "http://jackett.test/api/v2.0/indexers/all/results", json={"Results": results}) + items = {item.title: item.pubdate for item in search_jackett("spider-man")} + assert items == {"Dated": "2019-07-02", "Undated": None} + + +@responses.activate +def test_prowlarr_json_results_keep_their_dates(monkeypatch): + monkeypatch.setenv("PROWLARR_URL", "http://prowlarr.test") + monkeypatch.setattr(rf, "get_secret", lambda key: "key") + responses.add(responses.GET, "http://prowlarr.test/api/v1/indexer", json=[{"id": 1}]) + responses.add( + responses.GET, + "http://prowlarr.test/api/v1/search", + json=[{"title": "Dated", "size": 1, "seeders": 2, "leechers": 0, "indexer": "YTS", + "magnetUrl": "magnet:?xt=urn:btih:" + "c" * 40, "publishDate": "2024-12-08T16:53:15Z"}], + ) # fmt: skip + (item,) = rf.search_prowlarr("ubuntu") + assert item.pubdate == "2024-12-08" From 8c6573205c45f3e07f55496254dbe169d7c1fdd2 Mon Sep 17 00:00:00 2001 From: Piratebird <141295458+Piratebird@users.noreply.github.com> Date: Tue, 3 Nov 2026 16:28:33 +0200 Subject: [PATCH 13/18] :shipit: feat(search): merge duplicate results by info hash across sources - Match duplicates on info hash from magnets, hash-named .torrent URLs and the Jackett, Prowlarr and Torznab hash fields, then on normalized title and size - Merge duplicates instead of dropping them, keeping the best-seeded copy, a magnet link, any missing date or size, and every source - Show merged sources as "+N" in the list and as sources in --json - Use the shared dedupe in search_indexers --- CHANGELOG.md | 1 + src/helm/cli/commands/session.py | 1 + src/helm/search/rss_fetcher.py | 26 ++++--- src/helm/search/torrent_filter.py | 122 +++++++++++++++++++++++++----- tests/test_torrent_filter.py | 63 +++++++++++++++ 5 files changed, 183 insertions(+), 30 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d2da422..d2893b0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -35,6 +35,7 @@ Headless services, layered TOML/JSONC settings with `config` commands, themes an - Standalone `uninstall.sh` for raw GitHub execution, with preview-by-default, selective removal and unit tests. ### Fixed +- Duplicate results from different sources are merged instead of dropped. Results now match on info hash, read from magnets, from `.torrent` URLs named after the hash, and from the `InfoHash` field that Jackett, Prowlarr and Torznab send with their download links, before falling back to the title (ignoring case and punctuation) plus size. The merged result keeps the most-seeded copy, takes a missing date or size from another copy, uses a magnet over an indexer download link, lists every source as `Jackett (TPB) +1`, and lists them in `--json` as `sources`. - Search results from the Jackett and Prowlarr JSON APIs now keep their publish date (only the Torznab XML fallback did before). Jackett's `0001-01-01` placeholder is treated as no date. - A missing Prowlarr API key and a JSON search that falls back to Torznab are logged to `helm.log` only, not printed during searches. - One-shot waits now watch only the torrents this run sent (tagged `helm` plus a per-run `helm-ui-…` tag), so torrents added to qBittorrent by hand no longer hold up the teardown, and Ctrl+C removes only this run's unfinished torrents. The wait goes through the shared qBittorrent session and URL instead of its own `QB_WEBUI` default, and a missing password now stops it instead of retrying forever. diff --git a/src/helm/cli/commands/session.py b/src/helm/cli/commands/session.py index c8dd3ed..1201a8d 100644 --- a/src/helm/cli/commands/session.py +++ b/src/helm/cli/commands/session.py @@ -161,6 +161,7 @@ def run(args, teardown_oneshot): "link": sanitize_link(t.link), "seeders": getattr(t, "seeders", 0), "indexer": getattr(t, "indexer", "Unknown"), + "sources": getattr(t, "sources", None) or [getattr(t, "indexer", "Unknown")], } for t in filtered ] diff --git a/src/helm/search/rss_fetcher.py b/src/helm/search/rss_fetcher.py index 616e28d..b33630f 100644 --- a/src/helm/search/rss_fetcher.py +++ b/src/helm/search/rss_fetcher.py @@ -53,7 +53,9 @@ def source_status(error): class TorrentItem: - def __init__(self, title, link, seeders, leechers=0, size=0, pubdate=None, indexer="Unknown"): + def __init__( + self, title, link, seeders, leechers=0, size=0, pubdate=None, indexer="Unknown", info_hash=None, sources=None + ): self.title = title self.link = link self.seeders = seeders @@ -61,6 +63,10 @@ def __init__(self, title, link, seeders, leechers=0, size=0, pubdate=None, index self.size = size self.pubdate = pubdate self.indexer = indexer + # Set when the source reports a hash for a non-magnet link, so dedupe can match it. + self.info_hash = info_hash + # Every source that returned this torrent, filled in by dedupe. + self.sources = sources ISO_DATE = re.compile(r"^\s*(\d{4})-(\d{2})-(\d{2})") @@ -106,6 +112,7 @@ def _parse_feed(xml_text): seeders = 0 leechers = 0 + info_hash = None for attr in elem.findall("torznab:attr", namespaces=ns): name = attr.get("name") value = attr.get("value", "") @@ -125,6 +132,8 @@ def _parse_feed(xml_text): leechers = int(value) except ValueError: pass + elif name == "infohash": + info_hash = value elif name == "size" and size == 0: try: size = int(value) @@ -137,7 +146,7 @@ def _parse_feed(xml_text): indexer_elem = elem.find("jackettindexer") indexer = indexer_elem.text if indexer_elem is not None else "Jackett" - items.append(TorrentItem(title, link, seeders, leechers, size, pubdate, indexer)) + items.append(TorrentItem(title, link, seeders, leechers, size, pubdate, indexer, info_hash=info_hash)) return items @@ -222,6 +231,7 @@ def search_prowlarr(query, content_type="video"): size, pubdate=iso_day(item.get("publishDate")), indexer=f"Prowlarr ({indexer})", + info_hash=item.get("infoHash"), ) ) @@ -266,19 +276,10 @@ def search_indexers(query, content_type="video", fallback_lite=True): search never comes up empty. """ from helm.config.settings import load_settings + from helm.search.torrent_filter import dedupe manager = load_settings().get("search.indexer_manager") - def dedupe(items): - seen = set() - unique = [] - for item in items: - key = (item.title.lower().strip(), item.size) - if key not in seen: - seen.add(key) - unique.append(item) - return unique - items = [] if manager in ("prowlarr", "both"): items.extend(search_prowlarr(query, content_type)) @@ -342,6 +343,7 @@ def search_jackett(query, content_type="video"): size, pubdate=iso_day(item.get("PublishDate")), indexer=f"Jackett ({indexer})", + info_hash=item.get("InfoHash"), ) ) diff --git a/src/helm/search/torrent_filter.py b/src/helm/search/torrent_filter.py index 734ed35..1b10cd3 100644 --- a/src/helm/search/torrent_filter.py +++ b/src/helm/search/torrent_filter.py @@ -4,6 +4,8 @@ core/torrent_filter.py """ +import base64 +import copy import hashlib import re @@ -57,22 +59,106 @@ def filter_items(items, category_profiles, negatives, min_score=0, min_seeds=0): return [i[0] for i in sorted(results, key=lambda x: x[1], reverse=True)] +HEX_HASH = re.compile(r"^[0-9a-f]{40}$") +BASE32_HASH = re.compile(r"^[a-z2-7]{32}$") +MAGNET_HASH = re.compile(r"xt=urn:btih:([0-9a-z]+)", re.IGNORECASE) +TORRENT_URL_HASH = re.compile(r"(? 0: + return ("title", normalize_title(getattr(item, "title", "")), size) + link = getattr(item, "link", "") or "" + return ("link", hashlib.md5((link or getattr(item, "title", "")).encode("utf-8")).hexdigest()) + + +def _seeders(item): + try: + return int(getattr(item, "seeders", 0)) + except (TypeError, ValueError): + return 0 + + +def _known(value): + return value not in (None, "", 0, "Unknown") + + +def _merge(group): + """One item for a set of duplicates: the best-seeded copy, filled in from the others.""" + best = copy.copy(max(group, key=_seeders)) + for field in ("pubdate", "size"): + if not _known(getattr(best, field, None)): + value = next((getattr(i, field) for i in group if _known(getattr(i, field, None))), None) + if value is not None: + setattr(best, field, value) + if not str(getattr(best, "link", "")).lower().startswith("magnet:"): + magnet = next((i.link for i in group if str(getattr(i, "link", "")).lower().startswith("magnet:")), None) + if magnet: + best.link = magnet + found = item_hash(best) or next((item_hash(i) for i in group if item_hash(i)), None) + if found and hasattr(best, "info_hash"): + best.info_hash = found + winner = max(group, key=_seeders) + sources = [] + for item in [winner] + [i for i in group if i is not winner]: + for source in _sources(item): + if source not in sources: + sources.append(source) + if hasattr(best, "sources"): + best.sources = sources + if len(sources) > 1 and hasattr(best, "indexer"): + best.indexer = f"{sources[0]} +{len(sources) - 1}" + return best + + +def _sources(item): + """The sources behind an item; an already merged item keeps its list.""" + listed = getattr(item, "sources", None) + if listed: + return list(listed) + indexer = getattr(item, "indexer", None) + return [indexer] if indexer else [] + + def dedupe(items): - seen = set() - unique = [] - for i in items: - link = getattr(i, "link", "") - if "btih:" in link.lower(): - hash_start = link.lower().find("btih:") + 5 - hash_value = link[hash_start : hash_start + 40].lower() - else: - hash_value = ( - hashlib.md5(link.encode("utf-8")).hexdigest() - if link - else hashlib.md5(getattr(i, "title", "").encode("utf-8")).hexdigest() - ) - - if hash_value not in seen: - seen.add(hash_value) - unique.append(i) - return unique + """Collapse duplicates across sources, keeping first-seen order. + + Items match on info hash first, then on normalized title plus size, then on + the link. Duplicates are merged rather than dropped: the copy with the most + seeders wins, a missing date or size is taken from another copy, a magnet is + preferred over an indexer download URL, and every source is kept. + """ + groups = {} + for item in items: + groups.setdefault(dedupe_key(item), []).append(item) + return [group[0] if len(group) == 1 else _merge(group) for group in groups.values()] diff --git a/tests/test_torrent_filter.py b/tests/test_torrent_filter.py index d817585..a845bbb 100644 --- a/tests/test_torrent_filter.py +++ b/tests/test_torrent_filter.py @@ -76,3 +76,66 @@ def test_filter_items_keeps_unknown_seeders(): assert len(results) == 1 assert results[0].title == "Movie 1080p" assert results[0].seeders == -1 + + +from helm.search.rss_fetcher import TorrentItem # noqa: E402 +from helm.search.torrent_filter import item_hash, normalize_hash # noqa: E402 + +HASH = "c9e15763f722f23e98a29decdfae341b98d53056" +BASE32 = "ZHQVOY7XELZD5GFCTXWN7LRUDOMNKMCW" # the same hash in base32 + + +def test_normalize_hash_accepts_hex_and_base32(): + assert normalize_hash(HASH.upper()) == HASH + assert normalize_hash(BASE32) == HASH + for bad in (None, "", "xyz", HASH[:-1], 123): + assert normalize_hash(bad) is None + + +def test_item_hash_reads_field_magnet_and_torrent_url(): + assert item_hash(TorrentItem("a", "http://jackett/dl/x?path=abc", 1, info_hash=HASH.upper())) == HASH + assert item_hash(TorrentItem("a", f"magnet:?xt=urn:btih:{BASE32}&dn=a", 1)) == HASH + assert item_hash(TorrentItem("a", f"https://itorrents.org/torrent/{HASH.upper()}.torrent", 1)) == HASH + assert item_hash(TorrentItem("a", "http://localhost:19117/dl/tpb/?jackett_apikey=k&path=Q2ZESjhBRk", 1)) is None + + +def test_dedupe_merges_jackett_link_with_lite_magnet(): + jackett = TorrentItem( + "Movie.2019.1080p", "http://localhost:19117/dl/tpb/?path=x", 418, 84, 3_600_000_000, None, "Jackett (TPB)", HASH + ) + apibay = TorrentItem("Movie 2019 1080p", f"magnet:?xt=urn:btih:{HASH}", 400, 80, 0, "2019-10-11", "Apibay") + (merged,) = dedupe([jackett, apibay]) + assert merged.seeders == 418 and merged.leechers == 84 # best-seeded copy wins + assert merged.link.startswith("magnet:") # works without Jackett running + assert merged.pubdate == "2019-10-11" and merged.size == 3_600_000_000 # filled in from the other copy + assert merged.sources == ["Jackett (TPB)", "Apibay"] + assert merged.indexer == "Jackett (TPB) +1" + assert jackett.link.startswith("http") and jackett.sources is None # inputs are not changed + + +def test_dedupe_falls_back_to_normalized_title_and_size(): + a = TorrentItem("Spider-Man.Far.From.Home.2019", "http://a/1", 5, size=100, indexer="A") + b = TorrentItem("spider man far from home 2019", "http://b/2", 9, size=100, indexer="B") + c = TorrentItem("Spider-Man.Far.From.Home.2019", "http://c/3", 1, size=200, indexer="C") + d = TorrentItem("No size", "http://d/4", 1, indexer="D") + e = TorrentItem("No size", "http://e/5", 1, indexer="E") + unique = dedupe([a, b, c, d, e]) + assert [i.indexer for i in unique] == ["B +1", "C", "D", "E"] + + +def test_dedupe_is_stable_when_run_twice(): + items = [ + TorrentItem("x", f"magnet:?xt=urn:btih:{HASH}", s, indexer=name) + for s, name in ((3, "Apibay"), (7, "YTS"), (5, "Nyaa")) + ] + once = dedupe(items) + twice = dedupe(once + [TorrentItem("x", f"magnet:?xt=urn:btih:{HASH}", 1, indexer="Apibay")]) + assert once[0].indexer == "YTS +2" and once[0].sources == ["YTS", "Apibay", "Nyaa"] + assert twice[0].indexer == "YTS +2" and twice[0].sources == ["YTS", "Apibay", "Nyaa"] + + +def test_torrent_item_round_trips_through_worker_json(): + import json + + item = TorrentItem("x", "http://l", 1, info_hash=HASH, sources=["A", "B"]) + assert vars(TorrentItem(**json.loads(json.dumps(vars(item))))) == vars(item) From 63194ba8aa0cc1e44e8d1a95921a290336bd1835 Mon Sep 17 00:00:00 2001 From: Piratebird <141295458+Piratebird@users.noreply.github.com> Date: Tue, 3 Nov 2026 16:41:07 +0200 Subject: [PATCH 14/18] :shipit: feat(search): source categories, soft keyword filter, min_seeds 1 and show:all - Read Torznab categories from Jackett, Prowlarr and feeds, trust a matching category over title keywords, and hide results filed only under other types - Rank video results with audio codec, ep or single words lower instead of hiding them, and keep strong signals like PC, DODI or soundtrack as hard filters - Lower the min_seeds default to 1 and skip the old default of 3 when migrating config.json - Keep hidden results with a reason and list them with show:all in the result filter - Ask Torznab for books 7000 and console games 1000 --- CHANGELOG.md | 5 ++ README.md | 6 +- src/helm/cli/commands/session.py | 21 +++++- src/helm/config/config_manager.py | 41 ++++++++--- src/helm/config/settings.py | 9 ++- src/helm/search/rss_fetcher.py | 35 +++++++++- src/helm/search/torrent_filter.py | 49 ++++++++++++- src/helm/ui/tui.py | 30 +++++--- tests/test_cli_commands.py | 26 +++++++ tests/test_config_commands.py | 2 +- tests/test_config_manager.py | 16 +++-- tests/test_rss_fetcher.py | 13 ++-- tests/test_search_filters.py | 110 ++++++++++++++++++++++++++++++ tests/test_settings.py | 15 ++-- 14 files changed, 335 insertions(+), 43 deletions(-) create mode 100644 tests/test_search_filters.py diff --git a/CHANGELOG.md b/CHANGELOG.md index d2893b0..603b6fe 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ All notable changes to this project will be documented in this file. Headless services, layered TOML/JSONC settings with `config` commands, themes and the banner, a rebuilt setup that runs `helm-torrent init` inside the image, and a package restructure. Set the date when this is tagged. ### Changed +- `search.min_seeds` defaults to 1 instead of 3, so results with one or two seeders are shown. A `min_seeds = 3` in an old `config.json` is treated as the old default when migrating. - Rename the Lite downloader's `download_magnet` to `download_torrent`, since it also takes `.torrent` URLs and files. `download_magnet` stays as an alias. - Split setup: `setup.sh` now only checks the host (engine, native installs, systemd) and runs `helm-torrent init` inside the Helm image as the current user. `init` writes the compose file, `.env.docker`, API keys and the launcher, and takes `--engine`, `--indexers`, `--run-mode`, `--workdir`, `--socket`, `--project`, `--mount-source` and `--skip-prompts`; it asks for whatever is missing and runs even when the config file is broken. It no longer activates Jackett and Prowlarr indexers through their APIs: Jackett gets the seeded indexer files, and Prowlarr seeds its defaults on first search. If the image cannot be pulled, setup uses a local copy. - Rewrite `setup.sh` as small functions with a short `main`, tested against fake Docker, Podman and systemctl binaries. `setup.sh` and `helm-torrent init` now render one compose template, `src/helm/core/compose.template.yml`, and `docker-compose.yml.example` is removed. Setup no longer edits `config.json`; the indexer choice goes into `.env.docker` as `INDEXER_MANAGER`. The container name prefix is `helm` (or `COMPOSE_PROJECT_NAME`) everywhere, instead of the directory name in `.env.docker`. An existing `qBittorrent.conf` is kept instead of overwritten. @@ -18,6 +19,7 @@ Headless services, layered TOML/JSONC settings with `config` commands, themes an - Respect the configured download directory and reject unknown flags, blank queries, and invalid content types. ### Added +- `show:all` in the result filter lists the results that filters hid, marked `[HIDDEN]` with the reason, and the result header counts them. - Tests for the setup wizard's full-automation prompts against a local HTTP server that acts like Jackett, Prowlarr and qBittorrent, and in-process tests for `status`, indexer management and the interactive session. CI now installs tmux and tries libtorrent, so those tests run there instead of skipping, and lists any skips. - `helm-torrent daemon prune` deletes the records and logs of daemons that have stopped. - Theme presets (`helm`, `tokyo-night`, `nord`, `catppuccin-mocha`) with single-colour overrides, and `helm-torrent banner [--json]`. Banner modules and logo sources (built-in, file, command) run under one time limit, so a slow or failing part cannot break or delay the banner. @@ -35,6 +37,9 @@ Headless services, layered TOML/JSONC settings with `config` commands, themes an - Standalone `uninstall.sh` for raw GitHub execution, with preview-by-default, selective removal and unit tests. ### Fixed +- Content filters use the Torznab category a source gives (Jackett, Prowlarr and Torznab feeds): a result filed under the searched type skips the keyword checks, and one filed only under another type is hidden. Results without a category still use keywords. +- Keywords from another content type that are normal in video release names (audio codecs such as `AAC`, `MP3` and `FLAC`, plus `ep` and `single`) no longer hide video results; they only rank them lower. Strong signals such as `PC`, `DODI`, `FitGirl` or `soundtrack` still hide them. +- Book searches ask Torznab for category `7000` (books) as well as `8000` (other), and game searches add `1000` (console). - Duplicate results from different sources are merged instead of dropped. Results now match on info hash, read from magnets, from `.torrent` URLs named after the hash, and from the `InfoHash` field that Jackett, Prowlarr and Torznab send with their download links, before falling back to the title (ignoring case and punctuation) plus size. The merged result keeps the most-seeded copy, takes a missing date or size from another copy, uses a magnet over an indexer download link, lists every source as `Jackett (TPB) +1`, and lists them in `--json` as `sources`. - Search results from the Jackett and Prowlarr JSON APIs now keep their publish date (only the Torznab XML fallback did before). Jackett's `0001-01-01` placeholder is treated as no date. - A missing Prowlarr API key and a JSON search that falls back to Torznab are logged to `helm.log` only, not printed during searches. diff --git a/README.md b/README.md index c1b57af..1de75b0 100644 --- a/README.md +++ b/README.md @@ -50,7 +50,7 @@ It completely automates its own setup, orchestrating Jackett, Prowlarr, Flaresol - **Ephemeral (One-Shot) Mode:** Containers spin up when you search/download, and tear down immediately after to save RAM and CPU. - **Permanent Mode:** Keep the stack running 24/7 if you prefer. - **VPN Support:** Automatically route qBittorrent traffic through Gluetun (Wireguard/OpenVPN). -- **Live Search & Filter:** A fast, interactive CLI interface to search indexers and select torrents. +- **Live Search & Filter:** A fast, interactive CLI interface to search indexers and select torrents. The filter bar takes words to match plus `cat:`, `sort:size`, `sort:seeds` (prefix `-` for ascending) and `show:all`. - **Lite Mode (Zero Setup):** Search public APIs and bundled Python scrapers without Docker or Jackett. Lite sources run in isolated processes with a shared 30-second budget, including queueing, startup and network work. Six run simultaneously by default; use `--lite-workers 2` or `HELM_LITE_WORKERS=2` to reduce process concurrency (valid range: 1–12). Stalled workers are terminated and reaped, with POSIX process-group cleanup; completed source results are preserved. Each worker thread reuses its own HTTP session. - **CLI Indexer Management:** Manage both Jackett and Prowlarr indexers directly from the command line. @@ -96,7 +96,7 @@ If a source times out (for example, `nyaa.si`), Helm keeps results from other co - Enter a nonempty, specific query. A request containing `q=` has an empty query; current Helm rejects blank interactive and CLI searches. - Use `helm-torrent logs` for recent source errors, or `HELM_VERBOSE=true helm-torrent search "artist album" --type music --lite --json` for verbose diagnostics on stderr. -- If raw results exist but the final list is empty, check content filters and `search.min_seeds` in `config.toml` (default: 3). Use `helm-torrent paths` to locate it. +- If raw results exist but the final list is empty, check content filters and `search.min_seeds` in `config.toml` (default: 1). Use `helm-torrent paths` to locate it. Type `show:all` in the result filter to list hidden results with the reason each was hidden (`seeds`, `category` or `keyword:`). - Content types are mapped to plugin category keys when supported (video searches movies/TV/anime); general sources fall back to `all`. Inline feeds and unsupported categories still rely on local scoring/filtering. - A source summary on stderr distinguishes empty results from timeouts, HTTP failures, connection failures, and parse failures. Bundled plugins report swallowed failures; third-party plugins may need the `novaprinter.report_error` hook. Jobs whose queue budget expires are marked `budget_exhausted`; JSON stdout stays separate. @@ -174,7 +174,7 @@ What these do: ```toml # ~/.config/helm/config.toml [search] -min_seeds = 3 +min_seeds = 1 lite_workers = 6 default_type = "video" indexer_manager = "jackett" # jackett, prowlarr or both diff --git a/src/helm/cli/commands/session.py b/src/helm/cli/commands/session.py index 1201a8d..d17cb45 100644 --- a/src/helm/cli/commands/session.py +++ b/src/helm/cli/commands/session.py @@ -7,7 +7,7 @@ from helm.cli import deps from helm.cli.commands.banner import print_header from helm.cli.commands.indexers import manage_indexers -from helm.config.config_manager import CONTENT_PROFILES, NEGATIVE_KEYWORDS +from helm.config.config_manager import CONTENT_PROFILES, NEGATIVE_KEYWORDS, TORZNAB_GROUPS, WEAK_NEGATIVE_KEYWORDS from helm.ui.ansi import T @@ -88,9 +88,13 @@ def run(args, teardown_oneshot): elif state == "SEARCHING": keywords = [] negatives = [] + weak_negatives = [] + groups = set() for cat in categories: keywords.extend(CONTENT_PROFILES.get(cat, [])) negatives.extend(NEGATIVE_KEYWORDS.get(cat, [])) + weak_negatives.extend(WEAK_NEGATIVE_KEYWORDS.get(cat, [])) + groups.update(TORZNAB_GROUPS.get(cat, ())) # Collect profiles for scoring cat_profiles = {cat: CONTENT_PROFILES.get(cat, []) for cat in categories} @@ -101,6 +105,7 @@ def run(args, teardown_oneshot): query_words = set(re.findall(r"\b\w+\b", search_query.lower())) negatives = [n for n in negatives if n.lower() not in query_words] + weak_negatives = [n for n in weak_negatives if n not in all_positives and n.lower() not in query_words] # Special case for books cleaned_query = search_query @@ -123,7 +128,17 @@ def run(args, teardown_oneshot): min_seeds = deps.load_settings().get("search.min_seeds") unique_items = deps.dedupe(all_items) - filtered = deps.filter_items(unique_items, cat_profiles, negatives, min_score=0, min_seeds=min_seeds) + hidden = [] + filtered = deps.filter_items( + unique_items, + cat_profiles, + negatives, + min_score=0, + min_seeds=min_seeds, + weak_negatives=weak_negatives, + hidden=hidden, + groups=groups, + ) if not filtered: if args.json: @@ -187,7 +202,7 @@ def run(args, teardown_oneshot): try: media_type_str = "+".join(categories) if categories else "" selected, do_teardown = deps.interactive_selector( - filtered, mode_str, lite_mode=args.lite, media_type=media_type_str + filtered, mode_str, lite_mode=args.lite, media_type=media_type_str, hidden=hidden ) if do_teardown == "BACK": diff --git a/src/helm/config/config_manager.py b/src/helm/config/config_manager.py index 6a200ba..ab3181e 100644 --- a/src/helm/config/config_manager.py +++ b/src/helm/config/config_manager.py @@ -109,18 +109,43 @@ RELATED_MEDIA_TERMS = ["season", "episode", "s01", "s02"] +# Another category's keywords that are also normal in this category's release +# names: video releases name their audio track (x264 AAC, XviD MP3, FLAC) and TV +# packs use "Ep 01-06". These only lower a result's rank instead of hiding it. +WEAK_TERMS = { + "video": ["aac", "alac", "flac", "mp3", "ogg", "wav", "ep", "single"], +} + + +def _derived_negatives(cat): + derived = [kw for other, kws in CONTENT_PROFILES.items() if other != cat for kw in kws] + if cat != "video": + derived += RELATED_MEDIA_TERMS + return set(derived) + + def _build_negative_keywords(): - """Each category's negatives are the union of every *other* category's positives.""" - negatives = {} - for cat in CONTENT_PROFILES: - derived = [kw for other, kws in CONTENT_PROFILES.items() if other != cat for kw in kws] - if cat != "video": - derived += RELATED_MEDIA_TERMS - negatives[cat] = sorted(set(derived)) - return negatives + """Each category's negatives are every *other* category's positives, minus its weak terms.""" + return {cat: sorted(_derived_negatives(cat) - set(WEAK_TERMS.get(cat, ()))) for cat in CONTENT_PROFILES} + + +def _build_weak_negatives(): + return {cat: sorted(_derived_negatives(cat) & set(WEAK_TERMS.get(cat, ()))) for cat in CONTENT_PROFILES} NEGATIVE_KEYWORDS = _build_negative_keywords() +WEAK_NEGATIVE_KEYWORDS = _build_weak_negatives() + +# Torznab category ranges per content type (1000 console, 2000 movies, 3000 +# audio, 4000 PC, 5000 TV, 7000 books). 6000 (XXX), 8000 (other) and the +# tracker-specific ids above 100000 say nothing about the content type. +TORZNAB_GROUPS = { + "video": (2000, 5000), + "games": (1000, 4000), + "software": (4000,), + "books": (7000,), + "music": (3000,), +} def get_config_dir(): diff --git a/src/helm/config/settings.py b/src/helm/config/settings.py index 9d88ff3..ea2e9ff 100644 --- a/src/helm/config/settings.py +++ b/src/helm/config/settings.py @@ -59,7 +59,7 @@ class Field: COLOR_EXAMPLES.update({"success": "#4CAF50", "warning": "#E0AF68", "info": "#7DCFFF"}) FIELDS = ( - Field("search.min_seeds", "int", 3, legacy="min_seeds", minimum=0), + Field("search.min_seeds", "int", 1, legacy="min_seeds", minimum=0), Field("search.lite_workers", "int", 6, env="HELM_LITE_WORKERS", minimum=1, maximum=12), Field("search.default_type", "str", "video", choices=tuple(sorted(CONTENT_PROFILES))), Field( @@ -326,6 +326,11 @@ def atomic_write(path, text): os.unlink(temporary) +# Defaults that older versions wrote into every config.json. Such a value is +# the old default, not a user's choice, so migration treats it as unset. +RETIRED_DEFAULTS = {"search.min_seeds": 3} + + def map_legacy(config): """Convert config.json keys, keeping only valid values that differ from defaults. @@ -338,7 +343,7 @@ def map_legacy(config): value = check(field, config[field.legacy]) except ValueError: continue - if value != field.default: + if value != field.default and RETIRED_DEFAULTS.get(field.path, object()) != value: values[field.path] = value return values diff --git a/src/helm/search/rss_fetcher.py b/src/helm/search/rss_fetcher.py index b33630f..8e5b790 100644 --- a/src/helm/search/rss_fetcher.py +++ b/src/helm/search/rss_fetcher.py @@ -54,7 +54,17 @@ def source_status(error): class TorrentItem: def __init__( - self, title, link, seeders, leechers=0, size=0, pubdate=None, indexer="Unknown", info_hash=None, sources=None + self, + title, + link, + seeders, + leechers=0, + size=0, + pubdate=None, + indexer="Unknown", + info_hash=None, + sources=None, + categories=None, ): self.title = title self.link = link @@ -67,6 +77,8 @@ def __init__( self.info_hash = info_hash # Every source that returned this torrent, filled in by dedupe. self.sources = sources + # Torznab category ids the source filed this under, when it says. + self.categories = categories ISO_DATE = re.compile(r"^\s*(\d{4})-(\d{2})-(\d{2})") @@ -85,7 +97,7 @@ def iso_day(value): return "-".join(match.groups()) -CATEGORY_MAP = {"video": "2000,5000", "games": "4000", "software": "4000", "books": "8000", "music": "3000"} +CATEGORY_MAP = {"video": "2000,5000", "games": "1000,4000", "software": "4000", "books": "7000,8000", "music": "3000"} def _parse_feed(xml_text): @@ -113,6 +125,7 @@ def _parse_feed(xml_text): seeders = 0 leechers = 0 info_hash = None + categories = [c.text for c in elem.findall("category") if c.text] for attr in elem.findall("torznab:attr", namespaces=ns): name = attr.get("name") value = attr.get("value", "") @@ -134,6 +147,8 @@ def _parse_feed(xml_text): pass elif name == "infohash": info_hash = value + elif name == "category": + categories.append(value) elif name == "size" and size == 0: try: size = int(value) @@ -146,7 +161,19 @@ def _parse_feed(xml_text): indexer_elem = elem.find("jackettindexer") indexer = indexer_elem.text if indexer_elem is not None else "Jackett" - items.append(TorrentItem(title, link, seeders, leechers, size, pubdate, indexer, info_hash=info_hash)) + items.append( + TorrentItem( + title, + link, + seeders, + leechers, + size, + pubdate, + indexer, + info_hash=info_hash, + categories=categories or None, + ) + ) return items @@ -232,6 +259,7 @@ def search_prowlarr(query, content_type="video"): pubdate=iso_day(item.get("publishDate")), indexer=f"Prowlarr ({indexer})", info_hash=item.get("infoHash"), + categories=[c.get("id") for c in item.get("categories") or () if isinstance(c, dict)] or None, ) ) @@ -344,6 +372,7 @@ def search_jackett(query, content_type="video"): pubdate=iso_day(item.get("PublishDate")), indexer=f"Jackett ({indexer})", info_hash=item.get("InfoHash"), + categories=list(item.get("Category") or ()) or None, ) ) diff --git a/src/helm/search/torrent_filter.py b/src/helm/search/torrent_filter.py index 1b10cd3..767a697 100644 --- a/src/helm/search/torrent_filter.py +++ b/src/helm/search/torrent_filter.py @@ -18,11 +18,40 @@ def _compile_words(words): return re.compile(r"\b(?:" + "|".join(re.escape(w.lower()) for w in sorted_words) + r")\b") -def filter_items(items, category_profiles, negatives, min_score=0, min_seeds=0): +def category_groups(item): + """The standard Torznab groups (1000, 2000, ... 7000) a source put this item in.""" + groups = set() + for value in getattr(item, "categories", None) or (): + try: + number = int(value) + except (TypeError, ValueError): + continue + if 1000 <= number < 8000 and number // 1000 != 6: + groups.add(number // 1000 * 1000) + return groups + + +def filter_items( + items, category_profiles, negatives, min_score=0, min_seeds=0, weak_negatives=(), hidden=None, groups=None +): + """Score and filter search results, best first. + + A result whose source category matches *groups* skips the keyword checks; one + whose source category only matches other content types is hidden. Otherwise a + title with a *negatives* word is hidden and each *weak_negatives* word only + lowers its rank. Hidden items go to *hidden* as (item, reason) pairs, with + reason "seeds", "category" or "keyword:", so callers can still show them. + """ results = [] neg_pattern = _compile_words(negatives) + weak_pattern = _compile_words(weak_negatives) cat_patterns = {cat: _compile_words(pos) for cat, pos in category_profiles.items()} + wanted = set(groups or ()) + + def hide(item, reason): + if hidden is not None: + hidden.append((item, reason)) for item in items: title = getattr(item, "title", "").lower() @@ -33,11 +62,21 @@ def filter_items(items, category_profiles, negatives, min_score=0, min_seeds=0): seeders = 0 if seeders != -1 and seeders < min_seeds: + hide(item, "seeds") continue - if neg_pattern and neg_pattern.search(title): + source_groups = category_groups(item) if wanted else set() + trusted = bool(source_groups & wanted) + if source_groups and not trusted: + hide(item, "category") continue + if not trusted and neg_pattern: + match = neg_pattern.search(title) + if match: + hide(item, f"keyword:{match.group(0)}") + continue + best_cat = None best_score = 0 @@ -51,10 +90,14 @@ def filter_items(items, category_profiles, negatives, min_score=0, min_seeds=0): best_score = score best_cat = cat + penalty = 0 if trusted or not weak_pattern else len(set(weak_pattern.findall(title))) + if best_score >= min_score or not any(cat_patterns.values()): item.score = best_score item.media_type = best_cat if best_score > 0 else None - results.append((item, best_score)) + results.append((item, best_score - penalty)) + else: + hide(item, "score") return [i[0] for i in sorted(results, key=lambda x: x[1], reverse=True)] diff --git a/src/helm/ui/tui.py b/src/helm/ui/tui.py index 2fd5210..eb0f4d1 100644 --- a/src/helm/ui/tui.py +++ b/src/helm/ui/tui.py @@ -297,7 +297,10 @@ def redraw(): _exit_raw_input(fd, old_settings) -def interactive_selector(filtered_list, mode_str="", lite_mode=False, media_type=""): +def interactive_selector(filtered_list, mode_str="", lite_mode=False, media_type="", hidden=None): + """Pick one result. *hidden* holds (item, reason) pairs the filters removed; ``show:all`` lists them too.""" + hidden = list(hidden or ()) + hidden_reason = {id(item): reason for item, reason in hidden} fd = sys.stdin.fileno() if not IS_WINDOWS else None old_settings = termios.tcgetattr(fd) if not IS_WINDOWS else None current_input = "" @@ -317,9 +320,12 @@ def redraw(): cat_filter = None sort_key = None sort_desc = True + show_all = False for term in raw_terms: - if term.startswith("cat:"): + if term == "show:all": + show_all = True + elif term.startswith("cat:"): cat_filter = term.split(":", 1)[1] elif term.startswith("sort:"): sort_val = term.split(":", 1)[1] @@ -340,7 +346,8 @@ def redraw(): search_term = search_term[1:] disp_items = [] - for t in filtered_list: + source = list(filtered_list) + ([item for item, _ in hidden] if show_all else []) + for t in source: if search_term and search_term not in t.title.lower(): continue @@ -368,8 +375,12 @@ def redraw(): window_items = disp_items[start_idx:stop_idx] + if hidden and not show_all: + hidden_note = f" {T.MUTED}[{len(hidden)} hidden by filters, type show:all]{T.RST}" + else: + hidden_note = "" buf.append( - f"{T.BOLD}{T.TEXT}Found {len(disp_items)} results (showing {start_idx + 1}-{start_idx + len(window_items)}):{T.RST}{T.EOL}\r\n" + f"{T.BOLD}{T.TEXT}Found {len(disp_items)} results (showing {start_idx + 1}-{start_idx + len(window_items)}):{T.RST}{hidden_note}{T.EOL}\r\n" ) buf.append(T.LINE + "━" * 80 + f"{T.RST}{T.EOL}\r\n") @@ -381,8 +392,9 @@ def redraw(): is_generic = score == 0 # Only show tags for generic items, or items that have a media type (non-generic) - tag = f"[{item_type.upper()}]" if item_type else "[GENERIC]" - has_tag = is_generic or item_type + reason = hidden_reason.get(id(t)) + tag = "[HIDDEN]" if reason else f"[{item_type.upper()}]" if item_type else "[GENERIC]" + has_tag = reason or is_generic or item_type prefix_len = len(tag) + 1 if has_tag else 0 max_title_len = 38 - prefix_len @@ -397,6 +409,8 @@ def redraw(): size_str = format_size(getattr(t, "size", 0)) date_str = getattr(t, "pubdate", "") or "????-??-??" indexer = getattr(t, "indexer", "Unknown") + if reason: + indexer = f"{indexer} | {reason}" info_str = f"[{size_str:>9}] [{date_str:>10}] [{seeds:>4}↑ {leechs:>3}↓] [{indexer}]" @@ -417,9 +431,9 @@ def redraw(): buf.append(T.LINE + "━" * 80 + f"{T.RST}{T.EOL}\r\n") if lite_mode: - prompt = f"{T.BOLD}{T.TEXT}❯ Filter (cat:video, sort:size | Esc=Back, Ctrl-C=Exit):{T.RST} {current_input}" + prompt = f"{T.BOLD}{T.TEXT}❯ Filter (cat:video, sort:size, show:all | Esc=Back, Ctrl-C=Exit):{T.RST} {current_input}" else: - prompt = f"{T.BOLD}{T.TEXT}❯ Filter (cat:video, sort:size | Esc=Back, Ctrl-C=Exit, Ctrl-E=Teardown):{T.RST} {current_input}" + prompt = f"{T.BOLD}{T.TEXT}❯ Filter (cat:video, sort:size, show:all | Esc=Back, Ctrl-C=Exit, Ctrl-E=Teardown):{T.RST} {current_input}" buf.append(prompt + T.CLEAR_DOWN) sys.stdout.write("".join(buf)) diff --git a/tests/test_cli_commands.py b/tests/test_cli_commands.py index fea305d..53c3d51 100644 --- a/tests/test_cli_commands.py +++ b/tests/test_cli_commands.py @@ -275,3 +275,29 @@ def refuse(link, tag=None): monkeypatch.setattr(downloader, "download_torrent", lambda link: True) assert session.send_magnet(item(), lite_mode=False) is True assert "Falling back to LITE MODE" in capsys.readouterr().err + + +def test_session_hides_with_real_filters_and_passes_hidden_to_selector(ui, monkeypatch): + from helm.search.rss_fetcher import TorrentItem + from helm.search.torrent_filter import dedupe, filter_items + + monkeypatch.setattr(deps, "dedupe", dedupe) + monkeypatch.setattr(deps, "filter_items", filter_items) + found = [ + TorrentItem("Movie 2019 1080p XviD MP3", "magnet:?xt=urn:btih:" + "a" * 40, 5), + TorrentItem("Movie 2019 [DODI Repack]", "magnet:?xt=urn:btih:" + "b" * 40, 5), + TorrentItem("Movie 2019 720p", "magnet:?xt=urn:btih:" + "c" * 40, 0), + TorrentItem("Movie 2019 PC Edition", "magnet:?xt=urn:btih:" + "d" * 40, 5, categories=[2000]), + ] + seen = {} + + def selector(kept, *a, **kw): + seen["kept"] = [i.title for i in kept] + seen["hidden"] = {i.title: reason for i, reason in kw["hidden"]} + return kept[0], False + + ui(["movie"], [["video"]], [found], []) + monkeypatch.setattr(deps, "interactive_selector", selector) + session.run(session_args(), teardown_oneshot=lambda: None) + assert sorted(seen["kept"]) == ["Movie 2019 1080p XviD MP3", "Movie 2019 PC Edition"] + assert seen["hidden"] == {"Movie 2019 [DODI Repack]": "keyword:dodi", "Movie 2019 720p": "seeds"} diff --git a/tests/test_config_commands.py b/tests/test_config_commands.py index a311857..263ac49 100644 --- a/tests/test_config_commands.py +++ b/tests/test_config_commands.py @@ -113,7 +113,7 @@ def test_template_documents_every_field(file_format): def test_uncommented_jsonc_template_line_takes_effect(): - text = render_template("jsonc").replace('// "min_seeds": 3,', '"min_seeds": 9,') + text = render_template("jsonc").replace('// "min_seeds": 1,', '"min_seeds": 9,') assert parse_jsonc(text)["search"]["min_seeds"] == 9 diff --git a/tests/test_config_manager.py b/tests/test_config_manager.py index 96660b4..1877e4f 100644 --- a/tests/test_config_manager.py +++ b/tests/test_config_manager.py @@ -1,15 +1,15 @@ -from helm.config.config_manager import CONTENT_PROFILES, NEGATIVE_KEYWORDS +from helm.config.config_manager import CONTENT_PROFILES, NEGATIVE_KEYWORDS, WEAK_NEGATIVE_KEYWORDS def test_negative_keywords_derived_from_other_categories(): - # Every category's positives must be a negative for every other category, - # so adding a keyword to one profile propagates everywhere automatically. + # Every category's positives must be a negative (hard or weak) for every other + # category, so adding a keyword to one profile propagates everywhere automatically. for category in CONTENT_PROFILES: for other, other_keywords in CONTENT_PROFILES.items(): if other == category: continue for kw in other_keywords: - assert kw in NEGATIVE_KEYWORDS[category] + assert (kw in NEGATIVE_KEYWORDS[category]) != (kw in WEAK_NEGATIVE_KEYWORDS[category]) def test_video_negatives_do_not_block_media_terms(): @@ -17,3 +17,11 @@ def test_video_negatives_do_not_block_media_terms(): # results, unlike every other category. assert "season" not in NEGATIVE_KEYWORDS["video"] assert "episode" in NEGATIVE_KEYWORDS["games"] + + +def test_audio_codecs_and_ep_only_weakly_count_against_video(): + for word in ("aac", "mp3", "flac", "ep"): + assert word not in NEGATIVE_KEYWORDS["video"] and word in WEAK_NEGATIVE_KEYWORDS["video"] + for word in ("pc", "dodi", "fitgirl", "soundtrack", "epub"): + assert word in NEGATIVE_KEYWORDS["video"] + assert "mp3" in NEGATIVE_KEYWORDS["games"] and not WEAK_NEGATIVE_KEYWORDS["games"] diff --git a/tests/test_rss_fetcher.py b/tests/test_rss_fetcher.py index c9bcc6c..f75a461 100644 --- a/tests/test_rss_fetcher.py +++ b/tests/test_rss_fetcher.py @@ -122,13 +122,16 @@ def test_jackett_json_results_keep_their_dates(monkeypatch): monkeypatch.setattr(rf, "get_secret", lambda key: "key") results = [ {"Title": "Dated", "Size": 1, "Seeders": 5, "Peers": 1, "Tracker": "YTS", - "MagnetUri": "magnet:?xt=urn:btih:" + "a" * 40, "PublishDate": "2019-07-02T12:34:56.1234567+00:00"}, + "MagnetUri": "magnet:?xt=urn:btih:" + "a" * 40, "PublishDate": "2019-07-02T12:34:56.1234567+00:00", + "Category": [2000, 100001], "InfoHash": "A" * 40}, {"Title": "Undated", "Size": 2, "Seeders": 3, "Peers": 1, "Tracker": "TPB", "MagnetUri": "magnet:?xt=urn:btih:" + "b" * 40, "PublishDate": "0001-01-01T00:00:00"}, ] # fmt: skip responses.add(responses.GET, "http://jackett.test/api/v2.0/indexers/all/results", json={"Results": results}) - items = {item.title: item.pubdate for item in search_jackett("spider-man")} - assert items == {"Dated": "2019-07-02", "Undated": None} + found = {item.title: item for item in search_jackett("spider-man")} + assert {title: item.pubdate for title, item in found.items()} == {"Dated": "2019-07-02", "Undated": None} + assert found["Dated"].categories == [2000, 100001] and found["Dated"].info_hash == "A" * 40 + assert found["Undated"].categories is None @responses.activate @@ -140,7 +143,9 @@ def test_prowlarr_json_results_keep_their_dates(monkeypatch): responses.GET, "http://prowlarr.test/api/v1/search", json=[{"title": "Dated", "size": 1, "seeders": 2, "leechers": 0, "indexer": "YTS", - "magnetUrl": "magnet:?xt=urn:btih:" + "c" * 40, "publishDate": "2024-12-08T16:53:15Z"}], + "magnetUrl": "magnet:?xt=urn:btih:" + "c" * 40, "publishDate": "2024-12-08T16:53:15Z", + "infoHash": "c" * 40, "categories": [{"id": 5000, "name": "TV"}, {"id": 5040}]}], ) # fmt: skip (item,) = rf.search_prowlarr("ubuntu") assert item.pubdate == "2024-12-08" + assert item.categories == [5000, 5040] and item.info_hash == "c" * 40 diff --git a/tests/test_search_filters.py b/tests/test_search_filters.py new file mode 100644 index 0000000..1547b6f --- /dev/null +++ b/tests/test_search_filters.py @@ -0,0 +1,110 @@ +import sys + +import pytest + +from helm.config.config_manager import CONTENT_PROFILES, NEGATIVE_KEYWORDS, TORZNAB_GROUPS, WEAK_NEGATIVE_KEYWORDS +from helm.search.rss_fetcher import TorrentItem, _parse_feed +from helm.search.torrent_filter import category_groups, filter_items + +VIDEO = {"video": CONTENT_PROFILES["video"]} + + +def run(items, min_seeds=0, groups=TORZNAB_GROUPS["video"]): + hidden = [] + kept = filter_items( + items, + VIDEO, + NEGATIVE_KEYWORDS["video"], + min_seeds=min_seeds, + weak_negatives=WEAK_NEGATIVE_KEYWORDS["video"], + hidden=hidden, + groups=groups, + ) + return [i.title for i in kept], {i.title: reason for i, reason in hidden} + + +def test_audio_codec_and_episode_words_no_longer_hide_video(): + # Real titles from a "spiderman" search that the old filter dropped. + titles = [ + "The Amazing Spiderman 2 2014 HDCAM NEW AUDIO XviD MP3-RARBG", + "Ultimate.Spiderman.S02.Ep 01-06.RoSubbed", + "Spider-Man.2002.1080p.BluRay.x264.AAC", + ] + kept, hidden = run([TorrentItem(t, "magnet:?", 10) for t in titles]) + assert sorted(kept) == sorted(titles) and hidden == {} + + +def test_strong_other_category_words_still_hide_video(): + titles = ["Marvels SpiderMan 2 [DODI Repack]", "Spiderman 3 [English] [PC]", "Spiderman Soundtrack [Mp3 192kbps]"] + kept, hidden = run([TorrentItem(t, "magnet:?", 10) for t in titles]) + assert kept == [] + assert hidden == {titles[0]: "keyword:dodi", titles[1]: "keyword:pc", titles[2]: "keyword:soundtrack"} + + +def test_weak_words_rank_lower_at_equal_score(): + plain = TorrentItem("Movie 2019 1080p", "magnet:?", 1) + codec = TorrentItem("Movie 2019 1080p MP3", "magnet:?", 1) + kept, _ = run([codec, plain]) + assert kept == ["Movie 2019 1080p", "Movie 2019 1080p MP3"] + + +def test_source_category_beats_title_keywords(): + # The tracker filed it under Movies, so a "PC" in the title does not hide it. + movie = TorrentItem("The PC Movie 2020 1080p", "magnet:?", 5, categories=[2000, 2040, 100001]) + game = TorrentItem("Some Game 1080p", "magnet:?", 5, categories=[4050]) + other = TorrentItem("Unsorted pc upload", "magnet:?", 5, categories=[8000, 100002]) + kept, hidden = run([movie, game, other]) + assert kept == ["The PC Movie 2020 1080p"] + assert hidden == {"Some Game 1080p": "category", "Unsorted pc upload": "keyword:pc"} + + +def test_low_seeders_are_hidden_with_a_reason_and_unknown_kept(): + items = [TorrentItem("A 1080p", "magnet:?", 0), TorrentItem("B 1080p", "magnet:?", 1), TorrentItem("C", "m", -1)] + kept, hidden = run(items, min_seeds=1) + assert sorted(kept) == ["B 1080p", "C"] and hidden == {"A 1080p": "seeds"} + + +@pytest.mark.parametrize( + "values, groups", + [([2000, 2040], {2000}), (["5030"], {5000}), ([6000, 8000, 100003, "x", None], set()), (None, set())], +) +def test_category_groups(values, groups): + assert category_groups(TorrentItem("t", "l", 1, categories=values)) == groups + + +def test_torznab_feed_reads_categories_and_infohash(): + feed = """ + Moviehttp://jackett/dl/12000100001 + + + """ + (item,) = _parse_feed(feed) + assert item.categories == ["2000", "100001", "2040"] + assert item.info_hash == "C9E15763F722F23E98A29DECDFAE341B98D53056" + assert category_groups(item) == {2000} + + +def drive_selector(monkeypatch, keys, items, hidden): + from helm.ui import tui + + pressed = iter(keys) + monkeypatch.setattr(tui, "_read_key", lambda fd: next(pressed)) + monkeypatch.setattr(tui, "_enter_raw_input", lambda fd: None) + monkeypatch.setattr(tui, "_exit_raw_input", lambda fd, old: None) + if not tui.IS_WINDOWS: + monkeypatch.setattr(tui.termios, "tcgetattr", lambda fd: None) + monkeypatch.setattr(sys.stdin, "fileno", lambda: 0, raising=False) + return tui.interactive_selector(items, hidden=hidden) + + +def test_selector_shows_hidden_items_only_with_show_all(monkeypatch, capsys): + kept = TorrentItem("Kept 1080p", "magnet:?a", 9, indexer="YTS") + low = TorrentItem("Dead 1080p", "magnet:?b", 0, indexer="Apibay") + # Without show:all, the hidden item is counted but cannot be picked. + assert drive_selector(monkeypatch, ["DOWN", "\r"], [kept], [(low, "seeds")]) == (kept, False) + assert "1 hidden by filters, type show:all" in capsys.readouterr().out + # With show:all, it is listed after the kept results and marked. + keys = list("show:all") + ["DOWN", "\r"] + assert drive_selector(monkeypatch, keys, [kept], [(low, "seeds")]) == (low, False) + out = capsys.readouterr().out + assert "[HIDDEN]" in out and "Apibay | seeds" in out diff --git a/tests/test_settings.py b/tests/test_settings.py index 3efe5da..ee61f31 100644 --- a/tests/test_settings.py +++ b/tests/test_settings.py @@ -77,7 +77,7 @@ def snapshot(settings): def test_defaults_without_any_file(config_dir): settings = load_settings() - assert settings.get("search.min_seeds") == 3 + assert settings.get("search.min_seeds") == 1 assert settings.origin("search.min_seeds") == "default" assert settings.path is None assert list(config_dir.iterdir()) == [] @@ -268,7 +268,7 @@ def test_damaged_state_does_not_stop_startup(config_dir): state = Path(settings_module.state_file()) state.parent.mkdir(parents=True) state.write_text("{") - assert load_settings().get("search.min_seeds") == 3 + assert load_settings().get("search.min_seeds") == 1 remember({"search.min_seeds": 5}) assert load_settings().get("search.min_seeds") == 5 state.write_text('{"search.min_seeds": "bad", "other": 1}') @@ -337,8 +337,8 @@ def test_nothing_to_migrate_creates_no_file(config_dir, text): def test_corrupt_legacy_file_is_backed_up_once(config_dir, capsys): (config_dir / "config.json").write_text("{broken") - assert load_settings().get("search.min_seeds") == 3 - assert load_settings().get("search.min_seeds") == 3 + assert load_settings().get("search.min_seeds") == 1 + assert load_settings().get("search.min_seeds") == 1 assert (config_dir / "config.json.bak").read_text() == "{broken" assert capsys.readouterr().err.count("corrupted") == 1 @@ -509,3 +509,10 @@ def test_theme_and_banner_environment_overrides(config_dir, monkeypatch): assert settings.get("theme.preset") == "tokyo-night" assert settings.get("banner.enabled") is False assert settings.origin("theme.preset") == "env" + + +def test_old_min_seeds_default_in_config_json_is_not_migrated(): + # Old versions wrote min_seeds = 3 into every config.json; the default is now 1. + assert map_legacy({"min_seeds": 3}) == {} + assert map_legacy({"min_seeds": 1}) == {} + assert map_legacy({"min_seeds": 5}) == {"search.min_seeds": 5} From 41c00525d3cb64a3d980fd1a71c2de6c8263aafc Mon Sep 17 00:00:00 2001 From: Piratebird <141295458+Piratebird@users.noreply.github.com> Date: Tue, 3 Nov 2026 16:54:25 +0200 Subject: [PATCH 15/18] :shipit: feat(stack): seed 14 public Jackett indexers and share them with Prowlarr - Add EZTV, LimeTorrents, TheRARBG, TorrentDownloads, TorrentDownload, TorrentProject, Knaben, uindex, Kickass and ExtraTorrent, each checked against a live Jackett with FlareSolverr - Move YTS to its current yts.gg link - Keep one public indexer list for Jackett seeding and Prowlarr defaults, dropping the torrentgalaxy and nyaapantsu names Prowlarr never had - Leave existing Jackett indexer files alone when init runs again --- CHANGELOG.md | 3 ++ README.md | 2 ++ src/helm/search/indexer_manager.py | 3 +- src/helm/search/public_indexers.py | 28 +++++++++++++++ src/helm/stack/stack_setup.py | 18 +++++----- tests/test_public_indexers.py | 55 ++++++++++++++++++++++++++++++ 6 files changed, 100 insertions(+), 9 deletions(-) create mode 100644 src/helm/search/public_indexers.py create mode 100644 tests/test_public_indexers.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 603b6fe..87db8fe 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,7 @@ Headless services, layered TOML/JSONC settings with `config` commands, themes an - Respect the configured download directory and reject unknown flags, blank queries, and invalid content types. ### Added +- `init` now sets up 14 public Jackett indexers instead of 4, adding EZTV, LimeTorrents, TheRARBG, TorrentDownloads, TorrentDownload, TorrentProject, Knaben, uindex, Kickass and ExtraTorrent. Each was checked against a fresh Jackett with FlareSolverr. Prowlarr's first-search defaults use the same list. - `show:all` in the result filter lists the results that filters hid, marked `[HIDDEN]` with the reason, and the result header counts them. - Tests for the setup wizard's full-automation prompts against a local HTTP server that acts like Jackett, Prowlarr and qBittorrent, and in-process tests for `status`, indexer management and the interactive session. CI now installs tmux and tries libtorrent, so those tests run there instead of skipping, and lists any skips. - `helm-torrent daemon prune` deletes the records and logs of daemons that have stopped. @@ -37,6 +38,8 @@ Headless services, layered TOML/JSONC settings with `config` commands, themes an - Standalone `uninstall.sh` for raw GitHub execution, with preview-by-default, selective removal and unit tests. ### Fixed +- Rerunning `init` no longer resets Jackett indexers you have already configured; only missing ones are added. YTS is set up at its current `yts.gg` link instead of the retired `yts.mx`. +- Prowlarr's default indexers no longer include `torrentgalaxy` and `nyaapantsu`, which have no Prowlarr definition, so only 3 of its 5 defaults were ever set up. - Content filters use the Torznab category a source gives (Jackett, Prowlarr and Torznab feeds): a result filed under the searched type skips the keyword checks, and one filed only under another type is hidden. Results without a category still use keywords. - Keywords from another content type that are normal in video release names (audio codecs such as `AAC`, `MP3` and `FLAC`, plus `ep` and `single`) no longer hide video results; they only rank them lower. Strong signals such as `PC`, `DODI`, `FitGirl` or `soundtrack` still hide them. - Book searches ask Torznab for category `7000` (books) as well as `8000` (other), and game searches add `1000` (console). diff --git a/README.md b/README.md index 1de75b0..548a467 100644 --- a/README.md +++ b/README.md @@ -129,6 +129,8 @@ The script will guide you through: `setup.sh` only handles the host: the container engine, native installs and the optional systemd unit. It then pulls `ghcr.io/piratebird/helm` and runs `helm-torrent init` inside it, with the engine socket and your directories mounted at the same paths, so the files it writes are owned by you. `init` writes `docker-compose.yml` in the current directory from `src/helm/stack/compose.template.yml`, writes `state/.env.docker` with mode `0600` (including `INDEXER_MANAGER` for the containers), reads the Jackett and Prowlarr API keys, and creates the `helm-torrent.sh` launcher in one-shot mode. The CLI container gets your config directory, so `config.toml` and `config.jsonc` work there too. Set `COMPOSE_PROJECT_NAME` to change the container name prefix (default `helm`), `HELM_IMAGE` to use another image, or `HELM_SETUP_RUNNER=helm-torrent` to run `init` on the host instead of in the image. +`init` sets up 14 public Jackett indexers: 1337x, YTS, Nyaa, The Pirate Bay, EZTV, LimeTorrents, TheRARBG, TorrentDownloads, TorrentDownload, TorrentProject, Knaben, uindex, Kickass and ExtraTorrent (the list is in `src/helm/search/public_indexers.py`). Five of them sit behind Cloudflare and work through the stack's FlareSolverr. Prowlarr enables the same ones on its first search when it has none. An indexer you already set up in Jackett is left as it is, so rerunning `init` adds the missing ones only. +
## Why this exists diff --git a/src/helm/search/indexer_manager.py b/src/helm/search/indexer_manager.py index 7a490c2..9ba19de 100644 --- a/src/helm/search/indexer_manager.py +++ b/src/helm/search/indexer_manager.py @@ -5,6 +5,7 @@ from helm.config.secret_manager import get_secret from helm.config.settings import load_settings from helm.logger import get_logger +from helm.search.public_indexers import PUBLIC_INDEXER_IDS logger = get_logger(__name__) @@ -77,7 +78,7 @@ def remove_indexer(self, indexer_id): class ProwlarrManager: # Public trackers Helm enables by default when none are configured. - DEFAULT_SEED_NAMES = ("1337x", "yts", "torrentgalaxy", "nyaapantsu", "eztv") + DEFAULT_SEED_NAMES = PUBLIC_INDEXER_IDS def __init__(self): self.url = load_settings().get("services.prowlarr") diff --git a/src/helm/search/public_indexers.py b/src/helm/search/public_indexers.py new file mode 100644 index 0000000..7202bea --- /dev/null +++ b/src/helm/search/public_indexers.py @@ -0,0 +1,28 @@ +"""Public indexers Helm sets up by default in Jackett and Prowlarr. + +Each entry is a Jackett/Prowlarr definition id and the site link Jackett should +use. Links are the first entry of each definition's ``links`` list. Checked +2026-11-03 against a fresh Jackett with FlareSolverr: every one returned +results for a common query. The ones marked "Cloudflare" need FlareSolverr, +which Helm's stack runs. Skipped on purpose: torrentgalaxyclone (no results) +and internetarchive (matches any metadata, mostly not releases). +""" + +PUBLIC_INDEXERS = ( + ("1337x", "https://1337x.to/"), # Cloudflare + ("yts", "https://yts.gg/"), + ("nyaasi", "https://nyaa.si/"), + ("thepiratebay", "https://thepiratebay.org/"), + ("eztv", "https://eztvx.to/"), # Cloudflare, TV only + ("limetorrents", "https://www.limetorrents.fun/"), + ("therarbg", "https://therarbg.to/"), # Jackett only; Prowlarr has no definition + ("torrentdownloads", "https://www.torrentdownloads.pro/"), + ("torrentdownload", "https://www.torrentdownload.info/"), + ("torrentproject2", "https://torrentproject.cc/"), + ("knaben", "https://knaben.org/"), # meta-search over many trackers + ("uindex", "https://uindex.org/"), # Cloudflare + ("kickasstorrents-to", "https://kickass.torrentbay.st/"), # Cloudflare + ("extratorrent-st", "https://extratorrent.st/"), # Cloudflare +) + +PUBLIC_INDEXER_IDS = tuple(name for name, _ in PUBLIC_INDEXERS) diff --git a/src/helm/stack/stack_setup.py b/src/helm/stack/stack_setup.py index 7527a97..d93a9bc 100644 --- a/src/helm/stack/stack_setup.py +++ b/src/helm/stack/stack_setup.py @@ -11,6 +11,7 @@ """ import getpass +import json import os import re import shlex @@ -21,16 +22,12 @@ from dataclasses import dataclass, field from typing import Dict, List, Optional, Tuple +from helm.search.public_indexers import PUBLIC_INDEXERS from helm.stack import compose IMAGE = "ghcr.io/piratebird/helm:latest" SERVICES = ("prowlarr", "jackett", "qbittorrent", "flaresolverr", "gluetun") -JACKETT_SITES = ( - ("1337x", "https://1337x.to/"), - ("yts", "https://yts.mx/"), - ("nyaasi", "https://nyaa.si/"), - ("thepiratebay", "https://thepiratebay.org/"), -) +JACKETT_SITES = PUBLIC_INDEXERS QBITTORRENT_CONF = """[Preferences] WebUI\\Password_PBKDF2="@ByteArray(ARQ77eY1NUZaQsuDHbIMCA==:0WMRkYTUWVT9wVvdDtHAjU9b3b7uB8NR1Gur2hmQCvCDpm39Q+PsIfSYvgkvpe7L5yL8YQv8EaV7t8mP308QWg==)" WebUI\\Username=admin @@ -310,8 +307,13 @@ def seed_jackett(plan): directory = os.path.join(plan.state, "jackett", "Jackett", "Indexers") os.makedirs(directory, exist_ok=True) for name, site in JACKETT_SITES: - with open(os.path.join(directory, f"{name}.json"), "w", encoding="utf-8") as handle: - handle.write(f'[{{"id": "sitelink","type": "inputstring","name": "Site Link","value": "{site}"}}]\n') + path = os.path.join(directory, f"{name}.json") + if os.path.exists(path): + # Jackett saves the user's settings for this indexer here; never reset them. + continue + with open(path, "w", encoding="utf-8") as handle: + json.dump([{"id": "sitelink", "type": "inputstring", "name": "Site Link", "value": site}], handle) + handle.write("\n") def seed_qbittorrent(plan): diff --git a/tests/test_public_indexers.py b/tests/test_public_indexers.py new file mode 100644 index 0000000..2c674f7 --- /dev/null +++ b/tests/test_public_indexers.py @@ -0,0 +1,55 @@ +import json +from types import SimpleNamespace + +import responses + +from helm.search.indexer_manager import ProwlarrManager +from helm.search.public_indexers import PUBLIC_INDEXER_IDS, PUBLIC_INDEXERS +from helm.stack import stack_setup + + +def test_public_indexer_list_is_unique_and_https(): + assert len(set(PUBLIC_INDEXER_IDS)) == len(PUBLIC_INDEXER_IDS) >= 10 + for name, link in PUBLIC_INDEXERS: + assert name == name.lower() and link.startswith("https://") and link.endswith("/") + # Dead or legacy entries that used to be seeded. + assert "nyaapantsu" not in PUBLIC_INDEXER_IDS and "torrentgalaxy" not in PUBLIC_INDEXER_IDS + assert dict(PUBLIC_INDEXERS)["yts"] != "https://yts.mx/" + + +def test_seed_jackett_writes_every_indexer_in_jacketts_format(tmp_path, monkeypatch): + monkeypatch.setattr(stack_setup, "say", lambda text="": None) + stack_setup.seed_jackett(SimpleNamespace(state=str(tmp_path))) + directory = tmp_path / "jackett" / "Jackett" / "Indexers" + assert sorted(p.stem for p in directory.iterdir()) == sorted(PUBLIC_INDEXER_IDS) + for name, link in PUBLIC_INDEXERS: + (entry,) = json.loads((directory / f"{name}.json").read_text()) + assert entry == {"id": "sitelink", "type": "inputstring", "name": "Site Link", "value": link} + + +def test_seed_jackett_keeps_existing_indexer_settings(tmp_path, monkeypatch): + monkeypatch.setattr(stack_setup, "say", lambda text="": None) + directory = tmp_path / "jackett" / "Jackett" / "Indexers" + directory.mkdir(parents=True) + saved = '[{"id": "sitelink", "value": "https://my-mirror.example/"}, {"id": "sort", "value": "seeders"}]' + (directory / "1337x.json").write_text(saved) + stack_setup.seed_jackett(SimpleNamespace(state=str(tmp_path))) + assert (directory / "1337x.json").read_text() == saved + assert (directory / "knaben.json").is_file() + + +@responses.activate +def test_prowlarr_seeds_the_shared_list(monkeypatch): + monkeypatch.setenv("PROWLARR_API_KEY", "key") + schema = [ + {"definitionName": name, "name": name, "implementation": "Cardigann"} for name in ("knaben", "uindex", "other") + ] + [{"definitionName": "nyaapantsu", "name": "NyaaPantsu", "implementation": "Cardigann"}] + base = "http://localhost:19696/api/v1/indexer" + responses.add(responses.GET, f"{base}/schema", json=schema) + responses.add(responses.GET, base, json=[]) + responses.add(responses.POST, base, json={"id": 1}) + assert ProwlarrManager().seed_default_indexers() == 2 + posted = [ + json.loads(call.request.body)["definitionName"] for call in responses.calls if call.request.method == "POST" + ] + assert posted == ["knaben", "uindex"] From 78903efa45d60b1787a3145e552c63f75a128dfe Mon Sep 17 00:00:00 2001 From: Piratebird <141295458+Piratebird@users.noreply.github.com> Date: Tue, 3 Nov 2026 17:16:10 +0200 Subject: [PATCH 16/18] :shipit: feat(plugins): match qBittorrent's nova3 plugin API and use plugin download_torrent - Give retrieve_url and download_file qBittorrent's arguments, return values, unescaping, charset and gzip handling, and add headers, enable_socks_proxy, anySizeToBytes and SearchResults - Keep every plugin size form, seeder counts with separators, and pub_date as the result date - Pass third-party plugins the URL-encoded query, keeping the raw query for bundled ones - Resolve non-magnet plugin results through the plugin's download_torrent in a child process with a timeout, falling back to the link resolver --- CHANGELOG.md | 3 + README.md | 2 +- src/helm/cli/commands/session.py | 22 ++- src/helm/plugins/helpers.py | 133 ++++++++++--- src/helm/plugins/novaprinter.py | 103 +++++++--- src/helm/search/lite_plugin_loader.py | 20 +- src/helm/search/plugin_download.py | 111 +++++++++++ src/helm/search/rss_fetcher.py | 6 + src/helm/search/search_runner.py | 2 +- tests/test_plugin_compat.py | 268 ++++++++++++++++++++++++++ 10 files changed, 602 insertions(+), 68 deletions(-) create mode 100644 src/helm/search/plugin_download.py create mode 100644 tests/test_plugin_compat.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 87db8fe..b0f2ec8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,7 @@ Headless services, layered TOML/JSONC settings with `config` commands, themes an - Respect the configured download directory and reject unknown flags, blank queries, and invalid content types. ### Added +- qBittorrent plugin compatibility: `helpers` and `novaprinter` now match qBittorrent's nova3 API (`retrieve_url(url, custom_headers, request_data, ssl_context, unescape_html_entities)`, `download_file(url, referer)` returning `" "`, `headers`/`_headers`, `enable_socks_proxy`, `anySizeToBytes`, `SearchResults`). Your own plugins get the URL-encoded query, and when you pick a result whose link is not a magnet, the plugin's `download_torrent` runs in a child process with a 60-second timeout, falling back to Helm's own link resolver. By a static check of the 72 public plugins on qBittorrent's unofficial list, 59 should now load and run, up from about 30; the rest are Python 2 or need extra packages. - `init` now sets up 14 public Jackett indexers instead of 4, adding EZTV, LimeTorrents, TheRARBG, TorrentDownloads, TorrentDownload, TorrentProject, Knaben, uindex, Kickass and ExtraTorrent. Each was checked against a fresh Jackett with FlareSolverr. Prowlarr's first-search defaults use the same list. - `show:all` in the result filter lists the results that filters hid, marked `[HIDDEN]` with the reason, and the result header counts them. - Tests for the setup wizard's full-automation prompts against a local HTTP server that acts like Jackett, Prowlarr and qBittorrent, and in-process tests for `status`, indexer management and the interactive session. CI now installs tmux and tries libtorrent, so those tests run there instead of skipping, and lists any skips. @@ -38,6 +39,8 @@ Headless services, layered TOML/JSONC settings with `config` commands, themes an - Standalone `uninstall.sh` for raw GitHub execution, with preview-by-default, selective removal and unit tests. ### Fixed +- Plugin results whose size was given in GiB/MiB/KiB/TiB, in lowercase, with thousands separators, or as a number were dropped; they are kept now, and a plugin's `pub_date` shows as the result date. +- A plugin's second `retrieve_url` argument was sent as POST data instead of headers, and `download_file`'s referer was used as a file name. - Rerunning `init` no longer resets Jackett indexers you have already configured; only missing ones are added. YTS is set up at its current `yts.gg` link instead of the retired `yts.mx`. - Prowlarr's default indexers no longer include `torrentgalaxy` and `nyaapantsu`, which have no Prowlarr definition, so only 3 of its 5 defaults were ever set up. - Content filters use the Torznab category a source gives (Jackett, Prowlarr and Torznab feeds): a result filed under the searched type skips the keyword checks, and one filed only under another type is hidden. Results without a category still use keywords. diff --git a/README.md b/README.md index 548a467..664d1ff 100644 --- a/README.md +++ b/README.md @@ -343,7 +343,7 @@ Shoutout to the goats! This project is built utilizing these fantastic open-sour - **[LinuxServer.io](https://www.linuxserver.io)** — their massively maintained container images are what the Docker/Podman stack runs on (always coming in clutch istg). **Lite Mode Plugins:** -A massive thank you to the [qBittorrent search engine plugins community](https://github.com/qbittorrent/search-plugins) and developers. Helm's lightweight search mode natively supports their `.py` plugins, making it possible to search dozens of torrent indexers instantly without any Docker overhead. Bundled and adapted from that community (licensed for adaptation): **BitSearch, EZTV, LimeTorrents, SubsPlease, TorLock, TorrentProject, YTS, 1337x, The Pirate Bay/apibay** — alongside Helm's own **BitTorrented** plugin and the inline **apibay, torrents-csv & Nyaa** feeds. +A massive thank you to the [qBittorrent search engine plugins community](https://github.com/qbittorrent/search-plugins) and developers. Helm's lightweight search mode runs their `.py` plugins, making it possible to search dozens of torrent indexers instantly without any Docker overhead. Drop a plugin into the `plugins` folder of your config directory (`helm-torrent paths` shows it). Helm provides qBittorrent's plugin API: `retrieve_url` and `download_file` with qBittorrent's arguments, `headers`, `htmlentitydecode`, `enable_socks_proxy`, `prettyPrinter` (with `pub_date` and every size form `anySizeToBytes` accepts), `anySizeToBytes` and `SearchResults`. Plugins get the URL-encoded query, as in qBittorrent, and a result whose link is a details page goes through the plugin's own `download_torrent`. Python 2 plugins and plugins that need packages Helm does not install will not load. Bundled and adapted from that community (licensed for adaptation): **BitSearch, EZTV, LimeTorrents, SubsPlease, TorLock, TorrentProject, YTS, 1337x, The Pirate Bay/apibay** — alongside Helm's own **BitTorrented** plugin and the inline **apibay, torrents-csv & Nyaa** feeds. **Built with these Python libraries:** **[requests](https://github.com/psf/requests)** (originally Kenneth Reitz), **[beautifulsoup4](https://www.crummy.com/software/BeautifulSoup/)** (Leonard Richardson), **[python-dotenv](https://github.com/theskumar/python-dotenv)** (theskumar), and **[libtorrent](https://github.com/arvidn/libtorrent)** (Arvid Norberg) doing the heavy lifting. diff --git a/src/helm/cli/commands/session.py b/src/helm/cli/commands/session.py index d17cb45..40e76a1 100644 --- a/src/helm/cli/commands/session.py +++ b/src/helm/cli/commands/session.py @@ -1,6 +1,7 @@ """The interactive search session behind helm-torrent, ui and search.""" import json +import os import re import sys @@ -13,13 +14,28 @@ def send_magnet(selected, lite_mode, json_mode=False, success_msg="Torrent sent successfully :)", tag=None): """Send a torrent to qBittorrent, falling back to the built-in downloader if it is unavailable.""" + from helm.search import plugin_download + + # A plugin result may link to a details page that only its plugin can turn into a torrent. + link = plugin_download.resolve(selected) or selected.link + try: + return _send(link, lite_mode, json_mode, success_msg, tag) + finally: + if link != selected.link and plugin_download.is_plugin_temp_file(link): + try: + os.remove(link) + except OSError: + pass + + +def _send(link, lite_mode, json_mode, success_msg, tag): if lite_mode: from helm.torrents.lite_downloader import download_torrent - return download_torrent(selected.link) + return download_torrent(link) try: - deps.add_magnet(selected.link, tag=f"helm,{tag}" if tag else "helm") + deps.add_magnet(link, tag=f"helm,{tag}" if tag else "helm") if not json_mode: print(f"{T.TEXT}{success_msg}{T.RST}") except Exception as e: @@ -29,7 +45,7 @@ def send_magnet(selected, lite_mode, json_mode=False, success_msg="Torrent sent ) from helm.torrents.lite_downloader import download_torrent - return download_torrent(selected.link) + return download_torrent(link) return True diff --git a/src/helm/plugins/helpers.py b/src/helm/plugins/helpers.py index 8d9f6f5..e5fb7be 100644 --- a/src/helm/plugins/helpers.py +++ b/src/helm/plugins/helpers.py @@ -1,46 +1,115 @@ +"""Helpers for qBittorrent search plugins, with qBittorrent's nova3 signatures. + +Plugins written for qBittorrent import ``retrieve_url``, ``download_file``, +``headers`` (older plugins) or ``_headers``, ``htmlentitydecode`` and +``enable_socks_proxy`` from here. Requests go through Helm's shared session, +and failures raise instead of returning "", so the search reports which source +failed. +""" + +import gzip +import html +import os +import ssl +import tempfile +from typing import Dict + from helm.net.http import get_shared_session +TIMEOUT = 15 -def retrieve_url(url, request_data=None): - """ - Fetches the content of a URL. Used by qBittorrent search plugins. - """ - headers = { - "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36" - } - session = get_shared_session() - if request_data: - r = session.post(url, data=request_data, headers=headers, timeout=15) - else: - r = session.get(url, headers=headers, timeout=15) - r.raise_for_status() - return r.text +def _getBrowserUserAgent(): + return "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:140.0) Gecko/20100101 Firefox/140.0" -def download_file(url, filename=None): - """ - Downloads a file to a specific location. Used by qBittorrent search plugins. - """ - r = get_shared_session().get(url, timeout=15) - r.raise_for_status() - if filename: - with open(filename, "wb") as f: - f.write(r.content) - return filename - return r.content +getBrowserUserAgent = _getBrowserUserAgent -def htmlentitydecode(s): - """ - Decodes HTML entities. Used by qBittorrent search plugins. +# Old plugins import ``headers``, current ones ``_headers``; both are the same dict. +_headers = {"User-Agent": _getBrowserUserAgent()} +headers = _headers + +# Kept for old plugins; current qBittorrent unescapes in retrieve_url instead. +htmlentitydecode = html.unescape + +_proxies: Dict[str, str] = {} + + +def enable_socks_proxy(enable): + """Route plugin requests through ``qbt_socks_proxy`` (for example socks5h://host:1080) when set.""" + _proxies.clear() + url = os.environ.get("qbt_socks_proxy") + if enable and url: + _proxies.update({"http": url, "https": url}) + + +def _verify(ssl_context): + # Plugins pass an unverified context to accept a site's bad certificate. + if isinstance(ssl_context, ssl.SSLContext) and ssl_context.verify_mode == ssl.CERT_NONE: + return False + return True + + +def _body(response): + data = response.content + # Some sites send gzip without a Content-Encoding header. + if data[:2] == b"\x1f\x8b": + try: + return gzip.decompress(data) + except OSError: + return data + return data + + +def _decode(response): + content_type = response.headers.get("Content-Type", "") + charset = content_type.split("charset=", 1)[1].split(";")[0].strip() if "charset=" in content_type else "utf-8" + try: + return _body(response).decode(charset, "replace") + except LookupError: + return _body(response).decode("utf-8", "replace") + + +def retrieve_url(url, custom_headers={}, request_data=None, ssl_context=None, unescape_html_entities=True): # noqa: B006 + """Return the page at *url* as text, like qBittorrent's helper. + + *custom_headers* are added to the browser headers, *request_data* makes it a + POST, and HTML entities are unescaped unless *unescape_html_entities* is false. """ - import html + request_headers = {**_headers, **(custom_headers or {})} + session = get_shared_session() + options = {"headers": request_headers, "timeout": TIMEOUT, "verify": _verify(ssl_context)} + if _proxies: + options["proxies"] = dict(_proxies) + if request_data is not None: + if not any(key.lower() == "content-type" for key in request_headers): + request_headers["Content-Type"] = "application/x-www-form-urlencoded" + response = session.post(url, data=request_data, **options) + else: + response = session.get(url, **options) + response.raise_for_status() + text = _decode(response) + return html.unescape(text) if unescape_html_entities else text + - return html.unescape(s) +def download_file(url, referer=None, ssl_context=None): + """Save *url* to a temporary file and return " ", like qBittorrent's helper.""" + request_headers = dict(_headers) + if referer is not None: + request_headers["Referer"] = referer + options = {"headers": request_headers, "timeout": TIMEOUT, "verify": _verify(ssl_context)} + if _proxies: + options["proxies"] = dict(_proxies) + response = get_shared_session().get(url, **options) + response.raise_for_status() + handle, path = tempfile.mkstemp(suffix=".torrent") + with os.fdopen(handle, "wb") as stream: + stream.write(_body(response)) + return f"{path} {url}" -def validate_html(html, markers): - lower = html.lower() +def validate_html(html_text, markers): + lower = html_text.lower() if any(text in lower for text in ("just a moment", "cf-chl-", "captcha")): raise ValueError("Source returned a challenge page") if not any(marker.lower() in lower for marker in markers) and not any( diff --git a/src/helm/plugins/novaprinter.py b/src/helm/plugins/novaprinter.py index 23c4d61..3b281a0 100644 --- a/src/helm/plugins/novaprinter.py +++ b/src/helm/plugins/novaprinter.py @@ -1,5 +1,7 @@ +import datetime +import re import threading -from typing import List +from typing import List, TypedDict, Union from helm.search.rss_fetcher import TorrentItem, source_status @@ -30,41 +32,84 @@ def report_error(error): _local_results.errors.append(source_status(error)) +# The result dict plugins pass to prettyPrinter, as in qBittorrent's nova3. +# total=False keeps it usable on Python 3.8, which has no NotRequired. +SearchResults = TypedDict( + "SearchResults", + { + "link": str, + "name": str, + "size": Union[float, int, str], + "seeds": int, + "leech": int, + "engine_url": str, + "desc_link": str, + "pub_date": int, + }, + total=False, +) + +_SIZE = re.compile(r"^(?P\d*\.?\d+) *(?P[a-z]+)?", re.IGNORECASE) + + +def anySizeToBytes(size_string): + """Convert "1.5 GB", "700 MiB", "1,234 MB", 123 or 1.5e9 to bytes, or -1 if unknown (qBittorrent's rules).""" + if isinstance(size_string, bool): + return -1 + if isinstance(size_string, int): + return size_string + if isinstance(size_string, float): + return round(size_string) + match = _SIZE.match(str(size_string).strip().replace(",", "")) + if match is None: + return -1 + size = float(match.group("size")) + unit = match.group("unit") + if unit is not None: + size *= 2 ** {"T": 40, "G": 30, "M": 20, "K": 10}.get(unit[0].upper(), 0) + return round(size) + + +def _count(value): + """Seeders or leechers as an int; -1 when the plugin does not know.""" + if isinstance(value, bool): + return -1 + if isinstance(value, int): + return value + if isinstance(value, float): + return int(value) + text = str(value if value is not None else "").strip().replace(",", "") + return int(text) if text.lstrip("-").isdigit() else -1 + + +def _day(pub_date): + """A Unix timestamp as YYYY-MM-DD in UTC, or None when missing or invalid.""" + try: + stamp = int(pub_date) + except (TypeError, ValueError): + return None + if stamp <= 0: + return None + try: + return datetime.datetime.fromtimestamp(stamp, datetime.timezone.utc).strftime("%Y-%m-%d") + except (OverflowError, OSError, ValueError): + return None + + def prettyPrinter(result_dict): """ Called by qBittorrent search plugins to yield a parsed torrent result. It takes a dictionary and converts it into Helm's TorrentItem format. """ try: - # Convert size to bytes - size_str = result_dict.get("size", "0 B") - size_bytes = 0 - if "TB" in size_str: - size_bytes = int(float(size_str.replace("TB", "").strip()) * 1024**4) - elif "GB" in size_str: - size_bytes = int(float(size_str.replace("GB", "").strip()) * 1024**3) - elif "MB" in size_str: - size_bytes = int(float(size_str.replace("MB", "").strip()) * 1024**2) - elif "KB" in size_str: - size_bytes = int(float(size_str.replace("KB", "").strip()) * 1024) - else: - size_bytes = int(float(size_str.replace("B", "").strip())) - - seeders = result_dict.get("seeds", -1) - if isinstance(seeders, str): - seeders = int(seeders) if seeders.isdigit() else -1 - - leechers = result_dict.get("leech", -1) - if isinstance(leechers, str): - leechers = int(leechers) if leechers.isdigit() else -1 - item = TorrentItem( - title=result_dict.get("name", "Unknown"), - link=result_dict.get("link", ""), - size=size_bytes, - pubdate="Unknown", - seeders=seeders, - leechers=leechers, + title=str(result_dict.get("name") or "Unknown"), + link=str(result_dict.get("link") or ""), + size=max(anySizeToBytes(result_dict.get("size", -1)), 0), + pubdate=_day(result_dict.get("pub_date")), + seeders=_count(result_dict.get("seeds", -1)), + leechers=_count(result_dict.get("leech", -1)), + desc_link=result_dict.get("desc_link") or None, ) _local_results.items.append(item) except Exception as error: diff --git a/src/helm/search/lite_plugin_loader.py b/src/helm/search/lite_plugin_loader.py index e3eefe5..a6d6a0d 100644 --- a/src/helm/search/lite_plugin_loader.py +++ b/src/helm/search/lite_plugin_loader.py @@ -9,7 +9,8 @@ PLUGIN_SEARCH_TIMEOUT = 30 # Ensure our plugins directory is in the path so helpers and novaprinter can be imported -sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "../plugins"))) +BUNDLED_PLUGIN_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), "../plugins")) +sys.path.insert(0, BUNDLED_PLUGIN_DIR) import novaprinter # noqa: E402 @@ -81,8 +82,21 @@ def plugin_categories(plugin, content_type): return ["all"] if "all" in selected else selected -def _execute_plugin(plugin, query, content_type="all"): +def is_bundled(path): + return bool(path) and os.path.dirname(os.path.abspath(path)) == BUNDLED_PLUGIN_DIR + + +def plugin_query(query, path=None): + """The query a plugin gets: raw for Helm's bundled plugins, URL-encoded like + qBittorrent's nova2 for everyone else's, which build URLs from it directly.""" + from urllib.parse import quote + + return query if path is None or is_bundled(path) else quote(query) + + +def _execute_plugin(plugin, query, content_type="all", path=None): name = getattr(plugin, "name", plugin.__class__.__name__) + query = plugin_query(query, path) collector = novaprinter.get_results() collector.clear() novaprinter.get_errors().clear() @@ -103,6 +117,8 @@ def _execute_plugin(plugin, query, content_type="all"): after = len(collector) for item in collector: item.indexer = name + if path and callable(getattr(plugin, "download_torrent", None)): + item.plugin = os.path.abspath(path) logger.info(f"Event: Plugin {name} returned {after - before} results") # Pool workers can run several plugins. Return a snapshot before the next # plugin clears that worker's thread-local collector. diff --git a/src/helm/search/plugin_download.py b/src/helm/search/plugin_download.py new file mode 100644 index 0000000..f3b4eec --- /dev/null +++ b/src/helm/search/plugin_download.py @@ -0,0 +1,111 @@ +"""Turn a plugin result's link into a torrent with the plugin's own download_torrent. + +qBittorrent calls ``download_torrent(link)`` for any result whose link is not a +magnet; the plugin prints " ". Many plugins return +a details page as the link and only know how to get the torrent from it there. +The plugin runs in a child process with a timeout, like searches do, so a +stuck or crashing plugin cannot take the UI with it. +""" + +import io +import json +import os +import subprocess +import sys +import tempfile + +from helm.logger import get_logger + +logger = get_logger(__name__) +TIMEOUT = 60 + + +def needs_plugin(item): + link = str(getattr(item, "link", "") or "") + return bool(getattr(item, "plugin", None)) and not link.lower().startswith("magnet:") + + +def parse_output(text): + """The magnet or existing .torrent path from download_torrent's output, or None.""" + for line in text.splitlines(): + first = line.strip().split(" ", 1)[0] + if first.lower().startswith("magnet:"): + return first + if first and os.path.isfile(first): + if _looks_like_torrent(first): + return first + # download_file saved an error or details page, not torrent metadata. + if is_plugin_temp_file(first): + _remove(first) + return None + + +def _looks_like_torrent(path): + try: + with open(path, "rb") as stream: + return stream.read(1) == b"d" + except OSError: + return False + + +def _remove(path): + try: + os.remove(path) + except OSError: + pass + + +def resolve(item, timeout=TIMEOUT): + """Return a magnet or local .torrent path for *item* from its plugin, or None.""" + if not needs_plugin(item): + return None + from helm.services.runtime import child_environment + + request = json.dumps({"plugin": item.plugin, "link": item.link}) + try: + completed = subprocess.run( + [sys.executable, "-m", "helm.search.plugin_download", "--worker"], + input=request, + capture_output=True, + text=True, + timeout=timeout, + check=False, + env=child_environment(), + ) + except subprocess.TimeoutExpired: + logger.warning("Event: Plugin download_torrent timed out after %ss", timeout) + return None + if completed.returncode != 0: + logger.warning("Event: Plugin download_torrent failed: %s", completed.stderr.strip()[-300:]) + return None + found = parse_output(completed.stdout) + if found is None: + logger.warning("Event: Plugin download_torrent printed no magnet or file") + return found + + +def is_plugin_temp_file(path): + """True for a .torrent that a plugin's download_file left in the temp directory.""" + if not path or str(path).lower().startswith("magnet:"): + return False + path = os.path.abspath(str(path)) + return os.path.dirname(path) == os.path.abspath(tempfile.gettempdir()) and path.endswith(".torrent") + + +def worker(): + from helm.search.lite_plugin_loader import load_plugin + + request = json.load(sys.stdin) + plugin = load_plugin(request["plugin"]) + captured = io.StringIO() + module = sys.modules[type(plugin).__module__] + # The loader routes plugin prints to the log; download_torrent's print is its answer. + module.print = lambda *args, **kwargs: print(*args, file=captured) # type: ignore[attr-defined] + plugin.download_torrent(request["link"]) + sys.stdout.write(captured.getvalue()) + + +if __name__ == "__main__": + if sys.argv[1:] != ["--worker"]: + raise SystemExit("This module is an internal plugin worker") + worker() diff --git a/src/helm/search/rss_fetcher.py b/src/helm/search/rss_fetcher.py index 8e5b790..7c4bd68 100644 --- a/src/helm/search/rss_fetcher.py +++ b/src/helm/search/rss_fetcher.py @@ -65,6 +65,8 @@ def __init__( info_hash=None, sources=None, categories=None, + desc_link=None, + plugin=None, ): self.title = title self.link = link @@ -79,6 +81,10 @@ def __init__( self.sources = sources # Torznab category ids the source filed this under, when it says. self.categories = categories + # A plugin result's details page, and the plugin file that found it, so + # the plugin's own download_torrent can turn the link into a torrent. + self.desc_link = desc_link + self.plugin = plugin ISO_DATE = re.compile(r"^\s*(\d{4})-(\d{2})-(\d{2})") diff --git a/src/helm/search/search_runner.py b/src/helm/search/search_runner.py index f4ea08b..2bd7dda 100644 --- a/src/helm/search/search_runner.py +++ b/src/helm/search/search_runner.py @@ -146,7 +146,7 @@ def execute_job(job, query, content_type): from helm.search.lite_plugin_loader import _execute_plugin, load_plugin plugin = load_plugin(job.target) - return _execute_plugin(plugin, query, content_type) + return _execute_plugin(plugin, query, content_type, path=job.target) raise ValueError("Unknown search job kind") diff --git a/tests/test_plugin_compat.py b/tests/test_plugin_compat.py new file mode 100644 index 0000000..e98b269 --- /dev/null +++ b/tests/test_plugin_compat.py @@ -0,0 +1,268 @@ +"""qBittorrent nova3 plugin API compatibility, using small hand-written plugins.""" + +import gzip +import os +import ssl +import sys +import tempfile +import textwrap + +import pytest +import responses + +from helm.search import lite_plugin_loader, plugin_download +from helm.search.rss_fetcher import TorrentItem + +sys.path.insert(0, lite_plugin_loader.BUNDLED_PLUGIN_DIR) +import helpers # noqa: E402 +import novaprinter # noqa: E402 + +TORRENT = b"d4:infod4:name1:a12:piece lengthi16384e6:pieces20:" + b"x" * 20 + b"6:lengthi1eee" + + +# ------------------------------------------------------------------ helpers + + +@responses.activate +def test_retrieve_url_second_positional_argument_is_custom_headers(): + responses.add(responses.GET, "https://site.test/s", body="ok") + assert helpers.retrieve_url("https://site.test/s", {"Cookie": "a=b"}) == "ok" + sent = responses.calls[0].request.headers + assert sent["Cookie"] == "a=b" and sent["User-Agent"] == helpers.headers["User-Agent"] + + +@responses.activate +def test_retrieve_url_posts_form_data(): + responses.add(responses.POST, "https://site.test/api", body="posted") + assert helpers.retrieve_url("https://site.test/api", {}, b"q=ubuntu") == "posted" + request = responses.calls[0].request + assert request.body == b"q=ubuntu" and request.headers["Content-Type"] == "application/x-www-form-urlencoded" + + +@responses.activate +def test_retrieve_url_unescapes_by_default_and_honours_the_flag(): + responses.add(responses.GET, "https://site.test/", body="a & b <c>") + assert helpers.retrieve_url("https://site.test/") == "a & b " + assert helpers.retrieve_url("https://site.test/", unescape_html_entities=False) == "a & b <c>" + + +@responses.activate +def test_retrieve_url_decodes_charset_and_bare_gzip(): + responses.add( + responses.GET, "https://site.test/l1", body="café".encode("latin-1"), content_type="text/html; charset=latin-1" + ) + responses.add(responses.GET, "https://site.test/gz", body=gzip.compress("zipped é".encode())) + assert helpers.retrieve_url("https://site.test/l1") == "café" + assert helpers.retrieve_url("https://site.test/gz") == "zipped é" + + +@responses.activate +def test_retrieve_url_accepts_an_unverified_ssl_context(): + responses.add(responses.GET, "https://self-signed.test/", body="ok") + context = ssl.create_default_context() + context.check_hostname = False + context.verify_mode = ssl.CERT_NONE + assert helpers.retrieve_url("https://self-signed.test/", ssl_context=context) == "ok" + assert helpers._verify(context) is False and helpers._verify(None) is True + + +@responses.activate +def test_download_file_returns_path_and_url_and_sends_referer(): + responses.add(responses.GET, "https://site.test/a.torrent", body=TORRENT) + path, url = helpers.download_file("https://site.test/a.torrent", "https://site.test/details").split(" ", 1) + try: + assert url == "https://site.test/a.torrent" + with open(path, "rb") as stream: + assert stream.read() == TORRENT + assert responses.calls[0].request.headers["Referer"] == "https://site.test/details" + finally: + os.remove(path) + + +def test_old_and_new_header_names_and_socks_proxy(monkeypatch): + assert helpers.headers is helpers._headers and "Mozilla" in helpers.getBrowserUserAgent() + assert helpers.htmlentitydecode("&") == "&" + monkeypatch.setenv("qbt_socks_proxy", "socks5h://127.0.0.1:1080") + helpers.enable_socks_proxy(True) + assert helpers._proxies == {"http": "socks5h://127.0.0.1:1080", "https": "socks5h://127.0.0.1:1080"} + helpers.enable_socks_proxy(False) + assert helpers._proxies == {} + + +# ------------------------------------------------------------------ novaprinter + + +@pytest.mark.parametrize( + "size, expected", + [ + ("1.5 GB", 1610612736), + ("1.5 GiB", 1610612736), + ("700 MiB", 734003200), + ("2.1 gb", 2254857830), + ("1,234.5 MB", 1294467072), + ("12 KiB", 12288), + ("3 TiB", 3298534883328), + ("1234567", 1234567), + (1234567, 1234567), + (1.5e9, 1500000000), + ("-1", -1), + ("unknown", -1), + ], +) +def test_any_size_to_bytes_matches_qbittorrent(size, expected): + assert novaprinter.anySizeToBytes(size) == expected + + +def test_pretty_printer_keeps_every_size_form_and_the_date(): + novaprinter.get_results().clear() + for size in ("1.5 GiB", "1,234 MB", 1234567, 1.5e9, "lots"): + novaprinter.prettyPrinter( + {"link": "magnet:?x", "name": "a", "size": size, "seeds": "1,204", "leech": None, "engine_url": "e", + "desc_link": "https://site.test/t/1", "pub_date": 1696870394} + ) # fmt: skip + items = novaprinter.get_results() + assert [i.size for i in items] == [1610612736, 1293942784, 1234567, 1500000000, 0] + assert {i.pubdate for i in items} == {"2023-10-09"} + assert {i.seeders for i in items} == {1204} and {i.leechers for i in items} == {-1} + assert {i.desc_link for i in items} == {"https://site.test/t/1"} + novaprinter.get_results().clear() + + +def test_pretty_printer_without_a_date_and_search_results_type(): + novaprinter.get_results().clear() + novaprinter.prettyPrinter(novaprinter.SearchResults(link="magnet:?x", name="b", size="1 MB", seeds=1, leech=0)) + (item,) = novaprinter.get_results() + assert item.pubdate is None and item.size == 1048576 + novaprinter.get_results().clear() + + +# ------------------------------------------------------------------ community-style plugins + +COMMUNITY_PLUGIN = """ +# VERSION: 1.0 +from helpers import download_file, headers, retrieve_url +from novaprinter import SearchResults, anySizeToBytes, prettyPrinter + + +class community(object): + url = "https://community.test" + name = "Community" + supported_categories = {"all": "0", "movies": "1"} + + def search(self, what, cat="all"): + result: SearchResults = { + "link": self.url + "/details/" + what, + "name": "Seen " + what, + "size": str(anySizeToBytes("1.5 GiB")), + "seeds": 7, + "leech": 2, + "engine_url": self.url, + "desc_link": self.url + "/details/" + what, + "pub_date": 1696870394, + } + prettyPrinter(result) + + def download_torrent(self, info): + print(MAGNET + " " + info) +""" + + +def write_plugin(directory, name, body, **constants): + path = directory / f"{name}.py" + extra = "".join(f"{key} = {value!r}\n" for key, value in constants.items()) + path.write_text(textwrap.dedent(body).replace("# VERSION: 1.0\n", "# VERSION: 1.0\n" + extra, 1)) + return path + + +def test_community_plugin_loads_gets_an_encoded_query_and_remembers_itself(tmp_path): + path = write_plugin(tmp_path, "community", COMMUNITY_PLUGIN, MAGNET="magnet:?xt=urn:btih:" + "a" * 40) + plugin = lite_plugin_loader.load_plugin(str(path)) + (item,) = lite_plugin_loader._execute_plugin(plugin, "spider man & co", "all", path=str(path)) + assert item.title == "Seen spider%20man%20%26%20co" # nova2 URL-encodes the query + assert item.size == 1610612736 and item.pubdate == "2023-10-09" and item.indexer == "Community" + assert item.plugin == str(path) and item.desc_link == "https://community.test/details/spider%20man%20%26%20co" + + +def test_bundled_plugins_keep_the_raw_query(): + bundled = os.path.join(lite_plugin_loader.BUNDLED_PLUGIN_DIR, "yts.py") + assert lite_plugin_loader.plugin_query("spider man", bundled) == "spider man" + assert lite_plugin_loader.plugin_query("spider man", "/home/u/.config/helm/plugins/x.py") == "spider%20man" + assert lite_plugin_loader.plugin_query("spider man") == "spider man" + + +def test_plugin_download_returns_the_magnet_it_prints(tmp_path): + magnet = "magnet:?xt=urn:btih:" + "b" * 40 + path = write_plugin(tmp_path, "community", COMMUNITY_PLUGIN, MAGNET=magnet) + item = TorrentItem("t", "https://community.test/details/1", 1, plugin=str(path)) + assert plugin_download.resolve(item) == magnet + + +TORRENT_PLUGIN = """ +# VERSION: 1.0 +import tempfile + + +class saver(object): + url = "https://saver.test" + name = "Saver" + + def search(self, what, cat="all"): + pass + + def download_torrent(self, info): + handle, path = tempfile.mkstemp(suffix=".torrent") + with open(handle, "wb") as stream: + stream.write(BODY) + print(path + " " + info) +""" + + +def test_plugin_download_accepts_a_torrent_file_and_drops_an_html_one(tmp_path): + good = write_plugin(tmp_path, "saver", TORRENT_PLUGIN, BODY=TORRENT) + found = plugin_download.resolve(TorrentItem("t", "https://saver.test/1", 1, plugin=str(good))) + try: + assert found and plugin_download.is_plugin_temp_file(found) and open(found, "rb").read() == TORRENT + finally: + os.remove(found) + bad_dir = tmp_path / "bad" + bad_dir.mkdir() + bad = write_plugin(bad_dir, "saver", TORRENT_PLUGIN, BODY=b"details") + before = set(os.listdir(tempfile.gettempdir())) + assert plugin_download.resolve(TorrentItem("t", "https://saver.test/1", 1, plugin=str(bad))) is None + assert not {f for f in set(os.listdir(tempfile.gettempdir())) - before if f.endswith(".torrent")} + + +def test_plugin_download_survives_crashes_and_timeouts(tmp_path): + crash = write_plugin( + tmp_path, "crash", COMMUNITY_PLUGIN.replace("print(MAGNET", "raise RuntimeError(MAGNET"), MAGNET="x" + ) + assert plugin_download.resolve(TorrentItem("t", "https://c.test/1", 1, plugin=str(crash))) is None + slow_dir = tmp_path / "slow" + slow_dir.mkdir() + slow = write_plugin( + slow_dir, + "slow", + COMMUNITY_PLUGIN.replace("print(MAGNET", "__import__('time').sleep(30); print(MAGNET"), + MAGNET="x", + ) + assert plugin_download.resolve(TorrentItem("t", "https://c.test/1", 1, plugin=str(slow)), timeout=2) is None + + +def test_magnets_and_plain_results_skip_the_plugin(): + assert not plugin_download.needs_plugin(TorrentItem("t", "magnet:?xt=urn:btih:" + "c" * 40, 1, plugin="/p.py")) + assert not plugin_download.needs_plugin(TorrentItem("t", "https://x.test/a.torrent", 1)) + assert plugin_download.needs_plugin(TorrentItem("t", "https://x.test/details/1", 1, plugin="/p.py")) + + +def test_send_magnet_uses_the_plugin_result_and_removes_its_temp_file(monkeypatch): + from helm.cli import deps + from helm.cli.commands import session + + handle, path = tempfile.mkstemp(suffix=".torrent") + os.close(handle) + sent = [] + monkeypatch.setattr(plugin_download, "resolve", lambda item: path) + monkeypatch.setattr(deps, "add_magnet", lambda link, tag=None: sent.append(link)) + item = TorrentItem("t", "https://x.test/details/1", 1, plugin="/p.py") + assert session.send_magnet(item, lite_mode=False, json_mode=True) is True + assert sent == [path] and not os.path.exists(path) From 7e7371282a416746fc3226702a5c6fadcc44b47b Mon Sep 17 00:00:00 2001 From: Piratebird <141295458+Piratebird@users.noreply.github.com> Date: Tue, 3 Nov 2026 17:29:44 +0200 Subject: [PATCH 17/18] :shipit: fix(search): try split spellings on thin searches, soften REPACK, join rounded sizes - When a search finds fewer than 30 results, probe each long word split in two and also search the split that release names use, such as spider man for spiderman - Add search.spelling_variants to turn it off - Rank REPACK video releases lower instead of hiding them - Fold hashless results with a rounded size into the hashed copy with the same title --- CHANGELOG.md | 3 + README.md | 1 + src/helm/config/config_commands.py | 1 + src/helm/config/config_manager.py | 4 +- src/helm/config/settings.py | 1 + src/helm/search/query_variants.py | 77 ++++++++++++++++++++ src/helm/search/torrent_filter.py | 26 +++++++ src/helm/ui/tui.py | 113 ++++++++++++++++++----------- tests/test_query_variants.py | 84 +++++++++++++++++++++ tests/test_torrent_filter.py | 21 ++++++ 10 files changed, 287 insertions(+), 44 deletions(-) create mode 100644 src/helm/search/query_variants.py create mode 100644 tests/test_query_variants.py diff --git a/CHANGELOG.md b/CHANGELOG.md index b0f2ec8..eff8a41 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,7 @@ Headless services, layered TOML/JSONC settings with `config` commands, themes an - Respect the configured download directory and reject unknown flags, blank queries, and invalid content types. ### Added +- Spelling variants: when a search finds fewer than 30 results, Helm tries each long word split in two ("spiderman" as "spider man"), keeps a split only if probe results from Apibay and Torrents-csv contain the original word once punctuation is removed and outnumber the typed query at least twice, and then searches it too and merges the results. "spiderman brand new day" went from 6 results to 581. Turn it off with `search.spelling_variants = false` or `HELM_SPELLING_VARIANTS=false`. - qBittorrent plugin compatibility: `helpers` and `novaprinter` now match qBittorrent's nova3 API (`retrieve_url(url, custom_headers, request_data, ssl_context, unescape_html_entities)`, `download_file(url, referer)` returning `" "`, `headers`/`_headers`, `enable_socks_proxy`, `anySizeToBytes`, `SearchResults`). Your own plugins get the URL-encoded query, and when you pick a result whose link is not a magnet, the plugin's `download_torrent` runs in a child process with a 60-second timeout, falling back to Helm's own link resolver. By a static check of the 72 public plugins on qBittorrent's unofficial list, 59 should now load and run, up from about 30; the rest are Python 2 or need extra packages. - `init` now sets up 14 public Jackett indexers instead of 4, adding EZTV, LimeTorrents, TheRARBG, TorrentDownloads, TorrentDownload, TorrentProject, Knaben, uindex, Kickass and ExtraTorrent. Each was checked against a fresh Jackett with FlareSolverr. Prowlarr's first-search defaults use the same list. - `show:all` in the result filter lists the results that filters hid, marked `[HIDDEN]` with the reason, and the result header counts them. @@ -39,6 +40,8 @@ Headless services, layered TOML/JSONC settings with `config` commands, themes an - Standalone `uninstall.sh` for raw GitHub execution, with preview-by-default, selective removal and unit tests. ### Fixed +- `REPACK` no longer hides video results, since scene video releases use it too; it only ranks them lower. Game repacks are still caught by FitGirl, DODI, ElAmigos and similar keywords. +- Dedupe also joins a result that has no hash and a rounded size (such as LimeTorrents' "4.2 GB") to a hashed copy with the same title and a size within 2%. - Plugin results whose size was given in GiB/MiB/KiB/TiB, in lowercase, with thousands separators, or as a number were dropped; they are kept now, and a plugin's `pub_date` shows as the result date. - A plugin's second `retrieve_url` argument was sent as POST data instead of headers, and `download_file`'s referer was used as a file name. - Rerunning `init` no longer resets Jackett indexers you have already configured; only missing ones are added. YTS is set up at its current `yts.gg` link instead of the retired `yts.mx`. diff --git a/README.md b/README.md index 664d1ff..6150ef9 100644 --- a/README.md +++ b/README.md @@ -96,6 +96,7 @@ If a source times out (for example, `nyaa.si`), Helm keeps results from other co - Enter a nonempty, specific query. A request containing `q=` has an empty query; current Helm rejects blank interactive and CLI searches. - Use `helm-torrent logs` for recent source errors, or `HELM_VERBOSE=true helm-torrent search "artist album" --type music --lite --json` for verbose diagnostics on stderr. +- Sources match words literally, and release names often split names ("Spider-Man"). When a search finds little, Helm also tries the split spelling and prints `Also searched for ...`; set `search.spelling_variants = false` to turn this off. - If raw results exist but the final list is empty, check content filters and `search.min_seeds` in `config.toml` (default: 1). Use `helm-torrent paths` to locate it. Type `show:all` in the result filter to list hidden results with the reason each was hidden (`seeds`, `category` or `keyword:`). - Content types are mapped to plugin category keys when supported (video searches movies/TV/anime); general sources fall back to `all`. Inline feeds and unsupported categories still rely on local scoring/filtering. - A source summary on stderr distinguishes empty results from timeouts, HTTP failures, connection failures, and parse failures. Bundled plugins report swallowed failures; third-party plugins may need the `novaprinter.report_error` hook. Jobs whose queue budget expires are marked `budget_exhausted`; JSON stdout stays separate. diff --git a/src/helm/config/config_commands.py b/src/helm/config/config_commands.py index 55a1552..321f46d 100644 --- a/src/helm/config/config_commands.py +++ b/src/helm/config/config_commands.py @@ -37,6 +37,7 @@ "search.default_type": "Content profile used when none is given.", "search.indexer_manager": "Which manager to search: jackett, prowlarr or both.", "search.lite_only": "Always use Lite mode and skip the indexer managers.", + "search.spelling_variants": "When a search finds little, also try a long word split in two, such as spider man for spiderman.", "services.jackett": "Jackett web address.", "services.prowlarr": "Prowlarr web address.", "services.qbittorrent": "qBittorrent Web UI address.", diff --git a/src/helm/config/config_manager.py b/src/helm/config/config_manager.py index ab3181e..0f75d34 100644 --- a/src/helm/config/config_manager.py +++ b/src/helm/config/config_manager.py @@ -111,9 +111,9 @@ # Another category's keywords that are also normal in this category's release # names: video releases name their audio track (x264 AAC, XviD MP3, FLAC) and TV -# packs use "Ep 01-06". These only lower a result's rank instead of hiding it. +# packs use "Ep 01-06", and scene releases are re-released as REPACK. These only lower a result's rank instead of hiding it. WEAK_TERMS = { - "video": ["aac", "alac", "flac", "mp3", "ogg", "wav", "ep", "single"], + "video": ["aac", "alac", "flac", "mp3", "ogg", "wav", "ep", "single", "repack"], } diff --git a/src/helm/config/settings.py b/src/helm/config/settings.py index ea2e9ff..ada013e 100644 --- a/src/helm/config/settings.py +++ b/src/helm/config/settings.py @@ -71,6 +71,7 @@ class Field: choices=("both", "jackett", "prowlarr"), ), Field("search.lite_only", "bool", False, env="HELM_LITE_ONLY", legacy="LITE_MODE_ONLY"), + Field("search.spelling_variants", "bool", True, env="HELM_SPELLING_VARIANTS"), Field("services.jackett", "url", "http://localhost:19117", env="JACKETT_URL", legacy="JACKETT_URL"), Field("services.prowlarr", "url", "http://localhost:19696", env="PROWLARR_URL", legacy="PROWLARR_URL"), Field("services.qbittorrent", "url", "http://localhost:18080", env="QB_WEBUI", legacy="QB_WEBUI"), diff --git a/src/helm/search/query_variants.py b/src/helm/search/query_variants.py new file mode 100644 index 0000000..88b5fcf --- /dev/null +++ b/src/helm/search/query_variants.py @@ -0,0 +1,77 @@ +"""Find a better spelling when a one-word name is usually written as two. + +Search sources match words literally, and release names often split a name +that people type as one word: "spiderman" finds 6 results while "spider man" +finds hundreds of Spider-Man releases. When a search comes back thin, each long +word of the query is split at every position, each split is probed against two +fast sources, and a split wins only if its results contain the original word +once punctuation is removed (so "spider man" counts, "spi derman" does not) +and beat the query as typed. +""" + +import concurrent.futures +import re + +from helm.logger import get_logger + +logger = get_logger(__name__) + +THIN_RESULTS = 30 # fewer raw results than this triggers the variant probe +MIN_WORD = 6 # shorter words are rarely compounds and give too many splits +MIN_PART = 3 +MAX_CANDIDATES = 12 +MIN_GAIN = 2 # a variant must find at least twice as many matching results + + +def squash(text): + return re.sub(r"[^0-9a-z]+", "", (text or "").lower()) + + +def candidates(query): + """(word, split query) pairs: each long alphabetic word split once with a space.""" + words = query.split() + found = [] + for index, word in enumerate(words): + if len(word) < MIN_WORD or not word.isalpha(): + continue + for cut in range(MIN_PART, len(word) - MIN_PART + 1): + split = f"{word[:cut]} {word[cut:]}" + found.append((word, " ".join(words[:index] + [split] + words[index + 1 :]))) + return found[:MAX_CANDIDATES] + + +def _probe(query): + from helm.search.lite_fetcher import _fetch_apibay, _fetch_torrents_csv + + items = [] + for fetch in (_fetch_apibay, _fetch_torrents_csv): + try: + items.extend(fetch(query)) + except Exception: + logger.debug("Event: Variant probe failed for one source", exc_info=True) + return items + + +def matching(items, word, split_query): + """How many results contain *word* once punctuation is gone, and the rest of the query.""" + needed = [squash(word)] + [squash(w) for w in split_query.split() if squash(w) and squash(w) not in squash(word)] + return sum(1 for item in items if all(part in squash(getattr(item, "title", "")) for part in needed)) + + +def better_query(query, raw_count, probe=_probe, workers=6): + """Return a split spelling that finds clearly more, or None.""" + if raw_count >= THIN_RESULTS: + return None + options = candidates(query) + if not options: + return None + with concurrent.futures.ThreadPoolExecutor(max_workers=min(workers, len(options) + 1)) as pool: + baseline = pool.submit(probe, query) + probes = {variant: (word, pool.submit(probe, variant)) for word, variant in options} + base = len(baseline.result()) + scores = {variant: matching(future.result(), word, variant) for variant, (word, future) in probes.items()} + best = max(scores, key=lambda variant: scores[variant]) + if scores[best] >= max(MIN_GAIN * max(base, 1), 5): + logger.info("Event: Query %r also searched as %r (%s vs %s probe results)", query, best, scores[best], base) + return best + return None diff --git a/src/helm/search/torrent_filter.py b/src/helm/search/torrent_filter.py index 767a697..6b15398 100644 --- a/src/helm/search/torrent_filter.py +++ b/src/helm/search/torrent_filter.py @@ -204,4 +204,30 @@ def dedupe(items): groups = {} for item in items: groups.setdefault(dedupe_key(item), []).append(item) + _join_rounded_sizes(groups) return [group[0] if len(group) == 1 else _merge(group) for group in groups.values()] + + +SIZE_TOLERANCE = 0.02 + + +def _join_rounded_sizes(groups): + """Fold hashless results into a hashed one with the same title and nearly the same size. + + Sites that only show "4.2 GB" give a rounded size and no hash, so the exact + title-and-size key misses the copy another source reported precisely. + """ + by_title = {} + for key, group in groups.items(): + if key[0] == "hash": + for item in group: + by_title.setdefault(normalize_title(getattr(item, "title", "")), []).append((key, item)) + if not by_title: + return + for key in [k for k in groups if k[0] == "title"]: + title, size = key[1], key[2] + for target, item in by_title.get(title, ()): + other = getattr(item, "size", 0) or 0 + if other and abs(other - size) <= SIZE_TOLERANCE * max(other, size): + groups[target].extend(groups.pop(key)) + break diff --git a/src/helm/ui/tui.py b/src/helm/ui/tui.py index eb0f4d1..1c07e82 100644 --- a/src/helm/ui/tui.py +++ b/src/helm/ui/tui.py @@ -69,6 +69,69 @@ def format_size(size_bytes): return "????" +def _variant_for(query, raw_count): + """A split spelling worth searching too, when the search came back thin.""" + from helm.config.settings import ConfigError, load_settings + from helm.search.query_variants import better_query + + try: + if not load_settings().get("search.spelling_variants"): + return None + except ConfigError: + return None + try: + return better_query(query, raw_count) + except Exception: + return None + + +def _collect(query, content_type, lite_mode): + """Search Jackett/Prowlarr and Lite together (or Lite only) for one query.""" + from helm.search.rss_fetcher import SearchResults + + res = SearchResults() + used_lite = lite_mode + import concurrent.futures + + def fetch_jackett(): + from helm.search.rss_fetcher import search_indexers + + return search_indexers(query, content_type, fallback_lite=False) + + def fetch_lite(): + from helm.search.lite_fetcher import search_lite + + return search_lite(query, content_type) + + if not lite_mode: + jackett_future = None + lite_future = None + + with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor: + jackett_future = executor.submit(fetch_jackett) + lite_future = executor.submit(fetch_lite) + + try: + res.extend(jackett_future.result()) + except Exception as e: + print( + f"Indexer manager unavailable ({type(e).__name__}); using Lite results.", + file=sys.stderr, + ) + used_lite = True + + try: + res.extend(lite_future.result()) + except Exception as error: + from helm.search.rss_fetcher import SourceOutcome, source_status + + res.outcomes.append(SourceOutcome("Lite", source_status(error))) + else: + res.extend(fetch_lite()) + + return res, used_lite + + def animated_search(query, content_type, lite_mode=False, show_spinner=True): done = False @@ -88,54 +151,20 @@ def animate(): t = threading.Thread(target=animate) t.start() - from helm.search.rss_fetcher import SearchResults - - res = SearchResults() - used_lite = lite_mode + variant = None try: - import concurrent.futures - - def fetch_jackett(): - from helm.search.rss_fetcher import search_indexers - - return search_indexers(query, content_type, fallback_lite=False) - - def fetch_lite(): - from helm.search.lite_fetcher import search_lite - - return search_lite(query, content_type) - - if not lite_mode: - jackett_future = None - lite_future = None - - with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor: - jackett_future = executor.submit(fetch_jackett) - lite_future = executor.submit(fetch_lite) - - try: - res.extend(jackett_future.result()) - except Exception as e: - print( - f"Indexer manager unavailable ({type(e).__name__}); using Lite results.", - file=sys.stderr, - ) - used_lite = True - - try: - res.extend(lite_future.result()) - except Exception as error: - from helm.search.rss_fetcher import SourceOutcome, source_status - - res.outcomes.append(SourceOutcome("Lite", source_status(error))) - else: - res.extend(fetch_lite()) - + res, used_lite = _collect(query, content_type, lite_mode) + variant = _variant_for(query, len(res)) + if variant: + extra, _ = _collect(variant, content_type, lite_mode) + res.extend(extra) finally: done = True if t is not None: t.join() + if variant: + print(f"Also searched for '{variant}', the usual spelling in release names.", file=sys.stderr) if res.outcomes: summary = "; ".join(f"{o.source}: {o.status} ({o.count})" for o in res.outcomes) print(f"Sources: {summary}", file=sys.stderr) diff --git a/tests/test_query_variants.py b/tests/test_query_variants.py new file mode 100644 index 0000000..db0c14f --- /dev/null +++ b/tests/test_query_variants.py @@ -0,0 +1,84 @@ +from helm.search import query_variants +from helm.search.query_variants import better_query, candidates, matching +from helm.search.rss_fetcher import SearchResults, TorrentItem + + +def titles(*names): + return [TorrentItem(name, "magnet:?", 1) for name in names] + + +def test_candidates_split_only_long_alphabetic_words(): + found = [variant for _, variant in candidates("spiderman brand new day 2026")] + assert found == [ + "spi derman brand new day 2026", + "spid erman brand new day 2026", + "spide rman brand new day 2026", + "spider man brand new day 2026", + ] + assert candidates("brand new day") == [] and candidates("x264 1080p") == [] + + +def test_matching_counts_titles_that_still_contain_the_word(): + found = titles( + "Spider-Man Brand New Day 2026 1080p", "Spider.Man.Brand.New.Day.2160p", "Spider Woman Brand New Day" + ) + assert matching(found, "spiderman", "spider man brand new day") == 2 + assert matching(titles("Spi Derman and the Brand New Day"), "spiderman", "spi derman brand new day") == 1 + + +def probe_from(table): + return lambda query: table.get(query, []) + + +RELEASES = titles(*[f"Spider-Man.Brand.New.Day.2026.{n}.1080p" for n in range(40)]) + + +def test_better_query_picks_the_split_that_release_names_use(): + probe = probe_from( + {"spiderman brand new day": titles("Spiderman brand new day"), "spider man brand new day": RELEASES} + ) + assert better_query("spiderman brand new day", raw_count=6, probe=probe) == "spider man brand new day" + + +def test_better_query_stays_quiet_when_the_search_was_not_thin_or_nothing_wins(): + probe = probe_from({"spider man brand new day": RELEASES}) + assert better_query("spiderman brand new day", raw_count=300, probe=probe) is None + # A split must beat the typed query clearly, not just tie it. + even = probe_from({"batman begins": RELEASES[:10], "bat man begins": titles(*["Batman Begins"] * 12)}) + assert better_query("batman begins", raw_count=10, probe=even) is None + assert better_query("brand new day", raw_count=3, probe=probe) is None + + +def test_search_merges_the_variant_and_says_so(monkeypatch, capsys): + from helm.ui import tui + + queries = [] + + def collect(query, content_type, lite_mode): + queries.append(query) + return SearchResults(titles(query)), lite_mode + + monkeypatch.setattr(tui, "_collect", collect) + monkeypatch.setattr(tui, "_variant_for", lambda query, count: "spider man brand new day") + res, _ = tui.animated_search("spiderman brand new day", "video", lite_mode=True, show_spinner=False) + assert queries == ["spiderman brand new day", "spider man brand new day"] + assert [i.title for i in res] == queries + assert "Also searched for 'spider man brand new day'" in capsys.readouterr().err + + +def test_spelling_variants_can_be_turned_off(monkeypatch, tmp_path): + from helm.ui import tui + + monkeypatch.setenv("HELM_CONFIG_DIR", str(tmp_path)) + monkeypatch.setattr(query_variants, "better_query", lambda query, count: "spider man") + monkeypatch.setenv("HELM_SPELLING_VARIANTS", "false") + assert tui._variant_for("spiderman", 1) is None + monkeypatch.setenv("HELM_SPELLING_VARIANTS", "true") + assert tui._variant_for("spiderman", 1) == "spider man" + + +def test_repack_no_longer_hides_video(): + from helm.config.config_manager import NEGATIVE_KEYWORDS, WEAK_NEGATIVE_KEYWORDS + + assert "repack" not in NEGATIVE_KEYWORDS["video"] and "repack" in WEAK_NEGATIVE_KEYWORDS["video"] + assert "fitgirl" in NEGATIVE_KEYWORDS["video"] and "repack" in NEGATIVE_KEYWORDS["software"] diff --git a/tests/test_torrent_filter.py b/tests/test_torrent_filter.py index a845bbb..52eca41 100644 --- a/tests/test_torrent_filter.py +++ b/tests/test_torrent_filter.py @@ -139,3 +139,24 @@ def test_torrent_item_round_trips_through_worker_json(): item = TorrentItem("x", "http://l", 1, info_hash=HASH, sources=["A", "B"]) assert vars(TorrentItem(**json.loads(json.dumps(vars(item))))) == vars(item) + + +def test_dedupe_joins_a_rounded_size_copy_to_the_hashed_one(): + exact = TorrentItem( + "Movie.2026.1080p.WEBRip-Group", f"magnet:?xt=urn:btih:{HASH}", 3498, size=4_512_345_678, indexer="Apibay" + ) + rounded = TorrentItem( + "Movie 2026 1080p WEBRip Group", + "https://lime.test/movie.html", + 4174, + size=4_509_715_660, + indexer="LimeTorrents", + ) + far = TorrentItem( + "Movie 2026 1080p WEBRip Group", "https://lime.test/other.html", 9, size=2_000_000_000, indexer="LimeTorrents" + ) + unique = dedupe([exact, rounded, far]) + assert len(unique) == 2 + merged = unique[0] + assert merged.seeders == 4174 and merged.link.startswith("magnet:") and merged.indexer == "LimeTorrents +1" + assert unique[1].size == 2_000_000_000 From 1cda1972088de956afeefad14ac05bbe32c05a2d Mon Sep 17 00:00:00 2001 From: Piratebird <141295458+Piratebird@users.noreply.github.com> Date: Tue, 3 Nov 2026 17:48:01 +0200 Subject: [PATCH 18/18] :shipit: fix(ci): report a banner command's own timeout as timed out and run every Python version - Treat TimeoutExpired raised inside a banner module as a timeout, which failed the Python 3.8 run when the command's timeout fired just before the deadline - Set fail-fast to false so one Python version failing no longer cancels the others --- .github/workflows/ci.yml | 2 ++ CHANGELOG.md | 1 + src/helm/ui/banner.py | 3 +++ tests/test_theme_banner.py | 10 ++++++++++ 4 files changed, 16 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 83b4843..4c4d1b9 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -25,6 +25,8 @@ jobs: name: Run Python Tests runs-on: ubuntu-latest strategy: + # Report every Python version instead of cancelling the rest on the first failure. + fail-fast: false matrix: python-version: ["3.8", "3.9", "3.10", "3.11", "3.12"] steps: diff --git a/CHANGELOG.md b/CHANGELOG.md index eff8a41..418d420 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -40,6 +40,7 @@ Headless services, layered TOML/JSONC settings with `config` commands, themes an - Standalone `uninstall.sh` for raw GitHub execution, with preview-by-default, selective removal and unit tests. ### Fixed +- A banner command that hit its own timeout just before the banner deadline showed "unavailable" instead of "timed out"; it failed the Python 3.8 CI run. CI now runs every Python version to the end instead of cancelling the rest after one fails. - `REPACK` no longer hides video results, since scene video releases use it too; it only ranks them lower. Game repacks are still caught by FitGirl, DODI, ElAmigos and similar keywords. - Dedupe also joins a result that has no hash and a rounded size (such as LimeTorrents' "4.2 GB") to a hashed copy with the same title and a size within 2%. - Plugin results whose size was given in GiB/MiB/KiB/TiB, in lowercase, with thousands separators, or as a number were dropped; they are kept now, and a plugin's `pub_date` shows as the result date. diff --git a/src/helm/ui/banner.py b/src/helm/ui/banner.py index 12393d7..bca82d5 100644 --- a/src/helm/ui/banner.py +++ b/src/helm/ui/banner.py @@ -277,6 +277,9 @@ def run_with_deadline(functions, timeout): def work(index, function): try: results[index] = ("ok", function()) + except (subprocess.TimeoutExpired, TimeoutError): + # A command's own timeout equals the deadline, so it can fire first; it is still a timeout. + results[index] = ("timeout", None) except Exception: results[index] = ("error", None) diff --git a/tests/test_theme_banner.py b/tests/test_theme_banner.py index 373eb26..356da5e 100644 --- a/tests/test_theme_banner.py +++ b/tests/test_theme_banner.py @@ -207,6 +207,16 @@ def fail(): assert results == {0: ("ok", 1), 1: ("error", None), 2: ("timeout", None)} +def test_a_timeout_raised_inside_a_module_counts_as_timed_out(): + # Python 3.8 on CI: the command's own subprocess timeout fired before the deadline. + import subprocess + + def expired(): + raise subprocess.TimeoutExpired(["slow"], 1.5) + + assert run_with_deadline([expired], 1) == {0: ("timeout", None)} + + def test_custom_modules_and_separator(home): modules = [ {"type": "command", "label": "Hello", "command": python_command("print('\\n\\x1b[1mhi there\\x1b[0m')")},