From 5683f3935658ec92257a3fd504e1e916cf433a76 Mon Sep 17 00:00:00 2001 From: Elisha Lucero Date: Thu, 16 Jul 2026 01:22:16 -0500 Subject: [PATCH] fix: make Chaptarr book requests converge safely --- CHANGELOG.md | 50 + Cargo.lock | 2 +- Cargo.toml | 2 +- README.md | 30 +- docs/chaptarr/COMPATIBILITY.md | 140 +- docs/chaptarr/RELEASE_CHECKLIST.md | 37 +- doplarr/src/providers/chaptarr.rs | 1479 ++++++++++++++++- doplarr/src/providers/chaptarr/models.rs | 13 + doplarr/src/providers/chaptarr/selection.rs | 880 +++++++++- .../fixtures/chaptarr/edition_formats.json | 35 + 10 files changed, 2529 insertions(+), 139 deletions(-) create mode 100644 doplarr/tests/fixtures/chaptarr/edition_formats.json diff --git a/CHANGELOG.md b/CHANGELOG.md index 23b523b..42cc28e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,56 @@ All notable changes to DoplarrChaptarr Rust are documented here. +## 4.6.1-chaptarr.1 - Unreleased + +Fixes the new-author request failure observed live on 2026-07-15. The old bot +accepted a Farseer collection row while Robin Hobb's catalog was still +refreshing, monitored and searched that bundle too early, and still reported +success when that `BookSearch` completed with zero results. It had not selected +a usable ebook edition, and the import tail later removed the partial monitor +state. + +### Fixed + +- New-author requests now wait for the catalog import to settle before any + monitoring. The gate requires successful command polling, no author-relevant + catalog command in flight, and stable book and target-edition state; an API + error or deadline fails closed. The same wait runs after any bot-issued + `RefreshAuthor`. +- Requests now select exactly one edition of the requested format (preferring + English and the projected edition) via the full-book `PUT /book/{id}` with + `anyEditionOk: false` and `manualAdd`, mirroring the Chaptarr UI. Edition truth + is read exclusively from `GET /edition?bookId=...`; its authoritative + `format` distinguishes Ebook, Physical, and Audiobook so a physical edition + cannot be mistaken for an audiobook. +- This remains a single-work request flow. Results with clear multi-book title + signals - such as a title ending in `bundle` or `trilogy`, an `omnibus`, a box + set, a `complete ... series`, or an explicit numbered book collection/set - + are rejected with an instruction to request each individual title. The bot + does not expand one selection into many works. +- Duplicate import pockets (two local rows for one work, logged server-side as + `SERVER-BUG-CANDIDATE`) are disambiguated by which row actually carries + usable requested-format editions, and only that row is monitored. + Already-requested checks now span every matching row so an available or + in-flight twin stops a duplicate request. An exact active `BookSearch` and a + recent valid acknowledgement retained by the same bot process are also + deduplicated. +- The pre-search read-back now verifies the book is monitored AND its explicit + requested-format flag is true, and that exactly one requested-format edition + - the chosen one - is monitored before `BookSearch` is queued. A matching + work with no usable edition fails with an actionable message. +- Retries now distinguish an available, grabbed, actively searched, or + same-process recently acknowledged request from a partial monitor state. A + prior edition/monitor write without that search evidence is repaired through + the same verified sequence instead of being rejected as "already requested." + This deduplication is deliberately bounded: after a bot restart, or after a + search completes with no grab or file, an explicit retry may queue a fresh + search instead of leaving a zero-result request permanently blocked. + +This write-path change still requires the exact candidate image to pass the +disposable live mutation checklist before merge or release; fixtures and CI +cannot prove that private Chaptarr writes persist. + ## 4.6.0-chaptarr.1 - Unreleased This is a beta release candidate. Chaptarr's API is private and pre-1.0, and diff --git a/Cargo.lock b/Cargo.lock index 6ca322e..5364aa9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -368,7 +368,7 @@ dependencies = [ [[package]] name = "doplarr" -version = "4.6.0-chaptarr.1" +version = "4.6.1-chaptarr.1" dependencies = [ "anyhow", "async-trait", diff --git a/Cargo.toml b/Cargo.toml index 1720b06..45e5f64 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,7 +3,7 @@ members = ["doplarr", "radarr_api", "sonarr_api", "seerr_api"] resolver = "3" [workspace.package] -version = "4.6.0-chaptarr.1" +version = "4.6.1-chaptarr.1" edition = "2024" license = "GPL-3.0-only" authors = ["Elisha Lucero "] diff --git a/README.md b/README.md index b1b1e5b..4fe801d 100644 --- a/README.md +++ b/README.md @@ -19,6 +19,8 @@ binary beta; releases remain gated by the disposable Chaptarr checklist below. Each backend creates a `/request ` slash command. Chaptarr adds the same two public commands as the old fork: `/request book` and `/request audiobook`. +Each interaction requests one work. The bot does not expand a trilogy or series +query into multiple books; select an individual title for each request. ## Screenshots @@ -207,6 +209,30 @@ not add an author or book; Chaptarr is mutated only after the requester presses bounded Open Library fallback, but remain best-effort: a request must still work when a cover host is unavailable or a title has no usable image. +A request only reports success after Chaptarr confirms it is actionable. For an +author new to Chaptarr, the bot first waits for successful command checks, no +catalog command in flight, and stable book and target-edition state. A polling +error or deadline stops the request before any monitor/search work and tells the +requester to retry later. + +The bot rejects results whose titles carry clear multi-book signals - for +example, a title ending in `bundle` or `trilogy`, an `omnibus`, a box set, a +`complete ... series`, or an explicit numbered book collection/set - and asks +for an individual title. It does not reject a legitimate single-work title +merely because it contains a word such as `collection` or `series`. For a +single work, it chooses the best duplicate row, uses the +authoritative edition `format` to keep Ebook, Physical, and Audiobook distinct, +and selects exactly one requested-format edition. It then verifies both the +book monitor and the explicit format monitor plus the chosen edition before +queueing `BookSearch`. + +Retries use bounded deduplication. An exact queued/started `BookSearch`, a grab, +an available file, or a recent valid acknowledgement retained by the same bot +process stops an immediate duplicate. A partial edition/monitor state without +that evidence is repaired. After the bot restarts, or after a search completes +with no grab or file, an explicit retry may intentionally queue a fresh search +so a zero-result request is not blocked forever. + `openlibrary_covers` defaults to `true`. When enabled, a search whose Chaptarr results lack usable covers sends the search text to Open Library's public Search API. Results are cached and globally rate-limited. Set it to `false` on both @@ -226,7 +252,9 @@ sequence are documented in **[docs/chaptarr/COMPATIBILITY.md](docs/chaptarr/COMPATIBILITY.md)**. Maintainers should complete the **[beta release checklist](docs/chaptarr/RELEASE_CHECKLIST.md)** before -publishing against a new Chaptarr version. +merging or publishing any Chaptarr write-path change. The checklist includes an +exact-image disposable live write canary because fixture tests cannot prove +that Chaptarr persisted a private-API mutation. ## Running as a Service diff --git a/docs/chaptarr/COMPATIBILITY.md b/docs/chaptarr/COMPATIBILITY.md index deb1ba7..25566bc 100644 --- a/docs/chaptarr/COMPATIBILITY.md +++ b/docs/chaptarr/COMPATIBILITY.md @@ -23,13 +23,16 @@ put it in a URL, log line, fixture, or Discord response. | `GET` | `/author` | Resolve an already-local author | `id`, `foreignAuthorId`, `authorName` | | `GET` | `/author/{id}` | Read and verify the requested-format author gate | `id`, `ebookMonitorFuture`, `audiobookMonitorFuture` | | `GET` | `/book?authorId=...` | Poll and rank local format rows | fields listed under "Book rows" | -| `GET` | `/book/{id}` | Verify status and monitor writes | fields listed under "Book rows" | +| `GET` | `/book/{id}` | Verify status and monitor writes; its `editions` array is always empty and never edition truth | fields listed under "Book rows" | +| `GET` | `/edition?bookId=...` | The only source of local edition truth | `id`, authoritative `format`, `monitored`; language, title, and identifiers when present | +| `GET` | `/command` | Detect in-flight catalog commands while a new author's import settles | `name`, `status`; `body.authorId`/`body.authorIds` when present | | `GET` | `/qualityprofile` | Resolve per-format quality profiles | `id`, `name`, `profileType` | | `GET` | `/metadataprofile` | Resolve per-format metadata profiles | `id`, `name`, `profileType` | | `GET` | `/rootfolder` | Resolve accessible roots | `id`, `path`; `accessible` when present | | `POST` | `/book` | Add a new author/catalog or an exact work under an existing author | created book row with `authorId`, or enough identity to re-resolve it | | `PUT` | `/author/{id}` | Enable one format's author-level monitor gate | response is not trusted; verify with `GET` | -| `PUT` | `/book/monitor` | Monitor one selected book row | HTTP success only; verify with `GET /book/{id}` | +| `PUT` | `/book/{id}` | Select exactly one edition via the complete book body; monitor flags in this body are silently ignored | response is not trusted; verify with `GET /edition?bookId=...` | +| `PUT` | `/book/monitor` | Monitor one selected book row (the only book-level monitor write that persists) | HTTP success only; verify with `GET /book/{id}` | | `POST` | `/command` | Queue one `BookSearch`, or a narrowly gated `RefreshAuthor` | command acknowledgement; the body is otherwise opaque | Unknown response fields must be ignored. Fields used only for ranking or @@ -52,8 +55,9 @@ result. - `images`, `remoteCover`, and edition-level `images`. - `localEbookBooks` and `localAudiobookBooks`. Positive IDs in the array for the requested format are a better local shortcut than the top-level `id`. -- `editions`, which may carry `foreignEditionId`, `isEbook`, `isbn13`, `asin`, - language, and additional cover images. +- `editions`, which may carry projected `foreignEditionId`, `isEbook`, + `isbn13`, `asin`, language, and additional cover images. These lookup fields + are discovery hints, not authoritative local-edition format state. Lookup order is not stable and is not a ranking guarantee. Never use a local audiobook ID to satisfy an ebook request, or the reverse. @@ -112,8 +116,12 @@ For the requested format, status is evaluated in this order: 1. **Available:** matching row has `hasFiles: true`, or its matching statistics report a positive `bookFileCount`. -2. **Already requested:** matching row has `grabbed: true` or is monitored. -3. **Unmonitored:** neither condition is true. +2. **Active or recently acknowledged request:** the matching row is grabbed, + or a monitor flag is present and an exact `BookSearch` is queued/started, or + the same bot process retains a recent valid acknowledgement for that row. +3. **Partial request:** one or more monitor/edition writes exist without the + full verified state or a confirmed search. A retry repairs this state. +4. **Unmonitored:** none of those conditions is true. Where per-format legacy fields exist, use only the pair belonging to the requested format. Prefer the row-oriented `0.9.720.0` fields when `mediaType` @@ -136,6 +144,47 @@ resolves, report a metadata-pending error; do not search a sibling work. target remains a placeholder. It is not a general retry: refresh can reapply metadata-profile filters and remove editions. +### Editions, duplicate pockets, and catalog settling + +The following behaviors were confirmed by hand against live Chaptarr +`0.9.720.0` during the 2026-07-15 new-author incident repair. Each one can make +a naive request pipeline fail silently or appear to work: + +The incident was not a missing `BookSearch` call: the old path queued a search +for a Farseer collection row while Robin Hobb's catalog refresh was still in +flight, and that search returned zero results. The row had no selected usable +ebook edition, and later refresh work removed its partial monitor state. + +- `GET /book/{id}` (and the `/book?authorId=...` rows) always report + `"editions": []`. Edition truth comes only from `GET /edition?bookId={id}`. + Verifying "does this book have editions?" through the book resource wrongly + concludes there are none. +- `PUT /book/{id}` silently ignores `monitored` and the per-format monitor + flags: no error is returned and the flags stay false. Book-level monitoring + persists only through `PUT /book/monitor` with + `{"bookIds": [...], "monitored": true}`. +- Edition selection does persist through the full-book `PUT /book/{id}`: send + the complete book body plus `anyEditionOk: false` and the full `editions` + array with exactly one edition `monitored: true` and `manualAdd: true`, + mirroring the Chaptarr UI's manual pick. +- Local edition `format` is authoritative. Select Ebook only for an ebook + request and Audiobook only for an audiobook request. Physical is a separate + value and must never be inferred to mean Audiobook merely because a legacy + `isEbook` flag is false or missing. +- New-author imports can duplicate one work into multiple local rows + ("pockets", logged server-side as `[SERVER-BUG-CANDIDATE] ... provider id(s) + appearing in multiple pockets`). The pockets are not equivalent: one row can + carry many usable requested-format editions while its twin carries none. + Requests must choose the row with usable requested-format editions and + monitor only that row, and already-requested checks must span every matching + row rather than one preferred row. +- Catalog population after adding an author is not instantaneous. A 400+ book + author imports and refreshes for minutes, and monitor or edition writes made + before the catalog settles can be silently reverted by the tail of that + import. Require successful command polls, no author-relevant command in + flight, and stable book plus target-edition fingerprints before mutating. + Command/API errors and the deadline fail closed. + ## Search and selection invariants Search should be useful without becoming inventive: @@ -150,10 +199,17 @@ Search should be useful without becoming inventive: 4. Prefer exact normalized title matches, then narrowly allow subtitle variants separated by `:`, `-`, `—`, or parentheses. A plain shared prefix is not a match. Never cross authors after the user has selected one. -5. Within that title tier, prefer an explicit requested `mediaType`, a resolved +5. This provider requests one work per Discord interaction. Reject results with + clear multi-book title signals - such as a title ending in `bundle` or + `trilogy`, an `omnibus`, a box set, a `complete ... series`, or an explicit + numbered book collection/set - with an instruction to request an individual + title. A bare word such as `collection` or `series` is not sufficient because + it can be part of a legitimate single-work title. Do not silently expand one + selection into multiple works or substitute a bundle for its members. +6. Within that title tier, prefer an explicit requested `mediaType`, a resolved row, and a title whose length is closest to the selected lookup title. Popularity, votes, and release date are final tie-breakers. -6. If no row matches the selected title and format, stop. Falling back to a +7. If no row matches the selected title and format, stop. Falling back to a popular sibling title requests the wrong book. Provider IDs are hints, not universal identity. Lookup may return a Goodreads @@ -214,8 +270,9 @@ verifying every silent-write-prone step is more important than minimizing GETs. fetch no cover bytes and perform no write. 3. Let the user select a result, format-specific options, and explicit Request confirmation. Disable the Request button immediately after the click. -4. Re-resolve the selected lookup identity. Read local author/book state and - short-circuit available or already-requested rows before changing an author. +4. Re-resolve the selected lookup identity. Short-circuit an available work or + a fully consistent active request. Do not treat a bare monitor flag as proof + that a search was queued; carry partial state forward for repair. 5. If the author is new, `POST /book` with both roots, all four profile IDs, an explicit requested `mediaType`, every book-level monitor flag false, only the requested format's author-level `*MonitorFuture` gate true, and @@ -223,26 +280,53 @@ verifying every silent-write-prone step is more important than minimizing GETs. the exact work does not, post the selected work with that local `authorId`. A post response is only an acknowledgement and never implies that a usable or correctly identified row already exists. -6. Poll `GET /book?authorId=...` with a bounded deadline. Select only the exact +6. After a new-author add (and after any `RefreshAuthor` the bot itself + queues), wait for the catalog to settle before any further step. Require + successful `GET /command` samples with no queued/started command that could + touch the author, plus unchanged book and target-edition fingerprints across + consecutive samples, all within a hard deadline. A command/API error or + timeout fails closed before monitoring or search. +7. Poll `GET /book?authorId=...` with a bounded deadline. Reject a result with a + clear multi-book title signal and tell the requester to search for an + individual title. Otherwise select only the exact title/author/requested-format row; when both sides expose `foreignBookId`, it must match. Require a resolved row and repeat the identity check immediately before monitoring and after the monitor read-back. -7. Read the author. If the requested format's `*MonitorFuture` gate is false, +8. Re-resolve edition-aware: fetch `GET /edition?bookId=...` for every matching + row, disambiguate duplicate pockets by usable requested-format editions, and + use authoritative local `format` to choose one Ebook or Audiobook edition + (with preferred language). Physical is not an audiobook fallback. A matching + row without a usable requested-format edition stops with an actionable error. +9. Read the author. If the requested format's `*MonitorFuture` gate is false, set only that gate (plus the required top-level `monitored` field), then re-read the author to verify it. -8. `PUT /book/monitor` with one ID: `{"bookIds":[id],"monitored":true}`. -9. Re-read `/book/{id}` and verify the requested-format monitor state. If it did - not persist, stop and do not queue a search. -10. `POST /command` once with `{"name":"BookSearch","bookIds":[id]}`. -11. Treat retries as idempotent: re-read status first, never create duplicate - authors, and never queue multiple searches from one Discord interaction. - -The existing-author exact-work POST is based on the current Moonrock Helper -integration and sanitized fixture shapes, not a write test against Chaptarr -`0.9.720.0` performed for this release. The request uses an explicit allowlist -and keeps all book and edition monitor flags false. It remains beta until a -disposable-library write/read-back test proves that shape on a published -Chaptarr build. +10. Select the edition with the full-book `PUT /book/{id}`: complete book body, + `anyEditionOk: false`, and the full editions array carrying exactly one + edition with `monitored: true` and `manualAdd: true`. +11. `PUT /book/monitor` with one ID: `{"bookIds":[id],"monitored":true}`. +12. Re-read `/book/{id}` and `/edition?bookId=...` and verify all of: the row + still matches the selected work, top-level `monitored` is true, the explicit + requested-format monitor flag is true, and exactly one requested-format + edition - the chosen one - is monitored. These are AND conditions. If any + did not persist, stop and do not queue a search. +13. `POST /command` once with `{"name":"BookSearch","bookIds":[id]}` and + require a valid command acknowledgement. Only then may the requester be + told the request was accepted; acceptance does not promise an indexer match. +14. Treat retries as convergent with bounded deduplication. Re-read all matching + pockets; stop for an available file, grab, exact queued/started `BookSearch`, + or a recent valid acknowledgement retained by the same bot process. Repair a + partial edition or monitor state that lacks that evidence through steps + 8-13. Never create duplicate authors or queue a second concurrent/immediate + search. A restart clears the in-process acknowledgement, and a completed + zero-result search has no grab or file; an explicit retry in either case may + intentionally queue a fresh search rather than block the request forever. + +The request uses an explicit allowlist and starts all book and edition monitor +flags false. Every write-path change remains beta until the exact candidate +image passes a disposable-library live canary covering new-author settle, clear +multi-book rejection, edition selection, strict read-back, partial-state retry, +and `BookSearch` acknowledgement. Sanitized fixtures and read-only evidence +cannot prove that a private Chaptarr mutation still persists. Network calls need explicit connect and total-request timeouts. Polling needs a deadline and cancellation when the Discord interaction is no longer usable. @@ -343,8 +427,10 @@ Compatibility is maintained as follows: - Before claiming support for a new release, run read-only lookup/detail, profile, root, and status probes; sanitize any new shapes; update these fixtures; and run contract tests. -- A write-path change also requires a disposable or explicitly approved live - request test. Read-only evidence cannot prove a mutation still persists. +- A write-path change also requires the exact candidate image to pass the + disposable live canary in `RELEASE_CHECKLIST.md`. Record its commit, image + digest, Chaptarr version, results, and rollback artifact. Read-only evidence + cannot prove a mutation still persists. - Never regenerate a broad Readarr client from an unrelated OpenAPI document. Chaptarr is Readarr-like, but its format-specific fields and monitor behavior are the reason this narrow contract exists. diff --git a/docs/chaptarr/RELEASE_CHECKLIST.md b/docs/chaptarr/RELEASE_CHECKLIST.md index 36781c6..5257102 100644 --- a/docs/chaptarr/RELEASE_CHECKLIST.md +++ b/docs/chaptarr/RELEASE_CHECKLIST.md @@ -4,11 +4,18 @@ Use this checklist before publishing a DoplarrChaptarr build against a new Chaptarr version. Chaptarr's API is private and pre-1.0, so unit fixtures prove the client contract but cannot prove that writes still persist. +The Chaptarr provider is a single-work flow. This checklist does not approve +automatic series expansion. Results with clear multi-book title signals - such +as a title ending in `bundle` or `trilogy`, an `omnibus`, a box set, a +`complete ... series`, or an explicit numbered book collection/set - must be +rejected with an instruction to request individual titles. + ## Preconditions - Use a disposable Chaptarr instance or a disposable author/library root. Do not run mutation tests against a family production library. -- Record the exact DoplarrChaptarr commit, Chaptarr version and container digest. +- Record the exact DoplarrChaptarr commit, candidate-image digest, Chaptarr + version and Chaptarr container digest. Test that exact candidate image. - Back up Chaptarr's database and configuration and verify the restore path. - Use synthetic or explicitly approved test books in both formats. - Keep Open Library enrichment disabled if test search text must remain local. @@ -45,16 +52,36 @@ Run each case once and inspect Chaptarr after every step: 2. Request an audiobook for a different new author. 3. Request an exact missing work under an already-local author. 4. Request the other format for a work whose first format is already local. -5. Repeat one request concurrently from two Discord users. +5. Repeat one request concurrently from two Discord users, then repeat it once + immediately after a valid acknowledgement in the same bot process. +6. Select a result with a clear multi-book signal and press **Request**; verify + the bot names the single-work limitation and makes no mutation. +7. In the disposable instance, prepare a partial state with the chosen edition + and book monitored but no confirmed `BookSearch`, then repeat the request. +8. Inject or simulate a failed command poll during new-author settling and + verify the request fails closed before edition, monitor, or search writes. +9. Complete a search with zero results and no grab/file, or restart the bot after + its recent acknowledgement is lost, then explicitly retry; verify at most one + fresh search is queued by that new attempt. For every case, verify: - the selected title, author, `foreignBookId` when present and `mediaType` match; - no sibling work or unrequested edition was monitored; +- authoritative edition `format` matches the requested format, and a Physical + edition is never selected for an audiobook request; - the unrequested format's author gate did not change; -- the selected row became monitored and was read back successfully; -- exactly one `BookSearch` was queued; -- a second/concurrent request did not create a duplicate or queue another search; +- top-level book monitoring AND the explicit requested-format monitor flag were + both read back true; +- exactly one requested-format edition was monitored and matched the chosen ID; +- exactly one acknowledged `BookSearch` was queued after strict read-back; +- a concurrent request, exact active `BookSearch`, and immediate same-process + retry after a valid acknowledgement did not queue another search; +- a retry repaired partial state instead of reporting it already requested; +- after restart or a completed zero-result/no-grab search, an explicit retry may + queue one fresh search and does not queue more than one for that attempt; +- settle polling errors/timeouts produced a clear failure and no downstream + mutation; - a missing exact row did not queue `RefreshAuthor`; - an exact unresolved placeholder may queue at most one `RefreshAuthor`, and a still-unresolved row never reaches `BookSearch`. diff --git a/doplarr/src/providers/chaptarr.rs b/doplarr/src/providers/chaptarr.rs index 41b0c56..b3a609e 100644 --- a/doplarr/src/providers/chaptarr.rs +++ b/doplarr/src/providers/chaptarr.rs @@ -33,9 +33,13 @@ const API_PREFIX: &str = "/api/v1"; const OPEN_LIBRARY_SEARCH: &str = "https://openlibrary.org/search.json"; const RESOLVE_ATTEMPTS: usize = 20; const RESOLVE_DEADLINE: Duration = Duration::from_secs(25); +/// Consecutive identical book-list samples (with no catalog command in +/// flight) required before a freshly imported catalog counts as settled. +const SETTLE_STABLE_SAMPLES: usize = 3; const OPEN_LIBRARY_MIN_INTERVAL: Duration = Duration::from_secs(1); const OPEN_LIBRARY_CACHE_TTL: Duration = Duration::from_secs(6 * 60 * 60); const OPEN_LIBRARY_CACHE_CAPACITY: usize = 128; +const RECENT_SEARCH_ACK_TTL: Duration = Duration::from_secs(120); const OPEN_LIBRARY_USER_AGENT: &str = concat!( "DoplarrChaptarr/", env!("CARGO_PKG_VERSION"), @@ -51,6 +55,7 @@ struct OpenLibraryState { static OPEN_LIBRARY_STATE: OnceLock> = OnceLock::new(); static CHAPTARR_MUTATION_LOCKS: OnceLock>>>> = OnceLock::new(); +static CHAPTARR_RECENT_SEARCHES: OnceLock>> = OnceLock::new(); fn open_library_state() -> &'static Mutex { OPEN_LIBRARY_STATE.get_or_init(|| Mutex::new(OpenLibraryState::default())) @@ -60,6 +65,10 @@ fn mutation_locks() -> &'static Mutex>>> { CHAPTARR_MUTATION_LOCKS.get_or_init(|| Mutex::new(HashMap::new())) } +fn recent_searches() -> &'static Mutex> { + CHAPTARR_RECENT_SEARCHES.get_or_init(|| Mutex::new(HashMap::new())) +} + #[derive(Clone)] pub struct Chaptarr { client: reqwest::Client, @@ -69,6 +78,52 @@ pub struct Chaptarr { format: ChaptarrFormat, openlibrary_covers: bool, settings: ResolvedSettings, + settle: SettlePacing, +} + +/// Pacing for the new-author catalog-settle wait. A 400+ book author takes +/// real time to import; any monitor or edition work done before the catalog +/// settles can be silently reverted by the tail of that import. +#[derive(Debug, Clone)] +struct SettlePacing { + interval: Duration, + deadline: Duration, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +struct CatalogFingerprint { + books: Vec, + targets: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] +struct TargetFingerprint { + book_id: i64, + complete: bool, + release_date: String, + foreign_edition_id: String, + editions: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] +struct EditionFingerprint { + id: String, + foreign_edition_id: String, + format: String, + is_ebook: Option, + language: String, + title: String, + isbn13: String, + asin: String, +} + +impl Default for SettlePacing { + fn default() -> Self { + Self { + interval: Duration::from_secs(2), + deadline: Duration::from_secs(240), + } + } } #[derive(Debug, Clone)] @@ -120,6 +175,7 @@ impl Chaptarr { server_version: String::new(), format, openlibrary_covers: openlibrary_covers.unwrap_or(true), + settle: SettlePacing::default(), settings: ResolvedSettings { ebook_root: String::new(), audiobook_root: String::new(), @@ -365,7 +421,24 @@ impl Chaptarr { self.get(&format!("/book/{id}"), &[]).await } - async fn locate_existing(&self, item: &ChaptarrItem) -> Result<(Option, Option)> { + /// The book resource always reports `"editions": []`; this endpoint is the + /// only source of edition truth and every edition read must go through it. + async fn editions_for_book(&self, book_id: i64) -> Result> { + self.get("/edition", &[("bookId", book_id.to_string())]) + .await + } + + async fn commands(&self) -> Result> { + self.get("/command", &[]).await + } + + /// Locate the local author, the preferred matching book row, and every + /// book row of that author. The full row set matters because duplicate + /// import pockets can hold the requested work's real state on a twin row. + async fn locate_existing( + &self, + item: &ChaptarrItem, + ) -> Result<(Option, Option, Vec)> { if let Some(id) = item.existing_book_id { let book = self.get_book(id).await?; if local_row_matches_item(&book, self.format, &item.book) { @@ -375,7 +448,14 @@ impl Chaptarr { } else { self.find_author(item).await? }; - return Ok((author, Some(book))); + let rows = if let Some(author_id) = + author.as_ref().and_then(|a| positive_id(a.get("id"))) + { + self.books_for_author(author_id).await? + } else { + vec![book.clone()] + }; + return Ok((author, Some(book), rows)); } warn!( book_id = id, @@ -385,11 +465,11 @@ impl Chaptarr { } let author = self.find_author(item).await?; let Some(author_id) = author.as_ref().and_then(|a| positive_id(a.get("id"))) else { - return Ok((None, None)); + return Ok((None, None, Vec::new())); }; let rows = self.books_for_author(author_id).await?; let book = preferred_book(&rows, self.format, &item.book); - Ok((author, book)) + Ok((author, book, rows)) } async fn poll_target(&self, author_id: i64, selected: &BookShape) -> Result> { @@ -416,6 +496,233 @@ impl Chaptarr { } } + async fn catalog_fingerprint( + &self, + rows: &[Value], + selected: &BookShape, + require_target: bool, + ) -> Result> { + let matching: Vec<_> = rows + .iter() + .filter(|row| local_row_matches_item(row, self.format, selected)) + .collect(); + if require_target && !matching.iter().any(|target| book_complete(target)) { + return Ok(None); + } + let mut targets = Vec::new(); + for row in matching { + let Some(book_id) = positive_id(row.get("id")) else { + continue; + }; + let mut editions = self + .editions_for_book(book_id) + .await? + .iter() + .map(|edition| EditionFingerprint { + id: edition.get("id").map(Value::to_string).unwrap_or_default(), + foreign_edition_id: string_at(edition, "foreignEditionId").to_string(), + format: string_at(edition, "format").to_ascii_lowercase(), + is_ebook: edition.get("isEbook").and_then(Value::as_bool), + language: string_at(edition, "language").to_ascii_lowercase(), + title: string_at(edition, "title").to_string(), + isbn13: string_at(edition, "isbn13").to_string(), + asin: string_at(edition, "asin").to_string(), + }) + .collect::>(); + editions.sort(); + targets.push(TargetFingerprint { + book_id, + complete: book_complete(row), + release_date: string_at(row, "releaseDate").to_string(), + foreign_edition_id: string_at(row, "foreignEditionId").to_string(), + editions, + }); + } + targets.sort(); + Ok(Some(CatalogFingerprint { + books: book_list_fingerprint(rows), + targets, + })) + } + + /// Block until an author's catalog stops moving: no queued/running + /// command that could touch this author, and an unchanged book list plus + /// target-edition snapshot across consecutive samples. Monitoring or + /// edition selection performed before this point can be silently reverted + /// by the tail of the import, which is exactly the failure that strands a + /// request. + async fn wait_for_catalog_settle( + &self, + author_id: i64, + author_name: &str, + selected: &BookShape, + require_target: bool, + ) -> Result<()> { + let started = Instant::now(); + let deadline = started + self.settle.deadline; + let mut previous_fingerprint = None; + let mut stable_samples = 0_usize; + loop { + let commands = match self.commands().await { + Ok(commands) => commands, + Err(error) => { + warn!(author_id, %error, "Could not poll Chaptarr commands during settle"); + // Unknown command state is never equivalent to idle. A + // failed poll invalidates the entire quiet window. + stable_samples = 0; + previous_fingerprint = None; + if Instant::now() + self.settle.interval > deadline { + break; + } + sleep(self.settle.interval).await; + continue; + } + }; + let busy = catalog_command_active(&commands, author_id); + if busy { + stable_samples = 0; + previous_fingerprint = None; + } else { + let rows = self.books_for_author(author_id).await?; + let fingerprint = if rows.is_empty() && require_target { + None + } else { + self.catalog_fingerprint(&rows, selected, require_target) + .await? + }; + if let Some(fingerprint) = fingerprint { + if previous_fingerprint.as_ref() == Some(&fingerprint) { + stable_samples += 1; + } else { + stable_samples = 1; + } + previous_fingerprint = Some(fingerprint); + if stable_samples >= SETTLE_STABLE_SAMPLES { + info!( + author_id, + books = rows.len(), + elapsed_secs = started.elapsed().as_secs(), + "Chaptarr catalog settled" + ); + return Ok(()); + } + } else { + stable_samples = 0; + previous_fingerprint = None; + } + } + if Instant::now() + self.settle.interval > deadline { + break; + } + sleep(self.settle.interval).await; + } + warn!( + author_id, + "Chaptarr catalog never settled before the deadline" + ); + bail!(UserFacingError(format!( + "Chaptarr is still importing {author_name}'s catalog, so this request was NOT completed. Nothing was monitored or searched yet - please request it again in a few minutes." + ))); + } + + /// Resolve the one local row to monitor, edition-aware. Duplicate import + /// pockets for the same work are disambiguated by which row actually has + /// usable requested-format editions (read from `/edition`, never from the + /// book resource, which always reports an empty editions array). + async fn resolve_pocket( + &self, + author_id: i64, + selected: &BookShape, + ) -> Result)>> { + let rows = self.books_for_author(author_id).await?; + let mut candidates = Vec::new(); + for row in rows { + if !local_row_matches_item(&row, self.format, selected) { + continue; + } + let editions = match positive_id(row.get("id")) { + Some(id) => self.editions_for_book(id).await?, + None => Vec::new(), + }; + candidates.push((row, editions)); + } + if candidates.len() > 1 { + warn!( + author_id, + pockets = candidates.len(), + foreign_book_id = %selected.foreign_book_id, + "Duplicate Chaptarr pockets for one work; selecting by usable editions" + ); + } + let Some(index) = preferred_pocket(&candidates, self.format, selected) else { + return Ok(None); + }; + Ok(Some(candidates.swap_remove(index))) + } + + /// Mirror the Chaptarr UI's manual edition pick: a full-book PUT carrying + /// the complete book body, `anyEditionOk = false`, and the full editions + /// array with exactly one edition monitored and manually added. This is + /// the only edition write Chaptarr persists correctly. + async fn select_edition(&self, book: &Value, editions: &[Value], chosen: usize) -> Result<()> { + let book_id = positive_id(book.get("id")).context("Resolved Chaptarr book has no id")?; + let mut body = book.clone(); + let object = body + .as_object_mut() + .context("Chaptarr returned an invalid book")?; + object.insert("anyEditionOk".into(), Value::Bool(false)); + let editions_payload: Vec = editions + .iter() + .enumerate() + .map(|(index, edition)| { + let mut edition = edition.clone(); + if let Some(fields) = edition.as_object_mut() { + fields.insert("monitored".into(), Value::Bool(index == chosen)); + fields.insert("manualAdd".into(), Value::Bool(index == chosen)); + } + edition + }) + .collect(); + object.insert("editions".into(), Value::Array(editions_payload)); + self.send_json(Method::PUT, &format!("/book/{book_id}"), &body) + .await?; + Ok(()) + } + + /// The read-back whose absence made the original failure silent: confirm + /// the book row is monitored for the requested format AND that exactly one + /// requested-format edition - the one we chose - is monitored, before any + /// search is queued or any success is reported. + async fn verify_request_ready( + &self, + book_id: i64, + item: &ChaptarrItem, + chosen_edition: &Value, + ) -> Result<()> { + let verified = self.get_book(book_id).await?; + if !local_row_matches_item(&verified, self.format, &item.book) + || !format_is_monitored(&verified, self.format) + { + bail!(UserFacingError( + "Chaptarr did not keep the requested format monitored, so no search was queued." + .into() + )); + } + let editions = self.editions_for_book(book_id).await?; + let chosen = parse_edition(chosen_edition) + .context("The selected Chaptarr edition could not be re-read")?; + let confirmed = sole_monitored_edition(&editions, self.format) + .is_some_and(|edition| same_edition(&edition, &chosen)); + if !confirmed { + bail!(UserFacingError(format!( + "Chaptarr did not keep exactly one {} edition of {} monitored, so no search was queued. The book needs attention in Chaptarr.", + format_name(self.format), + item.book.title + ))); + } + Ok(()) + } + async fn enable_author_format(&self, author_id: i64) -> Result<()> { let endpoint = format!("/author/{author_id}"); let mut author: Value = self.get(&endpoint, &[]).await?; @@ -487,11 +794,12 @@ impl Chaptarr { .book .editions .iter() - .filter(|edition| edition.is_ebook.is_none_or(|value| value == expected_ebook)) + .filter(|edition| edition_usable(edition, self.format)) .map(|edition| { json!({ "title": if edition.title.is_empty() { &item.book.title } else { &edition.title }, "foreignEditionId": null_if_empty(&edition.foreign_edition_id), + "format": format_name(self.format), "isEbook": expected_ebook, "isbn13": edition.isbn13, "monitored": false, @@ -499,9 +807,15 @@ impl Chaptarr { }) }) .collect(); + // Lookup projections may omit authoritative format. Never relabel or + // carry such a projection (or a physical edition) into a write. A + // neutral requested-format placeholder lets Chaptarr resolve its own + // authoritative `/edition` rows, which are settled and re-read before + // any edition is selected. let editions = if selected_editions.is_empty() { vec![json!({ "title": item.book.title, + "format": format_name(self.format), "isEbook": expected_ebook, "monitored": false, "manualAdd": false @@ -549,11 +863,133 @@ impl Chaptarr { } async fn already_requested(&self, item: &ChaptarrItem) -> Result> { - let (_, book) = self.locate_existing(item).await?; - let Some(book) = book else { return Ok(None) }; - let state = format_state(&book, self.format); + let (_, _, rows) = self.locate_existing(item).await?; + let state = self.request_state_across(&rows, item).await?; Ok((state != FormatState::Missing).then_some(state)) } + + /// Monitoring is only a durable configuration flag; it does not prove a + /// search was queued. Treat a no-file row as genuinely in flight only when + /// Chaptarr reports a grab or an active BookSearch for that exact pocket. + /// This lets a later Discord retry repair edition/monitor/search failures + /// without allowing two concurrent requests through the mutation lock. + async fn request_state_across( + &self, + rows: &[Value], + item: &ChaptarrItem, + ) -> Result { + let state = format_state_across(rows, self.format, &item.book); + if state == FormatState::Available { + return Ok(FormatState::Available); + } + let matching: Vec<_> = rows + .iter() + .filter(|row| local_row_matches_item(row, self.format, &item.book)) + .collect(); + if matching + .iter() + .filter_map(|row| serde_json::from_value::((*row).clone()).ok()) + .any(|book| book.grabbed) + { + return Ok(FormatState::Processing); + } + let book_ids: Vec<_> = matching + .iter() + .filter_map(|row| positive_id(row.get("id"))) + .collect(); + // A strict monitored state needs command evidence before it can block + // a repair. A legacy/partial row can also have a real search in flight, + // so probe whenever matching local IDs exist, even if monitoring is + // incomplete. + if book_ids.is_empty() { + return Ok(FormatState::Missing); + } + if self.recent_search_acknowledged(&book_ids).await { + return Ok(FormatState::Processing); + } + let commands = match self.commands().await { + Ok(commands) => commands, + Err(error) => { + warn!(%error, "Could not verify whether the requested book is already being searched"); + bail!(UserFacingError( + "Chaptarr's search status could not be verified, so no duplicate search was started. Please try again in a moment." + .into() + )); + } + }; + if book_search_command_active(&commands, &book_ids) { + Ok(FormatState::Processing) + } else { + // A monitored row with no file, grab, or matching search is a + // recoverable partial request, not proof of successful work. + Ok(FormatState::Missing) + } + } + + fn recent_search_key(&self, book_id: i64) -> String { + format!("{}:{}:{book_id}", self.base_url, format_name(self.format)) + } + + async fn recent_search_acknowledged(&self, book_ids: &[i64]) -> bool { + let now = Instant::now(); + let mut searches = recent_searches().lock().await; + searches + .retain(|_, acknowledged| now.duration_since(*acknowledged) < RECENT_SEARCH_ACK_TTL); + book_ids + .iter() + .any(|id| searches.contains_key(&self.recent_search_key(*id))) + } + + async fn record_search_acknowledgement(&self, book_id: i64) { + let now = Instant::now(); + let mut searches = recent_searches().lock().await; + searches + .retain(|_, acknowledged| now.duration_since(*acknowledged) < RECENT_SEARCH_ACK_TTL); + searches.insert(self.recent_search_key(book_id), now); + } +} + +fn command_references_book(command: &Value, book_ids: &[i64]) -> bool { + [command.get("body"), Some(command)] + .into_iter() + .flatten() + .any(|scope| { + positive_id(scope.get("bookId")).is_some_and(|id| book_ids.contains(&id)) + || scope + .get("bookIds") + .and_then(Value::as_array) + .is_some_and(|ids| { + ids.iter().any(|id| { + positive_id(Some(id)).is_some_and(|id| book_ids.contains(&id)) + }) + }) + }) +} + +fn command_name(command: &Value) -> &str { + let name = string_at(command, "name"); + if name.is_empty() { + string_at(command, "commandName") + } else { + name + } +} + +fn book_search_command_active(commands: &[Value], book_ids: &[i64]) -> bool { + !book_ids.is_empty() + && commands.iter().any(|command| { + let status = string_at(command, "status").to_ascii_lowercase(); + matches!(status.as_str(), "queued" | "started") + && command_name(command).eq_ignore_ascii_case("BookSearch") + && command_references_book(command, book_ids) + }) +} + +fn valid_book_search_acknowledgement(response: &Value) -> bool { + let status = string_at(response, "status").to_ascii_lowercase(); + positive_id(response.get("id")).is_some() + && command_name(response).eq_ignore_ascii_case("BookSearch") + && matches!(status.as_str(), "queued" | "started" | "completed") } impl MediaItem for ChaptarrItem { @@ -768,24 +1204,25 @@ impl MediaBackend for Chaptarr { let _request_guard = work_lock.lock().await; // Re-read inside the per-work lock. Two simultaneous Discord clicks for - // the same work+format cannot both pass this idempotency boundary. - let (mut author, mut book) = self.locate_existing(&item).await?; - if let Some(ref row) = book { - match format_state(row, self.format) { - FormatState::Available => bail!(UserFacingError(format!( - "{} is already available as an {}.", - item.book.title, - format_name(self.format) - ))), - FormatState::Processing => bail!(UserFacingError(format!( - "{} is already requested as an {}.", - item.book.title, - format_name(self.format) - ))), - FormatState::Missing => {} - } + // the same work+format cannot both pass this idempotency boundary. The + // state check spans every matching local row, so an available or + // in-flight duplicate pocket also stops a second request. + let (mut author, mut book, rows) = self.locate_existing(&item).await?; + match self.request_state_across(&rows, &item).await? { + FormatState::Available => bail!(UserFacingError(format!( + "{} is already available as an {}.", + item.book.title, + format_name(self.format) + ))), + FormatState::Processing => bail!(UserFacingError(format!( + "{} is already requested as an {}.", + item.book.title, + format_name(self.format) + ))), + FormatState::Missing => {} } + let mut author_added = false; if author.is_none() { let response = self .send_json(Method::POST, "/book", &self.new_author_body(&item)) @@ -800,17 +1237,76 @@ impl MediaBackend for Chaptarr { // instead of treating a response shape as authoritative. author = self.find_author(&item).await?; } - } else if let Some(local_author) = author.as_ref() - && book.is_none() - { - let body = self.existing_author_book_body(&item, local_author)?; - self.send_json(Method::POST, "/book", &body).await?; + author_added = true; } - let author_id = author + let mut author_id = author .as_ref() .and_then(|a| positive_id(a.get("id"))) .context("Chaptarr could not resolve the requested author")?; + if author_added { + // A brand-new author's catalog import continues long after the + // target row first appears. Monitoring before it settles is how a + // request dies silently, so nothing below runs until it has. + self.wait_for_catalog_settle( + author_id, + &item.book.author.author_name, + &item.book, + true, + ) + .await?; + } else { + // A retry sees an existing author even when the original catalog + // import is still running. Even an idle command sample is not + // enough: live imports can mutate editions after that command + // disappears. Every existing-author write therefore requires the + // full three-snapshot catalog/edition stability gate. + self.wait_for_catalog_settle( + author_id, + &item.book.author.author_name, + &item.book, + book.is_some(), + ) + .await?; + let (refreshed_author, refreshed_book, refreshed_rows) = + self.locate_existing(&item).await?; + if let Some(refreshed_author) = refreshed_author { + author_id = positive_id(refreshed_author.get("id")) + .context("Chaptarr could not re-resolve the requested author")?; + author = Some(refreshed_author); + } + book = refreshed_book; + match self.request_state_across(&refreshed_rows, &item).await? { + FormatState::Available => bail!(UserFacingError(format!( + "{} is already available as an {}.", + item.book.title, + format_name(self.format) + ))), + FormatState::Processing => bail!(UserFacingError(format!( + "{} is already requested as an {}.", + item.book.title, + format_name(self.format) + ))), + FormatState::Missing => {} + } + if book.is_none() { + let local_author = author + .as_ref() + .context("Chaptarr could not resolve the requested author")?; + let body = self.existing_author_book_body(&item, local_author)?; + self.send_json(Method::POST, "/book", &body).await?; + // Adding one work can itself start metadata work. Do not let + // the first visible row escape into monitoring; require the + // newly added target and its edition list to settle first. + self.wait_for_catalog_settle( + author_id, + &item.book.author.author_name, + &item.book, + true, + ) + .await?; + } + } if book.as_ref().is_none_or(|row| !book_complete(row)) { book = self.poll_target(author_id, &item.book).await?; } @@ -818,12 +1314,21 @@ impl MediaBackend for Chaptarr { // RefreshAuthor is intentionally guarded and only runs after the // user has pressed Request, when the exact target exists as an // unresolved placeholder. A missing target is never refreshed. + // The refresh re-runs catalog work, so it gets the same settle + // wait before any monitoring happens. self.send_json( Method::POST, "/command", &json!({"name": "RefreshAuthor", "authorId": author_id}), ) .await?; + self.wait_for_catalog_settle( + author_id, + &item.book.author.author_name, + &item.book, + true, + ) + .await?; book = self.poll_target(author_id, &item.book).await?; } let book = book.ok_or_else(|| { @@ -843,30 +1348,78 @@ impl MediaBackend for Chaptarr { format_name(self.format) ))); } + + // Re-resolve edition-aware: duplicate import pockets are deduped by + // which row carries usable requested-format editions, and the edition + // to monitor is chosen from `/edition` data (the book resource always + // reports an empty editions array and must never be trusted for this). + let (book, editions) = self + .resolve_pocket(author_id, &item.book) + .await? + .ok_or_else(|| { + UserFacingError(format!( + "Chaptarr could not resolve this {} to a safe local book row. Try refreshing the author in Chaptarr.", + format_name(self.format) + )) + })?; + if !book_complete(&book) { + bail!(UserFacingError(format!( + "Chaptarr only has an unresolved placeholder for this {}. Try refreshing the author in Chaptarr.", + format_name(self.format) + ))); + } + let Some(chosen) = preferred_edition_index(&editions, self.format, &item.book) else { + bail!(UserFacingError(format!( + "Chaptarr has no usable {} edition of {}, so nothing was monitored or searched. The book needs attention in Chaptarr.", + format_name(self.format), + item.book.title + ))); + }; let book_id = positive_id(book.get("id")).context("Resolved Chaptarr book has no id")?; self.enable_author_format(author_id).await?; + self.select_edition(&book, &editions, chosen).await?; + // Book-level monitoring only persists through this dedicated endpoint; + // the full-book PUT above silently ignores monitored flags. self.send_json( Method::PUT, "/book/monitor", &json!({"bookIds": [book_id], "monitored": true}), ) .await?; - let verified = self.get_book(book_id).await?; - if !local_row_matches_item(&verified, self.format, &item.book) - || !format_is_monitored(&verified, self.format) + self.verify_request_ready(book_id, &item, &editions[chosen]) + .await?; + let acknowledgement = match self + .send_json( + Method::POST, + "/command", + &json!({"name": "BookSearch", "bookIds": [book_id]}), + ) + .await { - bail!(UserFacingError( - "Chaptarr did not keep the requested format monitored, so no search was queued." - .into() - )); + Ok(response) => response, + Err(error) => { + warn!(book_id, %error, "Chaptarr did not confirm BookSearch"); + bail!(UserFacingError(format!( + "Chaptarr kept the {} request settings but did not confirm that its search started. Request {} again to safely retry the search.", + format_name(self.format), + item.book.title + ))); + } + }; + if !valid_book_search_acknowledgement(&acknowledgement) { + warn!( + book_id, + ?acknowledgement, + "Chaptarr returned an invalid BookSearch acknowledgement" + ); + bail!(UserFacingError(format!( + "Chaptarr kept the {} request settings but did not confirm that its search started. Request {} again to safely retry the search.", + format_name(self.format), + item.book.title + ))); } - self.send_json( - Method::POST, - "/command", - &json!({"name": "BookSearch", "bookIds": [book_id]}), - ) - .await?; + self.record_search_acknowledgement(book_id).await; Ok(()) } @@ -911,6 +1464,12 @@ impl MediaBackend for Chaptarr { } fn validate_item(item: &ChaptarrItem) -> Result<()> { + if clear_multi_book_result_title(&item.book.title) { + bail!(UserFacingError(format!( + "{} looks like a multi-book collection. Request each individual title so Chaptarr can select and verify the right edition.", + item.book.title + ))); + } if book_identity_complete(&item.book) { Ok(()) } else { @@ -931,6 +1490,8 @@ mod tests { const AUDIOBOOK_PROJECTION_LOOKUP: &str = include_str!("../../tests/fixtures/chaptarr/lookup_audiobook_projection.json"); const AUTHOR: &str = include_str!("../../tests/fixtures/chaptarr/author.json"); + const COMMAND_RESPONSE: &str = + include_str!("../../tests/fixtures/chaptarr/command_response.json"); fn backend(format: ChaptarrFormat) -> Chaptarr { Chaptarr { @@ -940,6 +1501,10 @@ mod tests { server_version: "0.9.720.0".into(), format, openlibrary_covers: false, + settle: SettlePacing { + interval: Duration::from_millis(20), + deadline: Duration::from_secs(5), + }, settings: ResolvedSettings { ebook_root: "/library/ebooks".into(), audiobook_root: "/library/audiobooks".into(), @@ -1042,6 +1607,25 @@ mod tests { assert!(validate_item(&item).is_err()); } + #[test] + fn book_search_acknowledgement_requires_a_known_success_state() { + for status in ["queued", "started", "completed"] { + assert!(valid_book_search_acknowledgement(&json!({ + "id": 7101, + "commandName": "BookSearch", + "status": status + }))); + } + for response in [ + json!({"id": 7101, "name": "BookSearch", "status": "failed"}), + json!({"id": 7101, "name": "BookSearch", "status": "unexpected"}), + json!({"id": 0, "name": "BookSearch", "status": "queued"}), + json!({"id": 7101, "name": "RefreshAuthor", "status": "queued"}), + ] { + assert!(!valid_book_search_acknowledgement(&response)); + } + } + #[test] fn existing_author_body_is_allowlisted_and_all_unmonitored() { let item = lookup_item(); @@ -1065,6 +1649,35 @@ mod tests { ); } + #[test] + fn existing_author_audiobook_body_replaces_unsafe_projections_with_neutral_placeholder() { + let mut item = lookup_item(); + item.book.editions = serde_json::from_value(json!([ + { + "title": "The Clockwork Orchard hardcover", + "foreignEditionId": "hc:physical-1001", + "format": "physical", + "isEbook": false + }, + { + "title": "Untyped projection that might be physical", + "foreignEditionId": "hc:untyped-1001", + "isEbook": false + } + ])) + .unwrap(); + let author: Value = serde_json::from_str(AUTHOR).unwrap(); + let body = backend(ChaptarrFormat::Audiobook) + .existing_author_book_body(&item, &author) + .unwrap(); + let editions = body["editions"].as_array().unwrap(); + assert_eq!(editions.len(), 1); + assert!(editions[0].get("foreignEditionId").is_none()); + assert_eq!(editions[0]["format"], "audiobook"); + assert_eq!(editions[0]["isEbook"], false); + assert_eq!(editions[0]["monitored"], false); + } + #[test] fn new_author_body_contains_both_format_settings_but_no_book_monitoring() { let item = lookup_item(); @@ -1095,6 +1708,18 @@ mod tests { assert_eq!(body["monitored"], false); } + #[tokio::test] + async fn multi_book_collection_is_rejected_before_any_http_request() { + let mut item = lookup_item(); + item.book.title = "The Clockwork Orchard Trilogy 3-Book Bundle".into(); + let error = backend(ChaptarrFormat::Ebook) + .request(Vec::new(), Box::new(item), 1234) + .await + .unwrap_err(); + assert!(error.downcast_ref::().is_some()); + assert!(error.to_string().contains("individual title")); + } + #[tokio::test] async fn search_and_confirmation_use_only_get_requests() { let (base_url, requests, server) = @@ -1205,7 +1830,7 @@ mod tests { } #[tokio::test] - async fn new_author_audiobook_request_uses_safe_payload_and_readbacks() { + async fn new_author_audiobook_request_settles_selects_edition_and_readbacks() { let author = json!({ "id": 7001, "authorName": "Mara Vale", @@ -1218,8 +1843,10 @@ mod tests { "id": 5101, "authorId": 7001, "title": "The Clockwork Orchard", + "foreignBookId": "hc:work-1001", "mediaType": "audiobook", "monitored": false, + "audiobookMonitored": false, "hasFiles": false, "releaseDate": "2024-01-01", "foreignEditionId": "hc:audio-1001", @@ -1229,22 +1856,64 @@ mod tests { "id": 5101, "authorId": 7001, "title": "The Clockwork Orchard", + "foreignBookId": "hc:work-1001", "mediaType": "audiobook", "monitored": true, + "audiobookMonitored": true, "hasFiles": false, "releaseDate": "2024-01-01", "foreignEditionId": "hc:audio-1001", "images": [{"coverType": "cover", "url": "https://covers.example.test/audio.jpg"}] }); + let audio_edition = json!({ + "id": 9101, + "bookId": 5101, + "title": "The Clockwork Orchard", + "foreignEditionId": "hc:audio-1001", + "format": "audiobook", + "isEbook": false, + "language": "eng", + "monitored": false, + "manualAdd": false + }); + let monitored_audio_edition = json!({ + "id": 9101, + "bookId": 5101, + "title": "The Clockwork Orchard", + "foreignEditionId": "hc:audio-1001", + "format": "audiobook", + "isEbook": false, + "language": "eng", + "monitored": true, + "manualAdd": true + }); let responses = vec![ "[]".to_string(), json!({"authorId": 7001}).to_string(), author.to_string(), + // Catalog settle: three stable samples of commands, book rows, + // and the target's authoritative edition list. + "[]".to_string(), + json!([audiobook.clone()]).to_string(), + json!([audio_edition.clone()]).to_string(), + "[]".to_string(), + json!([audiobook.clone()]).to_string(), + json!([audio_edition.clone()]).to_string(), + "[]".to_string(), + json!([audiobook.clone()]).to_string(), + json!([audio_edition.clone()]).to_string(), + // Target resolution, then edition-aware pocket resolution. + json!([audiobook.clone()]).to_string(), json!([audiobook]).to_string(), + json!([audio_edition]).to_string(), + // Author format flag is already enabled by the add payload. author.to_string(), + // Edition-select PUT, monitor PUT, then the full read-back. "{}".to_string(), - monitored_audiobook.to_string(), "{}".to_string(), + monitored_audiobook.to_string(), + json!([monitored_audio_edition]).to_string(), + COMMAND_RESPONSE.to_string(), ]; let (base_url, requests, server) = mock_api(responses).await; let mut chaptarr = backend(ChaptarrFormat::Audiobook); @@ -1276,10 +1945,23 @@ mod tests { "GET /api/v1/author HTTP/1.1", "POST /api/v1/book HTTP/1.1", "GET /api/v1/author/7001 HTTP/1.1", + "GET /api/v1/command HTTP/1.1", "GET /api/v1/book?authorId=7001 HTTP/1.1", + "GET /api/v1/edition?bookId=5101 HTTP/1.1", + "GET /api/v1/command HTTP/1.1", + "GET /api/v1/book?authorId=7001 HTTP/1.1", + "GET /api/v1/edition?bookId=5101 HTTP/1.1", + "GET /api/v1/command HTTP/1.1", + "GET /api/v1/book?authorId=7001 HTTP/1.1", + "GET /api/v1/edition?bookId=5101 HTTP/1.1", + "GET /api/v1/book?authorId=7001 HTTP/1.1", + "GET /api/v1/book?authorId=7001 HTTP/1.1", + "GET /api/v1/edition?bookId=5101 HTTP/1.1", "GET /api/v1/author/7001 HTTP/1.1", + "PUT /api/v1/book/5101 HTTP/1.1", "PUT /api/v1/book/monitor HTTP/1.1", "GET /api/v1/book/5101 HTTP/1.1", + "GET /api/v1/edition?bookId=5101 HTTP/1.1", "POST /api/v1/command HTTP/1.1", ] ); @@ -1289,19 +1971,345 @@ mod tests { assert!(recorded[1].contains("\"audiobookMonitored\":false")); assert!(recorded[1].contains("\"ebookMonitorFuture\":false")); assert!(recorded[1].contains("\"audiobookMonitorFuture\":true")); - assert!(recorded[5].contains("\"bookIds\":[5101]")); - assert!(recorded[7].contains("\"name\":\"BookSearch\"")); + // The edition-select PUT mirrors the Chaptarr UI: complete book body, + // anyEditionOk off, and exactly one monitored, manually-added edition. + assert!(recorded[16].contains("\"anyEditionOk\":false")); + assert!(recorded[16].contains("\"manualAdd\":true")); + assert_eq!(recorded[16].matches("\"monitored\":true").count(), 1); + assert!(recorded[17].contains("\"bookIds\":[5101]")); + assert!(recorded[17].contains("\"monitored\":true")); + assert!(recorded[20].contains("\"name\":\"BookSearch\"")); + assert!(recorded[20].contains("\"bookIds\":[5101]")); } #[tokio::test] - async fn existing_author_missing_work_posts_allowlisted_body_then_verifies() { - let author_unmonitored = json!({ + async fn new_author_request_fails_loudly_while_catalog_is_importing() { + let author = json!({ "id": 7001, "authorName": "Mara Vale", "foreignAuthorId": "hc:author-1001", "monitored": true, "ebookMonitorFuture": false, - "audiobookMonitorFuture": false + "audiobookMonitorFuture": true + }); + let refresh_in_flight = json!([{ + "name": "RefreshAuthor", + "status": "started", + "body": {"authorId": 7001} + }]); + let responses = vec![ + "[]".to_string(), + json!({"authorId": 7001}).to_string(), + author.to_string(), + refresh_in_flight.to_string(), + ]; + let (base_url, requests, server) = mock_api(responses).await; + let mut chaptarr = backend(ChaptarrFormat::Audiobook); + chaptarr.settle.deadline = Duration::ZERO; + chaptarr.base_url = base_url; + chaptarr.client = reqwest::Client::builder() + .timeout(Duration::from_secs(2)) + .build() + .unwrap(); + let mut item = lookup_item(); + item.existing_book_id = None; + + let error = chaptarr + .request(Vec::new(), Box::new(item), 1234) + .await + .unwrap_err(); + assert!(error.downcast_ref::().is_some()); + assert!(error.to_string().contains("NOT completed")); + timeout(Duration::from_secs(2), server) + .await + .expect("mock server should finish") + .unwrap(); + + // The author add is the only mutation: nothing was monitored, no + // edition was selected, and no search was queued. + let recorded = requests.lock().await; + let lines: Vec<_> = recorded + .iter() + .map(|request| request_line(request)) + .collect(); + assert_eq!( + lines, + vec![ + "GET /api/v1/author HTTP/1.1", + "POST /api/v1/book HTTP/1.1", + "GET /api/v1/author/7001 HTTP/1.1", + "GET /api/v1/command HTTP/1.1", + ] + ); + } + + async fn assert_strict_readback_failure(generic_monitored: bool, format_monitored: bool) { + let author = json!({ + "id": 7001, + "authorName": "Mara Vale", + "foreignAuthorId": "hc:author-1001", + "monitored": true, + "ebookMonitorFuture": true, + "audiobookMonitorFuture": false + }); + let book = json!({ + "id": 4101, + "authorId": 7001, + "title": "The Clockwork Orchard", + "foreignBookId": "hc:work-1001", + "mediaType": "ebook", + "monitored": false, + "ebookMonitored": false, + "hasFiles": false, + "releaseDate": "2024-01-01", + "foreignEditionId": "hc:edition-1001", + "images": [{"coverType": "cover", "url": "https://covers.example.test/book.jpg"}] + }); + let edition = json!({ + "id": 8101, + "bookId": 4101, + "title": "The Clockwork Orchard", + "foreignEditionId": "hc:edition-1001", + "format": "ebook", + "isEbook": true, + "language": "eng", + "monitored": false, + "manualAdd": false + }); + let failed_readback = json!({ + "id": 4101, + "authorId": 7001, + "title": "The Clockwork Orchard", + "foreignBookId": "hc:work-1001", + "mediaType": "ebook", + "monitored": generic_monitored, + "ebookMonitored": format_monitored, + "hasFiles": false, + "releaseDate": "2024-01-01", + "foreignEditionId": "hc:edition-1001", + "images": [{"coverType": "cover", "url": "https://covers.example.test/book.jpg"}] + }); + let mut responses = vec![ + json!([author.clone()]).to_string(), + json!([book.clone()]).to_string(), + // Exact-search preflight runs even when import reverted both + // monitor flags. + "[]".to_string(), + ]; + for _ in 0..SETTLE_STABLE_SAMPLES { + responses.extend([ + "[]".to_string(), + json!([book.clone()]).to_string(), + json!([edition.clone()]).to_string(), + ]); + } + responses.extend([ + json!([author.clone()]).to_string(), + json!([book.clone()]).to_string(), + "[]".to_string(), + json!([book]).to_string(), + json!([edition]).to_string(), + author.to_string(), + "{}".to_string(), + "{}".to_string(), + failed_readback.to_string(), + ]); + let (base_url, requests, server) = mock_api(responses).await; + let mut chaptarr = backend(ChaptarrFormat::Ebook); + chaptarr.base_url = base_url; + let mut item = lookup_item(); + item.existing_book_id = None; + + let error = chaptarr + .request(Vec::new(), Box::new(item), 1234) + .await + .unwrap_err(); + assert!(error.downcast_ref::().is_some()); + assert!(error.to_string().contains("no search was queued")); + timeout(Duration::from_secs(2), server) + .await + .expect("mock server should finish") + .unwrap(); + let recorded = requests.lock().await; + assert!( + recorded + .iter() + .all(|request| !request.contains("\"name\":\"BookSearch\"")) + ); + } + + #[tokio::test] + async fn strict_readback_requires_both_generic_and_format_monitoring() { + assert_strict_readback_failure(true, false).await; + assert_strict_readback_failure(false, true).await; + } + + #[tokio::test] + async fn partial_or_import_reverted_state_still_dedupes_an_active_search() { + let partial = json!({ + "id": 4101, + "authorId": 7001, + "title": "The Clockwork Orchard", + "foreignBookId": "hc:work-1001", + "mediaType": "ebook", + "monitored": true, + "ebookMonitored": true, + "hasFiles": false + }); + let import_reverted = json!({ + "id": 4101, + "authorId": 7001, + "title": "The Clockwork Orchard", + "foreignBookId": "hc:work-1001", + "mediaType": "ebook", + "monitored": false, + "ebookMonitored": false, + "hasFiles": false + }); + let active = json!([{ + "id": 7101, + "commandName": "BookSearch", + "status": "started", + "body": {"bookIds": [4101]} + }]); + let (base_url, _requests, server) = + mock_api(vec!["[]".to_string(), active.to_string()]).await; + let mut chaptarr = backend(ChaptarrFormat::Ebook); + chaptarr.base_url = base_url; + let item = lookup_item(); + + assert_eq!( + chaptarr + .request_state_across(std::slice::from_ref(&partial), &item) + .await + .unwrap(), + FormatState::Missing + ); + assert_eq!( + chaptarr + .request_state_across(std::slice::from_ref(&import_reverted), &item) + .await + .unwrap(), + FormatState::Processing + ); + timeout(Duration::from_secs(2), server) + .await + .expect("mock server should finish") + .unwrap(); + } + + #[tokio::test] + async fn catalog_settle_resets_for_active_changed_and_unknown_command_state() { + let active_refresh = json!([{ + "id": 7201, + "name": "RefreshAuthor", + "status": "started", + "body": {"authorId": 7001} + }]); + let book = json!({ + "id": 4101, + "authorId": 7001, + "title": "The Clockwork Orchard", + "foreignBookId": "hc:work-1001", + "mediaType": "ebook", + "monitored": false, + "ebookMonitored": false, + "hasFiles": false, + "releaseDate": "2024-01-01", + "foreignEditionId": "hc:edition-1001", + "images": [{"coverType": "cover", "url": "https://covers.example.test/book.jpg"}] + }); + let edition_one = json!([{ + "id": 8101, + "bookId": 4101, + "title": "The Clockwork Orchard", + "foreignEditionId": "hc:edition-1001", + "format": "ebook", + "isEbook": true, + "language": "eng" + }]); + let edition_two = json!([ + { + "id": 8101, + "bookId": 4101, + "title": "The Clockwork Orchard", + "foreignEditionId": "hc:edition-1001", + "format": "ebook", + "isEbook": true, + "language": "eng" + }, + { + "id": 8102, + "bookId": 4101, + "title": "The Clockwork Orchard", + "foreignEditionId": "hc:edition-1002", + "format": "ebook", + "isEbook": true, + "language": "eng" + } + ]); + let mut responses = vec![active_refresh.to_string()]; + for editions in [&edition_one, &edition_two, &edition_two] { + responses.extend([ + "[]".to_string(), + json!([book.clone()]).to_string(), + editions.to_string(), + ]); + } + // Invalid JSON makes the command poll unknown and must erase the two + // quiet samples already accumulated for edition_two. + responses.push("not-json".to_string()); + for _ in 0..SETTLE_STABLE_SAMPLES { + responses.extend([ + "[]".to_string(), + json!([book.clone()]).to_string(), + edition_two.to_string(), + ]); + } + let (base_url, requests, server) = mock_api(responses).await; + let mut chaptarr = backend(ChaptarrFormat::Ebook); + chaptarr.base_url = base_url; + let item = lookup_item(); + + chaptarr + .wait_for_catalog_settle(7001, "Mara Vale", &item.book, true) + .await + .unwrap(); + timeout(Duration::from_secs(2), server) + .await + .expect("mock server should finish") + .unwrap(); + let recorded = requests.lock().await; + let lines: Vec<_> = recorded + .iter() + .map(|request| request_line(request)) + .collect(); + assert_eq!( + lines + .iter() + .filter(|line| **line == "GET /api/v1/command HTTP/1.1") + .count(), + 8 + ); + assert_eq!( + lines + .iter() + .filter(|line| **line == "GET /api/v1/edition?bookId=4101 HTTP/1.1") + .count(), + 6 + ); + assert!(lines.iter().all(|line| line.starts_with("GET "))); + } + + #[tokio::test] + async fn existing_author_missing_work_posts_allowlisted_body_then_verifies() { + let author_unmonitored = json!({ + "id": 7001, + "authorName": "Mara Vale", + "foreignAuthorId": "hc:author-1001", + "monitored": true, + "ebookMonitorFuture": false, + "audiobookMonitorFuture": false }); let author_monitored = json!({ "id": 7001, @@ -1315,8 +2323,10 @@ mod tests { "id": 4101, "authorId": 7001, "title": "The Clockwork Orchard", + "foreignBookId": "hc:work-1001", "mediaType": "ebook", "monitored": false, + "ebookMonitored": false, "hasFiles": false, "releaseDate": "2024-01-01", "foreignEditionId": "hc:edition-1001", @@ -1326,14 +2336,46 @@ mod tests { "id": 4101, "authorId": 7001, "title": "The Clockwork Orchard", + "foreignBookId": "hc:work-1001", "mediaType": "ebook", "monitored": true, + "ebookMonitored": true, "hasFiles": false, "releaseDate": "2024-01-01", "foreignEditionId": "hc:edition-1001", "images": [{"coverType": "cover", "url": "https://covers.example.test/book.jpg"}] }); - let responses = vec![ + let ebook_edition = json!({ + "id": 8101, + "bookId": 4101, + "title": "The Clockwork Orchard", + "foreignEditionId": "hc:edition-1001", + "format": "ebook", + "isEbook": true, + "language": "eng", + "monitored": false, + "manualAdd": false + }); + let monitored_ebook_edition = json!({ + "id": 8101, + "bookId": 4101, + "title": "The Clockwork Orchard", + "foreignEditionId": "hc:edition-1001", + "format": "ebook", + "isEbook": true, + "language": "eng", + "monitored": true, + "manualAdd": true + }); + let mut responses = vec![ + json!([author_unmonitored.clone()]).to_string(), + "[]".to_string(), + ]; + // Even an empty existing catalog requires three quiet snapshots. + for _ in 0..SETTLE_STABLE_SAMPLES { + responses.extend(["[]".to_string(), "[]".to_string()]); + } + responses.extend([ json!([author_unmonitored.clone()]).to_string(), "[]".to_string(), json!({ @@ -1347,14 +2389,29 @@ mod tests { "images": [{"url": "https://covers.example.test/wrong.jpg"}] }) .to_string(), + ]); + // POST /book can start its own import tail. The target row and + // authoritative editions must be unchanged for the full window. + for _ in 0..SETTLE_STABLE_SAMPLES { + responses.extend([ + "[]".to_string(), + json!([resolved_book.clone()]).to_string(), + json!([ebook_edition.clone()]).to_string(), + ]); + } + responses.extend([ + json!([resolved_book.clone()]).to_string(), json!([resolved_book]).to_string(), + json!([ebook_edition]).to_string(), author_unmonitored.to_string(), "{}".to_string(), author_monitored.to_string(), "{}".to_string(), - monitored_book.to_string(), "{}".to_string(), - ]; + monitored_book.to_string(), + json!([monitored_ebook_edition]).to_string(), + COMMAND_RESPONSE.to_string(), + ]); let (base_url, requests, server) = mock_api(responses).await; let mut chaptarr = backend(ChaptarrFormat::Ebook); chaptarr.base_url = base_url; @@ -1379,26 +2436,25 @@ mod tests { .iter() .map(|request| request_line(request)) .collect(); + assert_eq!(lines.len(), 31); + assert_eq!(lines[10], "POST /api/v1/book HTTP/1.1"); + assert!(recorded[10].contains("\"foreignBookId\":\"hc:work-1001\"")); + assert!(recorded[10].contains("\"monitored\":false")); + assert!(recorded[10].contains("\"ebookMonitored\":false")); + assert!(recorded[10].contains("\"audiobookMonitored\":false")); + assert!(!recorded[10].contains("remoteCover")); + assert!(recorded[26].contains("\"anyEditionOk\":false")); + assert!(recorded[26].contains("\"manualAdd\":true")); + assert_eq!(recorded[26].matches("\"monitored\":true").count(), 1); + assert_eq!(lines[27], "PUT /api/v1/book/monitor HTTP/1.1"); + assert_eq!(lines[30], "POST /api/v1/command HTTP/1.1"); assert_eq!( - lines, - vec![ - "GET /api/v1/author HTTP/1.1", - "GET /api/v1/book?authorId=7001 HTTP/1.1", - "POST /api/v1/book HTTP/1.1", - "GET /api/v1/book?authorId=7001 HTTP/1.1", - "GET /api/v1/author/7001 HTTP/1.1", - "PUT /api/v1/author/7001 HTTP/1.1", - "GET /api/v1/author/7001 HTTP/1.1", - "PUT /api/v1/book/monitor HTTP/1.1", - "GET /api/v1/book/4101 HTTP/1.1", - "POST /api/v1/command HTTP/1.1", - ] + lines[11..27] + .iter() + .filter(|line| **line == "GET /api/v1/edition?bookId=4101 HTTP/1.1") + .count(), + 4 ); - assert!(recorded[2].contains("\"foreignBookId\":\"hc:work-1001\"")); - assert!(recorded[2].contains("\"monitored\":false")); - assert!(recorded[2].contains("\"ebookMonitored\":false")); - assert!(recorded[2].contains("\"audiobookMonitored\":false")); - assert!(!recorded[2].contains("remoteCover")); assert_eq!( lines .iter() @@ -1409,7 +2465,192 @@ mod tests { } #[tokio::test] - async fn concurrent_existing_work_requests_queue_one_search() { + async fn malformed_search_acknowledgement_leaves_a_retryable_request() { + let author = json!({ + "id": 7001, + "authorName": "Mara Vale", + "foreignAuthorId": "hc:author-1001", + "monitored": true, + "ebookMonitorFuture": true, + "audiobookMonitorFuture": false + }); + let unmonitored_book = json!({ + "id": 4101, + "authorId": 7001, + "title": "The Clockwork Orchard", + "foreignBookId": "hc:work-1001", + "mediaType": "ebook", + "monitored": false, + "ebookMonitored": false, + "hasFiles": false, + "releaseDate": "2024-01-01", + "foreignEditionId": "hc:edition-1001", + "images": [{"coverType": "cover", "url": "https://covers.example.test/book.jpg"}] + }); + let monitored_book = json!({ + "id": 4101, + "authorId": 7001, + "title": "The Clockwork Orchard", + "foreignBookId": "hc:work-1001", + "mediaType": "ebook", + "monitored": true, + "ebookMonitored": true, + "hasFiles": false, + "releaseDate": "2024-01-01", + "foreignEditionId": "hc:edition-1001", + "images": [{"coverType": "cover", "url": "https://covers.example.test/book.jpg"}] + }); + let unmonitored_edition = json!({ + "id": 8101, + "bookId": 4101, + "title": "The Clockwork Orchard", + "foreignEditionId": "hc:edition-1001", + "format": "ebook", + "isEbook": true, + "language": "eng", + "monitored": false, + "manualAdd": false + }); + let monitored_edition = json!({ + "id": 8101, + "bookId": 4101, + "title": "The Clockwork Orchard", + "foreignEditionId": "hc:edition-1001", + "format": "ebook", + "isEbook": true, + "language": "eng", + "monitored": true, + "manualAdd": true + }); + let mut responses = vec![ + json!([author.clone()]).to_string(), + json!([unmonitored_book.clone()]).to_string(), + "[]".to_string(), + ]; + for _ in 0..SETTLE_STABLE_SAMPLES { + responses.extend([ + "[]".to_string(), + json!([unmonitored_book.clone()]).to_string(), + json!([unmonitored_edition.clone()]).to_string(), + ]); + } + responses.extend([ + json!([author.clone()]).to_string(), + json!([unmonitored_book.clone()]).to_string(), + "[]".to_string(), + json!([unmonitored_book.clone()]).to_string(), + json!([unmonitored_edition.clone()]).to_string(), + author.to_string(), + "{}".to_string(), + "{}".to_string(), + monitored_book.to_string(), + json!([monitored_edition.clone()]).to_string(), + // HTTP success without a command identity must not produce a + // Discord success or enter the recent-ack dedupe cache. + "{}".to_string(), + json!([author.clone()]).to_string(), + json!([monitored_book.clone()]).to_string(), + // The retry proves no exact search is active, then runs the full + // stability gate before repairing the persisted partial state. + "[]".to_string(), + ]); + for _ in 0..SETTLE_STABLE_SAMPLES { + responses.extend([ + "[]".to_string(), + json!([monitored_book.clone()]).to_string(), + json!([monitored_edition.clone()]).to_string(), + ]); + } + responses.extend([ + json!([author.clone()]).to_string(), + json!([monitored_book.clone()]).to_string(), + "[]".to_string(), + json!([monitored_book.clone()]).to_string(), + json!([monitored_edition.clone()]).to_string(), + author.to_string(), + "{}".to_string(), + "{}".to_string(), + monitored_book.to_string(), + json!([monitored_edition]).to_string(), + json!({"id": 7102, "name": "BookSearch", "status": "queued"}).to_string(), + ]); + let (base_url, requests, server) = mock_api(responses).await; + let mut chaptarr = backend(ChaptarrFormat::Ebook); + chaptarr.base_url = base_url; + let mut item = lookup_item(); + item.existing_book_id = None; + let retry_item = item.clone(); + + let first_error = chaptarr + .request(Vec::new(), Box::new(item), 1234) + .await + .unwrap_err(); + assert!(first_error.downcast_ref::().is_some()); + assert!( + first_error + .to_string() + .contains("did not confirm that its search started") + ); + chaptarr + .request(Vec::new(), Box::new(retry_item), 1234) + .await + .unwrap(); + timeout(Duration::from_secs(2), server) + .await + .expect("mock server should finish") + .unwrap(); + + let recorded = requests.lock().await; + let lines: Vec<_> = recorded + .iter() + .map(|request| request_line(request)) + .collect(); + assert_eq!(lines.len(), 46); + assert_eq!( + lines + .iter() + .filter(|line| **line == "GET /api/v1/command HTTP/1.1") + .count(), + 10 + ); + assert_eq!( + lines + .iter() + .filter(|line| **line == "GET /api/v1/edition?bookId=4101 HTTP/1.1") + .count(), + 10 + ); + assert_eq!( + lines + .iter() + .filter(|line| **line == "PUT /api/v1/book/4101 HTTP/1.1") + .count(), + 2 + ); + assert_eq!( + lines + .iter() + .filter(|line| **line == "PUT /api/v1/book/monitor HTTP/1.1") + .count(), + 2 + ); + assert_eq!( + lines + .iter() + .filter(|line| **line == "POST /api/v1/command HTTP/1.1") + .count(), + 2 + ); + assert!( + lines + .iter() + .all(|line| *line != "PUT /api/v1/author/7001 HTTP/1.1") + ); + assert!(recorded[45].contains("\"name\":\"BookSearch\"")); + } + + #[tokio::test] + async fn concurrent_existing_work_waits_for_edition_stability_and_queues_one_search() { let author_unmonitored = json!({ "id": 7001, "authorName": "Mara Vale", @@ -1430,8 +2671,10 @@ mod tests { "id": 4101, "authorId": 7001, "title": "The Clockwork Orchard", + "foreignBookId": "hc:work-1001", "mediaType": "ebook", "monitored": false, + "ebookMonitored": false, "hasFiles": false, "releaseDate": "2024-01-01", "foreignEditionId": "hc:edition-1001", @@ -1441,25 +2684,86 @@ mod tests { "id": 4101, "authorId": 7001, "title": "The Clockwork Orchard", + "foreignBookId": "hc:work-1001", "mediaType": "ebook", "monitored": true, + "ebookMonitored": true, "hasFiles": false, "releaseDate": "2024-01-01", "foreignEditionId": "hc:edition-1001", "images": [{"coverType": "cover", "url": "https://covers.example.test/book.jpg"}] }); - let responses = vec![ + let ebook_edition = json!({ + "id": 8101, + "bookId": 4101, + "title": "The Clockwork Orchard", + "foreignEditionId": "hc:edition-1001", + "format": "ebook", + "isEbook": true, + "language": "eng", + "monitored": false, + "manualAdd": false + }); + let monitored_ebook_edition = json!({ + "id": 8101, + "bookId": 4101, + "title": "The Clockwork Orchard", + "foreignEditionId": "hc:edition-1001", + "format": "ebook", + "isEbook": true, + "language": "eng", + "monitored": true, + "manualAdd": true + }); + let second_edition = json!({ + "id": 8102, + "bookId": 4101, + "title": "The Clockwork Orchard: Annotated", + "foreignEditionId": "hc:edition-1002", + "format": "ebook", + "isEbook": true, + "language": "eng", + "monitored": false, + "manualAdd": false + }); + let expanded_editions = json!([ebook_edition.clone(), second_edition.clone()]); + let monitored_editions = json!([monitored_ebook_edition, second_edition]); + let mut responses = vec![ json!([author_unmonitored.clone()]).to_string(), json!([book_unmonitored.clone()]).to_string(), + // Exact-search preflight must run before the longer stability + // window even though this row is currently unmonitored. + "[]".to_string(), + // The command is idle throughout, but the edition list grows + // after the first sample. Stability must restart at that point. + "[]".to_string(), + json!([book_unmonitored.clone()]).to_string(), + json!([ebook_edition]).to_string(), + ]; + for _ in 0..SETTLE_STABLE_SAMPLES { + responses.extend([ + "[]".to_string(), + json!([book_unmonitored.clone()]).to_string(), + expanded_editions.to_string(), + ]); + } + responses.extend([ + json!([author_unmonitored.clone()]).to_string(), + json!([book_unmonitored.clone()]).to_string(), + "[]".to_string(), + json!([book_unmonitored.clone()]).to_string(), + expanded_editions.to_string(), author_unmonitored.to_string(), "{}".to_string(), author_monitored.to_string(), "{}".to_string(), - book_monitored.to_string(), "{}".to_string(), + book_monitored.to_string(), + monitored_editions.to_string(), + COMMAND_RESPONSE.to_string(), json!([author_monitored.clone()]).to_string(), json!([book_monitored.clone()]).to_string(), - ]; + ]); let (base_url, requests, server) = mock_api(responses).await; let mut chaptarr = backend(ChaptarrFormat::Ebook); chaptarr.base_url = base_url; @@ -1487,24 +2791,17 @@ mod tests { .iter() .map(|request| request_line(request)) .collect(); + assert_eq!(lines.len(), 30); assert_eq!( - lines, - vec![ - "GET /api/v1/author HTTP/1.1", - "GET /api/v1/book?authorId=7001 HTTP/1.1", - "GET /api/v1/author/7001 HTTP/1.1", - "PUT /api/v1/author/7001 HTTP/1.1", - "GET /api/v1/author/7001 HTTP/1.1", - "PUT /api/v1/book/monitor HTTP/1.1", - "GET /api/v1/book/4101 HTTP/1.1", - "POST /api/v1/command HTTP/1.1", - "GET /api/v1/author HTTP/1.1", - "GET /api/v1/book?authorId=7001 HTTP/1.1", - ] + lines + .iter() + .filter(|line| **line == "GET /api/v1/edition?bookId=4101 HTTP/1.1") + .count(), + 6 ); - assert!(recorded[5].contains("\"bookIds\":[4101]")); - assert!(recorded[5].contains("\"monitored\":true")); - assert!(recorded[7].contains("\"name\":\"BookSearch\"")); + assert!(recorded[24].contains("\"bookIds\":[4101]")); + assert!(recorded[24].contains("\"monitored\":true")); + assert!(recorded[27].contains("\"name\":\"BookSearch\"")); assert_eq!( lines .iter() diff --git a/doplarr/src/providers/chaptarr/models.rs b/doplarr/src/providers/chaptarr/models.rs index 4ae8e55..ee3aae9 100644 --- a/doplarr/src/providers/chaptarr/models.rs +++ b/doplarr/src/providers/chaptarr/models.rs @@ -73,10 +73,23 @@ pub(super) struct Image { #[derive(Debug, Clone, Default, Deserialize)] #[serde(rename_all = "camelCase")] pub(super) struct Edition { + #[serde(default, deserialize_with = "null_default")] + pub(super) id: Value, + /// Chaptarr's authoritative edition discriminator (`ebook`, `audiobook`, + /// or `physical`). Older/projection responses may omit it, in which case + /// callers can fall back to `is_ebook` deliberately. + #[serde(default, deserialize_with = "null_default")] + pub(super) format: String, #[serde(default)] pub(super) is_ebook: Option, #[serde(default)] pub(super) isbn13: Option, + #[serde(default)] + pub(super) asin: Option, + #[serde(default, deserialize_with = "null_default")] + pub(super) language: String, + #[serde(default, deserialize_with = "null_default")] + pub(super) monitored: bool, #[serde(default, deserialize_with = "null_default")] pub(super) title: String, #[serde(default, deserialize_with = "null_default")] diff --git a/doplarr/src/providers/chaptarr/selection.rs b/doplarr/src/providers/chaptarr/selection.rs index 7e01c73..5c1c3b4 100644 --- a/doplarr/src/providers/chaptarr/selection.rs +++ b/doplarr/src/providers/chaptarr/selection.rs @@ -1,6 +1,6 @@ //! Pure compatibility, matching, and display helpers for Chaptarr data. -use super::models::{BookShape, OpenLibraryResponse, Profile, RootFolder, SystemStatus}; +use super::models::{BookShape, Edition, OpenLibraryResponse, Profile, RootFolder, SystemStatus}; use crate::config::ChaptarrFormat; use anyhow::{Result, bail}; use serde_json::Value; @@ -227,8 +227,12 @@ pub(super) fn local_row_matches_item( let Some(local) = parse_book(value) else { return false; }; - if !selected.foreign_book_id.is_empty() && !local.foreign_book_id.is_empty() { - local.foreign_book_id == selected.foreign_book_id + if !selected.foreign_book_id.trim().is_empty() { + // Once lookup supplied a stable work id, never substitute a same-title + // row whose id is missing or different. Title matching is only a + // fallback for projections that genuinely have no work id. + !local.foreign_book_id.trim().is_empty() + && local.foreign_book_id == selected.foreign_book_id } else { title_match_tier(&local.title, &selected.title) > 0 } @@ -241,12 +245,17 @@ pub(super) fn search_format_affinity(book: &BookShape, format: ChaptarrFormat) - if !book.media_type.is_empty() { return u8::from(book.media_type.eq_ignore_ascii_case(format_name(format))) * 3; } - let flags: Vec<_> = book.editions.iter().filter_map(|e| e.is_ebook).collect(); - if flags.is_empty() { + if book.editions.is_empty() + || book + .editions + .iter() + .all(|edition| edition.format.trim().is_empty() && edition.is_ebook.is_none()) + { 1 - } else if flags - .into_iter() - .any(|v| v == (format == ChaptarrFormat::Ebook)) + } else if book + .editions + .iter() + .any(|edition| edition_projection_compatible(edition, format)) { 2 } else { @@ -265,7 +274,7 @@ pub(super) fn format_is_monitored(value: &Value, format: ChaptarrFormat) -> bool ChaptarrFormat::Ebook => book.ebook_monitored, ChaptarrFormat::Audiobook => book.audiobook_monitored, }; - format_flag || book.monitored + book.monitored && format_flag } pub(super) fn format_state(value: &Value, format: ChaptarrFormat) -> FormatState { @@ -289,6 +298,30 @@ pub(super) fn format_state(value: &Value, format: ChaptarrFormat) -> FormatState } } +fn format_state_rank(state: FormatState) -> u8 { + match state { + FormatState::Available => 2, + FormatState::Processing => 1, + FormatState::Missing => 0, + } +} + +/// Chaptarr imports can leave duplicate local rows ("pockets") for the same +/// work, and availability or an in-flight grab may live on either twin. The +/// authoritative state for a request is therefore the strongest state across +/// every local row that matches the selected work, never a single row. +pub(super) fn format_state_across( + rows: &[Value], + format: ChaptarrFormat, + selected: &BookShape, +) -> FormatState { + rows.iter() + .filter(|row| local_row_matches_item(row, format, selected)) + .map(|row| format_state(row, format)) + .max_by_key(|state| format_state_rank(*state)) + .unwrap_or(FormatState::Missing) +} + pub(super) fn preferred_book( rows: &[Value], format: ChaptarrFormat, @@ -314,6 +347,255 @@ pub(super) fn preferred_book( candidates.pop() } +pub(super) fn parse_edition(value: &Value) -> Option { + serde_json::from_value(value.clone()).ok() +} + +fn command_references_author(command: &Value, author_id: i64) -> Option { + // Commands echo their payload under `body` on current builds; tolerate a + // flattened shape as well. + let scopes = [command.get("body"), Some(command)]; + let mut saw_scope = false; + for scope in scopes.into_iter().flatten() { + if let Some(id) = positive_id(scope.get("authorId")) { + saw_scope = true; + if id == author_id { + return Some(true); + } + } + if let Some(ids) = scope.get("authorIds").and_then(Value::as_array) { + saw_scope = true; + if ids + .iter() + .any(|id| positive_id(Some(id)) == Some(author_id)) + { + return Some(true); + } + } + } + if saw_scope { Some(false) } else { None } +} + +/// True while a queued or running Chaptarr command could still be mutating +/// this author's catalog: any command scoped to the author, or an unscoped +/// refresh-style command that may sweep every author. +pub(super) fn catalog_command_active(commands: &[Value], author_id: i64) -> bool { + commands.iter().any(|command| { + let status = string_at(command, "status").to_ascii_lowercase(); + if status != "queued" && status != "started" { + return false; + } + match command_references_author(command, author_id) { + Some(references) => references, + None => { + let name = { + let name = string_at(command, "name"); + if name.is_empty() { + string_at(command, "commandName") + } else { + name + } + } + .to_ascii_lowercase(); + name.contains("refresh") + } + } + }) +} + +/// Relevant identity and completeness fields for one catalog row. Watching +/// these fields prevents a row from looking settled merely because its id was +/// allocated before Chaptarr populated the rest of its metadata. +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] +pub(super) struct BookRowFingerprint { + id: i64, + foreign_book_id: String, + title: String, + foreign_edition_id: String, + media_type: String, + release_date: String, + image_count: usize, + embedded_edition_count: usize, + monitored: bool, + ebook_monitored: bool, + audiobook_monitored: bool, +} + +/// Order-independent identity and readiness shape of an author's book list, +/// used to decide when a fresh catalog import has stopped adding, replacing, +/// or completing rows in place. +pub(super) fn book_list_fingerprint(rows: &[Value]) -> Vec { + let mut fingerprint: Vec = rows + .iter() + .map(|row| { + let book = parse_book(row).unwrap_or_default(); + BookRowFingerprint { + id: positive_id(row.get("id")).unwrap_or_default(), + foreign_book_id: book.foreign_book_id, + title: book.title, + foreign_edition_id: book.foreign_edition_id, + media_type: book.media_type, + release_date: book.release_date.unwrap_or_default(), + image_count: book.images.len(), + embedded_edition_count: book.editions.len(), + monitored: book.monitored, + ebook_monitored: book.ebook_monitored, + audiobook_monitored: book.audiobook_monitored, + } + }) + .collect(); + fingerprint.sort(); + fingerprint +} + +/// An edition can be mutated or accepted during read-back only when +/// Chaptarr's authoritative `format` is present and matches the request. +/// `isEbook=false` cannot distinguish an audiobook from a physical edition, +/// so the legacy boolean is never sufficient for a write decision. +pub(super) fn edition_usable(edition: &Edition, format: ChaptarrFormat) -> bool { + let declared = edition.format.trim(); + !declared.is_empty() && declared.eq_ignore_ascii_case(format_name(format)) +} + +/// Lookup ranking and cover discovery are non-mutating and can safely tolerate +/// an old projection with no authoritative format. Explicit physical, +/// unrecognized, or opposite-format records are still excluded. +fn edition_projection_compatible(edition: &Edition, format: ChaptarrFormat) -> bool { + let declared = edition.format.trim(); + if !declared.is_empty() { + return declared.eq_ignore_ascii_case(format_name(format)); + } + edition + .is_ebook + .is_none_or(|value| value == (format == ChaptarrFormat::Ebook)) +} + +pub(super) fn usable_edition_count(editions: &[Value], format: ChaptarrFormat) -> usize { + editions + .iter() + .filter_map(parse_edition) + .filter(|edition| edition_usable(edition, format)) + .count() +} + +/// English is a ranking preference only, never a filter: the metadata server +/// returns heavily translation-padded edition lists, and the household's +/// libraries are English. A work with no English edition still resolves. +pub(super) fn is_english(language: &str) -> bool { + matches!( + normalize(language) + .split_whitespace() + .next() + .unwrap_or_default(), + "en" | "eng" | "english" + ) +} + +/// Choose the single edition to monitor, mirroring a manual pick in the +/// Chaptarr UI. Only editions of the requested format are considered; among +/// those, reject companion/summary material and prefer an exact title before +/// considering the projected edition or language. This keeps a projected or +/// English summary from outranking the real work. Public identifiers remain a +/// final indexer-match tiebreaker. +pub(super) fn preferred_edition_index( + editions: &[Value], + format: ChaptarrFormat, + selected: &BookShape, +) -> Option { + editions + .iter() + .enumerate() + .filter_map(|(index, value)| parse_edition(value).map(|edition| (index, edition))) + .filter(|(_, edition)| edition_usable(edition, format)) + .max_by_key(|(index, edition)| { + let title_rank = if edition.title.trim().is_empty() { + 1 + } else { + title_match_tier(&edition.title, &selected.title) + }; + ( + !junk_title(&edition.title), + title_rank, + !edition.foreign_edition_id.is_empty() + && edition.foreign_edition_id == selected.foreign_edition_id, + is_english(&edition.language), + edition.isbn13.is_some() || edition.asin.is_some(), + Reverse(*index), + ) + }) + .map(|(index, _)| index) +} + +/// Pick which duplicate local pocket of the selected work to monitor. Import +/// bugs can leave twin rows for one `foreignBookId` whose edition sets are not +/// equivalent, so a row that actually carries usable requested-format editions +/// beats every row that does not; the usual completeness/popularity ordering +/// only breaks ties. Returns an index into `rows`. +pub(super) fn preferred_pocket( + rows: &[(Value, Vec)], + format: ChaptarrFormat, + selected: &BookShape, +) -> Option { + rows.iter() + .enumerate() + .filter(|(_, (row, _))| local_row_matches_item(row, format, selected)) + .max_by_key(|(index, (row, editions))| { + let usable = usable_edition_count(editions, format); + let shape = parse_book(row).unwrap_or_default(); + ( + usable > 0, + title_match_tier(string_at(row, "title"), &selected.title), + book_complete(row), + usable, + shape.ratings.popularity.to_bits(), + shape.ratings.votes, + shape.release_date, + Reverse(*index), + ) + }) + .map(|(index, _)| index) +} + +/// Exactly-one-monitored-edition read-back: returns the lone monitored +/// edition only when a single one exists and it does not contradict the +/// requested format. Anything else means the request must not proceed. +pub(super) fn sole_monitored_edition( + editions: &[Value], + format: ChaptarrFormat, +) -> Option { + let mut monitored = Vec::new(); + for value in editions { + match value.get("monitored") { + None | Some(Value::Null | Value::Bool(false)) => continue, + Some(Value::Bool(true)) => { + // A malformed monitored row cannot be silently discarded: it + // may be a second selected edition or the only selected one. + let edition = parse_edition(value)?; + if !edition.monitored { + return None; + } + monitored.push(edition); + } + Some(_) => return None, + } + } + match <[Edition; 1]>::try_from(monitored) { + Ok([edition]) if edition_usable(&edition, format) => Some(edition), + _ => None, + } +} + +/// True when the two edition records identify the same edition. Local ids are +/// authoritative; the foreign edition id is the fallback. Unidentifiable +/// records never match, so verification fails closed. +pub(super) fn same_edition(left: &Edition, right: &Edition) -> bool { + if let (Some(a), Some(b)) = (positive_id(Some(&left.id)), positive_id(Some(&right.id))) { + return a == b; + } + !left.foreign_edition_id.trim().is_empty() + && left.foreign_edition_id == right.foreign_edition_id +} + pub(super) fn title_match_tier(candidate: &str, requested: &str) -> u8 { if candidate.trim().is_empty() || requested.trim().is_empty() { return 0; @@ -351,7 +633,6 @@ pub(super) fn needs_author_refresh(book: Option<&Value>) -> bool { } pub(super) fn absolute_cover(book: &BookShape, format: ChaptarrFormat) -> Option { - let expected_ebook = format == ChaptarrFormat::Ebook; book.images .iter() .filter(|i| i.cover_type == "cover") @@ -359,7 +640,7 @@ pub(super) fn absolute_cover(book: &BookShape, format: ChaptarrFormat) -> Option .chain( book.editions .iter() - .filter(|edition| edition.is_ebook.is_none_or(|value| value == expected_ebook)) + .filter(|edition| edition_projection_compatible(edition, format)) .flat_map(|edition| edition.images.iter()), ) .map(|i| i.url.as_str()) @@ -369,11 +650,10 @@ pub(super) fn absolute_cover(book: &BookShape, format: ChaptarrFormat) -> Option } pub(super) fn public_identifier_cover(book: &BookShape, format: ChaptarrFormat) -> Option { - let expected_ebook = format == ChaptarrFormat::Ebook; for edition in book .editions .iter() - .filter(|edition| edition.is_ebook.is_none_or(|value| value == expected_ebook)) + .filter(|edition| edition_projection_compatible(edition, format)) { if let Some(isbn) = edition .isbn13 @@ -470,6 +750,55 @@ pub(super) fn junk_title(title: &str) -> bool { let title = title.to_lowercase(); PHRASES.iter().any(|phrase| title.contains(phrase)) } + +/// Conservatively identify search results that clearly represent several +/// books rather than one work. A plain story "collection" is intentionally +/// not enough; the title must carry a strong multi-book signal. +pub(super) fn clear_multi_book_result_title(title: &str) -> bool { + let normalized = normalize(title); + let words: Vec<_> = normalized.split_whitespace().collect(); + let last = words.last().copied().unwrap_or_default(); + + if matches!(last, "bundle" | "bundles") + || words.contains(&"omnibus") + || words + .windows(2) + .any(|pair| matches!(pair, ["box" | "boxed", "set" | "sets"])) + || last == "trilogy" + || (last == "series" && words.contains(&"complete")) + { + return true; + } + + fn is_multi_count(word: &str) -> bool { + word.parse::().is_ok_and(|count| count > 1) + || matches!( + word, + "two" + | "three" + | "four" + | "five" + | "six" + | "seven" + | "eight" + | "nine" + | "ten" + | "eleven" + | "twelve" + ) + } + + words.windows(3).any(|window| { + is_multi_count(window[0]) + && matches!(window[1], "book" | "books") + && matches!(window[2], "collection" | "set") + }) || words.windows(4).any(|window| { + window[0] == "collection" + && window[1] == "of" + && is_multi_count(window[2]) + && matches!(window[3], "book" | "books") + }) +} #[cfg(test)] mod tests { use super::*; @@ -496,6 +825,8 @@ mod tests { include_str!("../../../tests/fixtures/chaptarr/put_monitor_response.json"); const COMMAND_RESPONSE: &str = include_str!("../../../tests/fixtures/chaptarr/command_response.json"); + const EDITION_FORMATS: &str = + include_str!("../../../tests/fixtures/chaptarr/edition_formats.json"); fn selected_book(title: &str, foreign_book_id: &str) -> BookShape { BookShape { @@ -703,6 +1034,34 @@ mod tests { ); } + #[test] + fn monitoring_readiness_requires_both_generic_and_format_flags() { + let ready = json!({ + "mediaType": "ebook", + "monitored": true, + "ebookMonitored": true + }); + let generic_only = json!({ + "mediaType": "ebook", + "monitored": true, + "ebookMonitored": false + }); + let format_only = json!({ + "mediaType": "ebook", + "monitored": false, + "ebookMonitored": true + }); + + assert!(format_is_monitored(&ready, ChaptarrFormat::Ebook)); + assert!(!format_is_monitored(&generic_only, ChaptarrFormat::Ebook)); + assert!(!format_is_monitored(&format_only, ChaptarrFormat::Ebook)); + assert_eq!( + format_state(&generic_only, ChaptarrFormat::Ebook), + FormatState::Missing, + "a generic-only partial mutation must remain repairable" + ); + } + #[test] fn fixture_states_are_strictly_format_scoped() { let available: Value = serde_json::from_str(AVAILABLE).unwrap(); @@ -830,6 +1189,17 @@ mod tests { assert!( preferred_book(&[same_title_wrong_id], ChaptarrFormat::Ebook, &selected,).is_none() ); + + let same_title_missing_id = json!({ + "id": 9997, + "title": "The Clockwork Orchard", + "mediaType": "ebook" + }); + assert!(!local_row_matches_item( + &same_title_missing_id, + ChaptarrFormat::Ebook, + &selected, + )); } #[test] @@ -857,4 +1227,488 @@ mod tests { "A good book & story" ); } + + #[test] + fn duplicate_pockets_resolve_to_the_row_with_usable_editions() { + // The live incident shape: two local rows for one foreignBookId. The + // twin with only an audiobook-slanted edition must lose an ebook + // request to the row that carries real ebook editions. + let selected = selected_book("Royal Assassin", "hc:54244"); + let starved = json!({ + "id": 40717, + "title": "Royal Assassin", + "foreignBookId": "hc:54244", + "mediaType": "ebook", + "releaseDate": "1996-03-01", + "foreignEditionId": "hc:audio-slanted", + "images": [{"url": "https://covers.example.test/x.jpg"}], + "ratings": {"popularity": 99, "votes": 9000} + }); + let stocked = json!({ + "id": 40510, + "title": "Royal Assassin", + "foreignBookId": "hc:54244", + "mediaType": "ebook", + "releaseDate": "1996-03-01", + "foreignEditionId": "hc:eng-ebook", + "images": [{"url": "https://covers.example.test/y.jpg"}], + "ratings": {"popularity": 1, "votes": 1} + }); + let rows = vec![ + ( + starved, + vec![json!({ + "id": 1, + "format": "audiobook", + "isEbook": false, + "language": "eng" + })], + ), + ( + stocked, + vec![ + json!({"id": 2, "format": "ebook", "isEbook": true, "language": "eng"}), + json!({"id": 3, "format": "ebook", "isEbook": true, "language": "fre"}), + ], + ), + ]; + assert_eq!( + preferred_pocket(&rows, ChaptarrFormat::Ebook, &selected), + Some(1) + ); + // For an audiobook request the starved row is the only usable pocket. + assert_eq!( + preferred_pocket(&rows, ChaptarrFormat::Audiobook, &selected), + None, + "cross-format rows must never match" + ); + } + + #[test] + fn pocket_without_usable_editions_is_still_reported_for_diagnosis() { + let selected = selected_book("The Devils", "hc:devils"); + let pruned = json!({ + "id": 41000, + "title": "The Devils", + "foreignBookId": "hc:devils", + "mediaType": "ebook" + }); + let rows = vec![(pruned, Vec::new())]; + // The row still resolves (so the caller can name the problem), but no + // edition is choosable, which must fail the request loudly. + assert_eq!( + preferred_pocket(&rows, ChaptarrFormat::Ebook, &selected), + Some(0) + ); + assert_eq!( + preferred_edition_index(&[], ChaptarrFormat::Ebook, &selected), + None + ); + } + + #[test] + fn edition_choice_prefers_explicit_format_english_and_exact_title() { + let selected = lookup_book(); + let editions = vec![ + json!({"id": 1, "format": "ebook", "isEbook": true, "language": "ger", "title": "Die Uhrwerk-Plantage"}), + json!({"id": 2, "format": "ebook", "isEbook": true, "language": "eng", "title": "The Clockwork Orchard", "isbn13": "9780000000002"}), + json!({"id": 3, "format": "audiobook", "isEbook": false, "language": "eng", "title": "The Clockwork Orchard"}), + json!({"id": 4, "language": "eng", "title": "The Clockwork Orchard"}), + ]; + assert_eq!( + preferred_edition_index(&editions, ChaptarrFormat::Ebook, &selected), + Some(1) + ); + assert_eq!( + preferred_edition_index(&editions, ChaptarrFormat::Audiobook, &selected), + Some(2) + ); + } + + #[test] + fn authoritative_edition_format_rejects_physical_and_bad_values() { + let editions: Vec = serde_json::from_str(EDITION_FORMATS).unwrap(); + assert_eq!(usable_edition_count(&editions, ChaptarrFormat::Ebook), 1); + assert_eq!( + usable_edition_count(&editions, ChaptarrFormat::Audiobook), + 1, + "a live-shaped physical edition must not count as an audiobook" + ); + + let physical_claiming_ebook = parse_edition(&json!({ + "id": 1, + "format": "physical", + "isEbook": true + })) + .unwrap(); + assert!(!edition_usable( + &physical_claiming_ebook, + ChaptarrFormat::Ebook + )); + assert!(!edition_usable( + &physical_claiming_ebook, + ChaptarrFormat::Audiobook + )); + + let ebook_with_stale_legacy_flag = parse_edition(&json!({ + "id": 2, + "format": "EBOOK", + "isEbook": false + })) + .unwrap(); + assert!(edition_usable( + &ebook_with_stale_legacy_flag, + ChaptarrFormat::Ebook + )); + + let unknown = parse_edition(&json!({ + "id": 3, + "format": "comic", + "isEbook": true + })) + .unwrap(); + assert!(!edition_usable(&unknown, ChaptarrFormat::Ebook)); + + let physical_projection: BookShape = serde_json::from_value(json!({ + "editions": [{"id": 30, "format": "physical", "isEbook": false}] + })) + .unwrap(); + assert_eq!( + search_format_affinity(&physical_projection, ChaptarrFormat::Audiobook), + 0, + "physical-only lookup data must not create audiobook affinity" + ); + + let legacy_ebook = parse_edition(&json!({"id": 4, "isEbook": true})).unwrap(); + let legacy_audio = parse_edition(&json!({"id": 5, "isEbook": false})).unwrap(); + let untyped = parse_edition(&json!({"id": 6})).unwrap(); + assert!(!edition_usable(&legacy_ebook, ChaptarrFormat::Ebook)); + assert!(!edition_usable(&legacy_audio, ChaptarrFormat::Audiobook)); + assert!(!edition_usable(&untyped, ChaptarrFormat::Ebook)); + assert!(!edition_usable(&untyped, ChaptarrFormat::Audiobook)); + assert!(edition_projection_compatible( + &legacy_ebook, + ChaptarrFormat::Ebook + )); + assert!(edition_projection_compatible( + &legacy_audio, + ChaptarrFormat::Audiobook + )); + assert!(edition_projection_compatible( + &untyped, + ChaptarrFormat::Ebook + )); + assert!(edition_projection_compatible( + &untyped, + ChaptarrFormat::Audiobook + )); + assert!(!edition_projection_compatible( + &physical_claiming_ebook, + ChaptarrFormat::Ebook + )); + + let legacy_values = vec![json!({ + "id": 7, + "isEbook": false, + "language": "eng", + "title": "The Clockwork Orchard", + "monitored": true + })]; + assert_eq!( + usable_edition_count(&legacy_values, ChaptarrFormat::Audiobook), + 0 + ); + assert_eq!( + preferred_edition_index(&legacy_values, ChaptarrFormat::Audiobook, &lookup_book()), + None + ); + assert!( + sole_monitored_edition(&legacy_values, ChaptarrFormat::Audiobook).is_none(), + "isEbook=false cannot prove that a monitored row is not physical" + ); + } + + #[test] + fn edition_choice_honors_the_projected_edition_and_demotes_junk() { + let mut selected = lookup_book(); + selected.foreign_edition_id = "hc:edition-3001".into(); + let editions = vec![ + json!({"id": 1, "format": "ebook", "isEbook": true, "language": "eng", "title": "The Clockwork Orchard"}), + json!({"id": 2, "format": "ebook", "isEbook": true, "language": "eng", "title": "The Clockwork Orchard", "foreignEditionId": "hc:edition-3001"}), + ]; + assert_eq!( + preferred_edition_index(&editions, ChaptarrFormat::Ebook, &selected), + Some(1) + ); + + let junky = vec![ + json!({"id": 1, "format": "ebook", "isEbook": true, "language": "eng", "title": "Summary of The Clockwork Orchard"}), + json!({"id": 2, "format": "ebook", "isEbook": true, "language": "eng", "title": "The Clockwork Orchard"}), + ]; + assert_eq!( + preferred_edition_index(&junky, ChaptarrFormat::Ebook, &selected), + Some(1) + ); + + let projected_english_summary = vec![ + json!({ + "id": 1, + "format": "ebook", + "language": "eng", + "title": "Summary of The Clockwork Orchard", + "foreignEditionId": "hc:edition-3001" + }), + json!({ + "id": 2, + "format": "ebook", + "language": "fre", + "title": "The Clockwork Orchard" + }), + ]; + assert_eq!( + preferred_edition_index(&projected_english_summary, ChaptarrFormat::Ebook, &selected), + Some(1), + "the exact non-junk work must beat a projected English summary" + ); + } + + #[test] + fn non_english_only_works_remain_requestable() { + let selected = selected_book("Le Comte", "hc:x"); + let editions = vec![json!({ + "id": 7, + "format": "ebook", + "isEbook": true, + "language": "fre", + "title": "Le Comte" + })]; + assert_eq!( + preferred_edition_index(&editions, ChaptarrFormat::Ebook, &selected), + Some(0) + ); + } + + #[test] + fn english_detection_is_a_preference_marker() { + assert!(is_english("eng")); + assert!(is_english("en-US")); + assert!(is_english("English")); + assert!(!is_english("fre")); + assert!(!is_english("")); + } + + #[test] + fn sole_monitored_edition_requires_exactly_one_of_the_right_format() { + let one = json!({"id": 1, "format": "ebook", "isEbook": true, "monitored": true}); + let other = json!({"id": 2, "format": "ebook", "isEbook": true, "monitored": false}); + let found = sole_monitored_edition(&[one.clone(), other.clone()], ChaptarrFormat::Ebook) + .expect("one monitored ebook edition"); + assert_eq!(positive_id(Some(&found.id)), Some(1)); + + // Zero or two monitored editions is a failed selection. + assert!( + sole_monitored_edition(std::slice::from_ref(&other), ChaptarrFormat::Ebook).is_none() + ); + let second = json!({"id": 3, "format": "ebook", "isEbook": true, "monitored": true}); + assert!(sole_monitored_edition(&[one.clone(), second], ChaptarrFormat::Ebook).is_none()); + // A monitored edition that contradicts the format is a failure too. + assert!(sole_monitored_edition(&[one], ChaptarrFormat::Audiobook).is_none()); + + let valid = json!({ + "id": 4, + "format": "ebook", + "monitored": true + }); + let malformed = json!({ + "id": 5, + "format": 42, + "monitored": true + }); + assert!( + sole_monitored_edition(&[valid, malformed], ChaptarrFormat::Ebook).is_none(), + "a malformed monitored row cannot be discarded during read-back" + ); + assert!( + sole_monitored_edition( + &[json!({"id": 6, "format": "ebook", "monitored": "yes"})], + ChaptarrFormat::Ebook + ) + .is_none() + ); + } + + #[test] + fn edition_identity_fails_closed() { + let by_id = |value: &Value| parse_edition(value).unwrap(); + assert!(same_edition( + &by_id(&json!({"id": 5, "foreignEditionId": "hc:a"})), + &by_id(&json!({"id": 5, "foreignEditionId": "hc:b"})), + )); + assert!(!same_edition( + &by_id(&json!({"id": 5})), + &by_id(&json!({"id": 6})), + )); + assert!(same_edition( + &by_id(&json!({"foreignEditionId": "hc:a"})), + &by_id(&json!({"foreignEditionId": "hc:a"})), + )); + assert!(!same_edition(&by_id(&json!({})), &by_id(&json!({})))); + } + + #[test] + fn catalog_commands_gate_on_author_scope_and_refreshes() { + let scoped_running = json!([{ + "name": "RefreshAuthor", + "status": "started", + "body": {"authorId": 230} + }]); + assert!(catalog_command_active( + scoped_running.as_array().unwrap(), + 230 + )); + // A refresh scoped to a different author is not ours. + assert!(!catalog_command_active( + scoped_running.as_array().unwrap(), + 231 + )); + + let unscoped_refresh = json!([{"name": "RefreshAuthor", "status": "queued"}]); + assert!(catalog_command_active( + unscoped_refresh.as_array().unwrap(), + 230 + )); + let alternate_name = json!([{"commandName": "RefreshAuthor", "status": "started"}]); + assert!(catalog_command_active( + alternate_name.as_array().unwrap(), + 230 + )); + + let finished = json!([{ + "name": "RefreshAuthor", + "status": "completed", + "body": {"authorId": 230} + }]); + assert!(!catalog_command_active(finished.as_array().unwrap(), 230)); + + let unrelated = json!([{"name": "RssSync", "status": "started"}]); + assert!(!catalog_command_active(unrelated.as_array().unwrap(), 230)); + + let id_list = json!([{ + "name": "BulkRefresh", + "status": "started", + "body": {"authorIds": [12, 230]} + }]); + assert!(catalog_command_active(id_list.as_array().unwrap(), 230)); + } + + #[test] + fn book_list_fingerprints_ignore_order_but_track_membership() { + let a = json!({"id": 1, "foreignBookId": "hc:a"}); + let b = json!({"id": 2, "foreignBookId": "hc:b"}); + assert_eq!( + book_list_fingerprint(&[a.clone(), b.clone()]), + book_list_fingerprint(&[b.clone(), a.clone()]) + ); + assert_ne!( + book_list_fingerprint(std::slice::from_ref(&a)), + book_list_fingerprint(&[a, b]) + ); + + let allocated = json!({ + "id": 3, + "foreignBookId": "hc:c", + "title": "Catalog Row", + "mediaType": "ebook" + }); + let populated = json!({ + "id": 3, + "foreignBookId": "hc:c", + "title": "Catalog Row", + "mediaType": "ebook", + "foreignEditionId": "hc:edition-c", + "releaseDate": "2024-01-01", + "images": [{"url": "https://covers.example.test/c.jpg"}] + }); + assert_ne!( + book_list_fingerprint(&[allocated]), + book_list_fingerprint(&[populated]), + "in-place metadata population must reset the settle streak" + ); + } + + #[test] + fn strongest_state_across_duplicate_pockets_wins() { + let selected = selected_book("Royal Assassin", "hc:54244"); + let missing = json!({ + "title": "Royal Assassin", + "foreignBookId": "hc:54244", + "mediaType": "ebook", + "monitored": false + }); + let processing = json!({ + "title": "Royal Assassin", + "foreignBookId": "hc:54244", + "mediaType": "ebook", + "monitored": true, + "ebookMonitored": true + }); + let other_work = json!({ + "title": "Assassin's Quest", + "foreignBookId": "hc:99999", + "mediaType": "ebook", + "hasFiles": true + }); + assert_eq!( + format_state_across( + &[missing.clone(), processing, other_work], + ChaptarrFormat::Ebook, + &selected + ), + FormatState::Processing + ); + assert_eq!( + format_state_across(&[missing], ChaptarrFormat::Ebook, &selected), + FormatState::Missing + ); + assert_eq!( + format_state_across(&[], ChaptarrFormat::Ebook, &selected), + FormatState::Missing + ); + } + + #[test] + fn clear_multi_book_titles_are_detected_conservatively() { + for title in [ + "The Farseer Trilogy 3-Book Bundle", + "The Earthsea Omnibus, Volume One", + "Realm of the Elderlings Box Set", + "Realm of the Elderlings Boxed Sets", + "The Complete Broken Earth Trilogy", + "The Complete Discworld Series", + "Three-Book Collection", + "A Collection of 4 Books", + ] { + assert!( + clear_multi_book_result_title(title), + "expected a clear multi-book result: {title}" + ); + } + + for title in [ + "Stories: A Collection", + "The Lottery and Other Stories", + "Bundle of Joy", + "Trilogy of Terror", + "A Series of Unfortunate Events", + "Fourier Series", + "A Collection of 4 Stories", + "The Book of Three", + "Collected Poems", + ] { + assert!( + !clear_multi_book_result_title(title), + "must not reject an ordinary single-work title: {title}" + ); + } + } } diff --git a/doplarr/tests/fixtures/chaptarr/edition_formats.json b/doplarr/tests/fixtures/chaptarr/edition_formats.json new file mode 100644 index 0000000..dad5ea4 --- /dev/null +++ b/doplarr/tests/fixtures/chaptarr/edition_formats.json @@ -0,0 +1,35 @@ +[ + { + "id": 8101, + "bookId": 4101, + "title": "The Clockwork Orchard", + "foreignEditionId": "hc:edition-ebook", + "format": "ebook", + "isEbook": true, + "language": "eng", + "monitored": false, + "manualAdd": false + }, + { + "id": 8102, + "bookId": 4101, + "title": "The Clockwork Orchard", + "foreignEditionId": "hc:edition-audiobook", + "format": "audiobook", + "isEbook": false, + "language": "eng", + "monitored": false, + "manualAdd": false + }, + { + "id": 8103, + "bookId": 4101, + "title": "The Clockwork Orchard", + "foreignEditionId": "hc:edition-physical", + "format": "physical", + "isEbook": false, + "language": "eng", + "monitored": false, + "manualAdd": false + } +]