From f27e006e576866ad19fe350f5f1907585356eaac Mon Sep 17 00:00:00 2001 From: Brent <25038394+elric667@users.noreply.github.com> Date: Sat, 14 Nov 2026 00:25:25 +0000 Subject: [PATCH 1/5] Back off pending author import retries after the first hour Pending author imports that wait on the metadata server retried every ~5 minutes forever, and every attempt runs a full author refresh. A request that never resolves cost 288 author refreshes a day (#359, #264, #119). Keep the existing cadence for roughly the first hour (three 1-minute retries, then 5-minute retries through attempt 15), then double the delay up to a 6-hour ceiling. Imports still never fail on a transient wait. The shared AuthorRetrySchedule.NextAttempt used by metadata and format sync is unchanged. Also log the "waiting until" line at Warn only on the attempts ShouldWarn already selects (1, 4, every 10th), Debug otherwise. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_018XPvbXWnYFj6KyHWfsjbQt --- .../Books/PendingAuthorImportRetryFixture.cs | 30 +++++++++++++++- .../Books/AuthorRetrySchedule.cs | 35 +++++++++++++++++++ .../Services/PendingAuthorImportService.cs | 5 +-- 3 files changed, 67 insertions(+), 3 deletions(-) diff --git a/src/Chaptarr.Core.Test/Books/PendingAuthorImportRetryFixture.cs b/src/Chaptarr.Core.Test/Books/PendingAuthorImportRetryFixture.cs index fe0e4d50d..967cd5c9f 100644 --- a/src/Chaptarr.Core.Test/Books/PendingAuthorImportRetryFixture.cs +++ b/src/Chaptarr.Core.Test/Books/PendingAuthorImportRetryFixture.cs @@ -194,11 +194,39 @@ public void schedule_retry_should_not_turn_a_transient_wait_into_failure_at_the_ Assert.That(item.OverallStatus, Is.EqualTo(PendingImportStatus.Retrying)); Assert.That(item.AudiobookStatus, Is.EqualTo(PendingImportStatus.Pending)); Assert.That(item.EbookStatus, Is.EqualTo(PendingImportStatus.NotRequested)); - Assert.That(item.NextAttemptAt, Is.InRange(before.AddMinutes(3.9), DateTime.UtcNow.AddMinutes(6.1))); + + // A long-running wait stays Retrying forever, but at the capped backoff rather than every five minutes. + Assert.That(item.NextAttemptAt, Is.InRange(before.AddHours(4.79), DateTime.UtcNow.AddHours(7.21))); Assert.That(repositoryProxy.Updated, Is.SameAs(item)); Assert.That(events.Events, Has.None.InstanceOf()); } + [TestCase(1, 60)] + [TestCase(3, 60)] + [TestCase(4, 300)] + [TestCase(15, 300)] + [TestCase(16, 600)] + [TestCase(17, 1200)] + [TestCase(21, 19200)] + [TestCase(22, 21600)] + [TestCase(8727, 21600)] + [TestCase(int.MaxValue, 21600)] + public void pending_import_retry_should_keep_the_first_hour_fast_then_back_off_to_a_ceiling(int attemptCount, double expectedSeconds) + { + Assert.That(AuthorRetrySchedule.PendingImportDelaySeconds(attemptCount), Is.EqualTo(expectedSeconds)); + } + + [Test] + public void shared_author_retry_schedule_should_keep_its_five_minute_ceiling() + { + // Metadata sync and format sync share NextAttempt; only pending imports back off further. + var before = DateTime.UtcNow; + + var next = AuthorRetrySchedule.NextAttempt(500); + + Assert.That(next, Is.InRange(before.AddSeconds(239), DateTime.UtcNow.AddSeconds(361))); + } + [Test] public void expected_version_status_update_should_leave_a_newer_merged_request_unchanged() { diff --git a/src/NzbDrone.Core/Books/AuthorRetrySchedule.cs b/src/NzbDrone.Core/Books/AuthorRetrySchedule.cs index 64dea1042..13c19850b 100644 --- a/src/NzbDrone.Core/Books/AuthorRetrySchedule.cs +++ b/src/NzbDrone.Core/Books/AuthorRetrySchedule.cs @@ -4,6 +4,14 @@ namespace NzbDrone.Core.Books { internal static class AuthorRetrySchedule { + // Pending author imports keep the original cadence for roughly the first hour + // (three one-minute retries, then five-minute retries), then double the delay up + // to this ceiling. A request the metadata server never fulfils still retries + // forever, but a few times a day instead of 288 attempts (each a full author + // refresh) a day. + internal const int PendingImportFastAttempts = 15; + internal const double PendingImportMaxDelaySeconds = 6 * 60 * 60; + public static bool ShouldWarn(int attemptCount) => attemptCount == 1 || attemptCount == 4 || attemptCount % 10 == 0; public static DateTime NextAttempt(int attemptCount) @@ -11,6 +19,33 @@ public static DateTime NextAttempt(int attemptCount) // Shared with pending author requests: three short retries, then a bounded // five-minute delay. Jitter keeps a recovered server from receiving a burst. var seconds = attemptCount <= 3 ? 60 : 300; + return WithJitter(seconds); + } + + public static DateTime NextPendingImportAttempt(int attemptCount) + { + return WithJitter(PendingImportDelaySeconds(attemptCount)); + } + + internal static double PendingImportDelaySeconds(int attemptCount) + { + if (attemptCount <= 3) + { + return 60; + } + + if (attemptCount <= PendingImportFastAttempts) + { + return 300; + } + + // Cap the exponent so very large legacy attempt counts cannot overflow. + var doublings = Math.Min(attemptCount - PendingImportFastAttempts, 16); + return Math.Min(300 * Math.Pow(2, doublings), PendingImportMaxDelaySeconds); + } + + private static DateTime WithJitter(double seconds) + { return DateTime.UtcNow.AddSeconds(seconds * (0.8 + Random.Shared.NextDouble() * 0.4)); } } diff --git a/src/NzbDrone.Core/Books/Services/PendingAuthorImportService.cs b/src/NzbDrone.Core/Books/Services/PendingAuthorImportService.cs index 4e498a23e..ae2c86c36 100644 --- a/src/NzbDrone.Core/Books/Services/PendingAuthorImportService.cs +++ b/src/NzbDrone.Core/Books/Services/PendingAuthorImportService.cs @@ -1025,7 +1025,7 @@ public void ScheduleRetry(PendingAuthorImport item, string error) current.MaxAttempts = 0; current.LastAttemptAt = DateTime.UtcNow; current.LastError = error; - current.NextAttemptAt = AuthorRetrySchedule.NextAttempt(current.AttemptCount); + current.NextAttemptAt = AuthorRetrySchedule.NextPendingImportAttempt(current.AttemptCount); current.OverallStatus = PendingImportStatus.Retrying; current.UpdatedAt = DateTime.UtcNow; @@ -1042,7 +1042,8 @@ public void ScheduleRetry(PendingAuthorImport item, string error) } CopyMutableState(current, item); - _logger.Warn("Pending import {0} attempt {1} waiting until {2}: {3}", current.Id, current.AttemptCount, current.NextAttemptAt, error); + var level = AuthorRetrySchedule.ShouldWarn(current.AttemptCount) ? LogLevel.Warn : LogLevel.Debug; + _logger.Log(level, "Pending import {0} attempt {1} waiting until {2}: {3}", current.Id, current.AttemptCount, current.NextAttemptAt, error); return; } } From fc3c95d44e347f02e5da4a562687d61eabe30a22 Mon Sep 17 00:00:00 2001 From: Brent <25038394+elric667@users.noreply.github.com> Date: Sat, 21 Nov 2026 01:27:25 +0000 Subject: [PATCH 2/5] Don't push back a request merged in while a retry is scheduled ScheduleRetry re-reads the row and only copies the processed progress when the version is unchanged, but it always replaced NextAttemptAt with the new backoff. If a new request was merged in meanwhile (newer version, due now), it could be delayed by up to seven hours. Keep the newer request's earlier time; the backoff still applies to the request the worker processed. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_018XPvbXLSvnvziBY9jiTQDr --- .../Books/PendingAuthorImportRetryFixture.cs | 48 +++++++++++++++++++ .../Services/PendingAuthorImportService.cs | 8 +++- 2 files changed, 55 insertions(+), 1 deletion(-) diff --git a/src/Chaptarr.Core.Test/Books/PendingAuthorImportRetryFixture.cs b/src/Chaptarr.Core.Test/Books/PendingAuthorImportRetryFixture.cs index 967cd5c9f..a43a4017a 100644 --- a/src/Chaptarr.Core.Test/Books/PendingAuthorImportRetryFixture.cs +++ b/src/Chaptarr.Core.Test/Books/PendingAuthorImportRetryFixture.cs @@ -201,6 +201,54 @@ public void schedule_retry_should_not_turn_a_transient_wait_into_failure_at_the_ Assert.That(events.Events, Has.None.InstanceOf()); } + [Test] + public void schedule_retry_should_not_push_back_a_request_merged_in_after_the_worker_read_it() + { + var repository = DispatchProxy.Create(); + var repositoryProxy = (RepositoryProxy)repository; + var subject = new PendingAuthorImportService(repository, DispatchProxy.Create(), new RecordingEventAggregator(), LogManager.GetCurrentClassLogger()); + + // The worker processed version 5 at attempt 99; meanwhile a new request was merged + // in (version 6) and made due straight away. + var processed = new PendingAuthorImport + { + Id = 42, ProviderId = "gr:42", AttemptCount = 99, Version = 5, + AudiobookStatus = PendingImportStatus.Pending, EbookStatus = PendingImportStatus.NotRequested, + OverallStatus = PendingImportStatus.Retrying + }; + var dueNow = DateTime.UtcNow; + repositoryProxy.Active = new PendingAuthorImport + { + Id = 42, ProviderId = "gr:42", AttemptCount = 99, Version = 6, NextAttemptAt = dueNow, + AudiobookStatus = PendingImportStatus.Pending, EbookStatus = PendingImportStatus.NotRequested, + OverallStatus = PendingImportStatus.Pending + }; + + subject.ScheduleRetry(processed, PendingAuthorImportRetryReason.AuthorNotYetAvailable); + + Assert.That(repositoryProxy.Updated.NextAttemptAt, Is.EqualTo(dueNow)); + } + + [Test] + public void schedule_retry_should_back_off_the_request_the_worker_processed() + { + var repository = DispatchProxy.Create(); + var repositoryProxy = (RepositoryProxy)repository; + var subject = new PendingAuthorImportService(repository, DispatchProxy.Create(), new RecordingEventAggregator(), LogManager.GetCurrentClassLogger()); + var item = new PendingAuthorImport + { + Id = 42, ProviderId = "gr:42", AttemptCount = 99, Version = 5, NextAttemptAt = DateTime.UtcNow, + AudiobookStatus = PendingImportStatus.Pending, EbookStatus = PendingImportStatus.NotRequested, + OverallStatus = PendingImportStatus.Retrying + }; + repositoryProxy.Active = item; + var before = DateTime.UtcNow; + + subject.ScheduleRetry(item, PendingAuthorImportRetryReason.AuthorNotYetAvailable); + + Assert.That(repositoryProxy.Updated.NextAttemptAt, Is.GreaterThan(before.AddHours(4.79))); + } + [TestCase(1, 60)] [TestCase(3, 60)] [TestCase(4, 300)] diff --git a/src/NzbDrone.Core/Books/Services/PendingAuthorImportService.cs b/src/NzbDrone.Core/Books/Services/PendingAuthorImportService.cs index ae2c86c36..cf42c0d2e 100644 --- a/src/NzbDrone.Core/Books/Services/PendingAuthorImportService.cs +++ b/src/NzbDrone.Core/Books/Services/PendingAuthorImportService.cs @@ -1025,7 +1025,13 @@ public void ScheduleRetry(PendingAuthorImport item, string error) current.MaxAttempts = 0; current.LastAttemptAt = DateTime.UtcNow; current.LastError = error; - current.NextAttemptAt = AuthorRetrySchedule.NextPendingImportAttempt(current.AttemptCount); + var backoff = AuthorRetrySchedule.NextPendingImportAttempt(current.AttemptCount); + + // A request merged in after this worker read the row may be due sooner; the backoff + // is for the request this worker processed, so it must not push the newer one back. + current.NextAttemptAt = current.Version != item.Version && current.NextAttemptAt < backoff + ? current.NextAttemptAt + : backoff; current.OverallStatus = PendingImportStatus.Retrying; current.UpdatedAt = DateTime.UtcNow; From e3c9ac020b87e769538686ec3e9a98910e6ec370 Mon Sep 17 00:00:00 2001 From: Brent <25038394+elric667@users.noreply.github.com> Date: Sat, 21 Nov 2026 17:51:04 +0000 Subject: [PATCH 3/5] Re-run CI The macOS job failed on LogRedactionBoundaryFixture, a timing test that also fails intermittently on develop. This empty commit starts a new run. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_018XPvbXLSvnvziBY9jiTQDr From 095e4d5ff6af6558818f44959e262a841a945a4e Mon Sep 17 00:00:00 2001 From: robertlordhood <204023072+robertlordhood@users.noreply.github.com> Date: Fri, 4 Dec 2026 03:57:18 +0000 Subject: [PATCH 4/5] Use the shared retry ladder for pending author imports Waiting authors now step through the same 1m, 5m, 15m, 30m, 1h, 3h ladder as other escalations and then hold at six hours. A new request for a waiting author, from Add Author, Add Book or a list, is checked once straight away and keeps its step on the ladder. A manual retry does the same. A resync that repeats the saved request leaves the schedule alone: requested narrations are compared in their merged form, and the author's own monitor choices after they are restored. A new display name or format tab is saved without touching the schedule. A null edition ID no longer breaks the merge. A worker result that finishes after a merge or a manual retry no longer counts as a failure against the newer schedule. Co-authored-by: elric667 <25038394+elric667@users.noreply.github.com> --- docs/API_IDENTITY_AND_LIFECYCLE.md | 2 +- .../PendingAuthorImportResource.cs | 2 +- src/Chaptarr.Api.V1/openapi.json | 2 +- .../Books/PendingAuthorImportRetryFixture.cs | 228 +++++++++++++++++- .../ImportListCommonConfigurationFixture.cs | 118 +++++++++ .../Books/AuthorRetrySchedule.cs | 37 +-- .../Services/PendingAuthorImportService.cs | 62 ++--- 7 files changed, 379 insertions(+), 72 deletions(-) diff --git a/docs/API_IDENTITY_AND_LIFECYCLE.md b/docs/API_IDENTITY_AND_LIFECYCLE.md index 615cb18d6..13047f2c2 100644 --- a/docs/API_IDENTITY_AND_LIFECYCLE.md +++ b/docs/API_IDENTITY_AND_LIFECYCLE.md @@ -319,7 +319,7 @@ null This means the item is queued or not ready. It is not a final not-found response, and it is not a full resource. -For author imports, Chaptarr keeps the request active without an arbitrary attempt ceiling. It uses its ordinary retry cadence (roughly one minute for the first three attempts, then roughly five minutes with jitter) until the metadata server returns a served payload or a typed declared-stop outcome. `PendingAuthorImportResource.maxAttempts` is `0` for this unbounded lifecycle; `attemptCount` remains an observational counter, not a failure threshold. +For author imports, Chaptarr keeps the request active without an arbitrary attempt ceiling. It waits about 1, 5, 15 and 30 minutes, then 1, 3 and 6 hours, staying at 6 hours (each with jitter), until the metadata server returns a served payload or a typed declared-stop outcome. `PendingAuthorImportResource.maxAttempts` is `0` for this unbounded lifecycle; `attemptCount` is not a failure threshold; it sets the wait. A later request that adds something new is checked once straight away; `attemptCount` is not reset. When a book add queues an author that is not available yet, `addOptions.searchForNewBook=true` remains attached to that exact media-specific request. `PendingAuthorImportResource.audiobookBooksToSearch` and `ebookBooksToSearch` expose the queued provider IDs; they are durable provider identities, not local Book row IDs. Once the authoritative author catalog imports, Chaptarr resolves those IDs within the requested media type and queues an exact Book search. If the imported catalog does not contain a requested provider ID, Chaptarr logs the missing target and does not broaden the search or synthesize a Book. diff --git a/src/Chaptarr.Api.V1/PendingImport/PendingAuthorImportResource.cs b/src/Chaptarr.Api.V1/PendingImport/PendingAuthorImportResource.cs index 08059b9f0..dc7b47eea 100644 --- a/src/Chaptarr.Api.V1/PendingImport/PendingAuthorImportResource.cs +++ b/src/Chaptarr.Api.V1/PendingImport/PendingAuthorImportResource.cs @@ -52,7 +52,7 @@ public class PendingAuthorImportResource : RestResource public DateTime? UpdatedAt { get; set; } public DateTime? LastAttemptAt { get; set; } public DateTime NextAttemptAt { get; set; } - [SwaggerSchema("Observational retry count; it is not a terminal-failure threshold.")] + [SwaggerSchema("Retry count that sets the next wait; it is not a terminal-failure threshold.")] public int AttemptCount { get; set; } [SwaggerSchema("Zero means the transient/not-ready retry lifecycle is unbounded. Typed 404/409 outcomes stop automatic retrying instead.")] public int MaxAttempts { get; set; } diff --git a/src/Chaptarr.Api.V1/openapi.json b/src/Chaptarr.Api.V1/openapi.json index cf310ccbb..2c9067bc5 100644 --- a/src/Chaptarr.Api.V1/openapi.json +++ b/src/Chaptarr.Api.V1/openapi.json @@ -20964,7 +20964,7 @@ }, "attemptCount": { "type": "integer", - "description": "Observational retry count; it is not a terminal-failure threshold.", + "description": "Retry count that sets the next wait; it is not a terminal-failure threshold.", "format": "int32" }, "maxAttempts": { diff --git a/src/Chaptarr.Core.Test/Books/PendingAuthorImportRetryFixture.cs b/src/Chaptarr.Core.Test/Books/PendingAuthorImportRetryFixture.cs index a43a4017a..6a16b3242 100644 --- a/src/Chaptarr.Core.Test/Books/PendingAuthorImportRetryFixture.cs +++ b/src/Chaptarr.Core.Test/Books/PendingAuthorImportRetryFixture.cs @@ -159,7 +159,7 @@ public void metadata_202_hint_should_preserve_the_existing_later_attempt_schedul var reloaded = new PendingAuthorImportService(new PendingAuthorImportRepository(database, events), authors, events, LogManager.GetCurrentClassLogger()); var saved = reloaded.GetByProviderId("hc:9001"); - Assert.That(saved.NextAttemptAt, Is.InRange(before.AddSeconds(239), DateTime.UtcNow.AddSeconds(361))); + Assert.That(saved.NextAttemptAt, Is.InRange(before.AddMinutes(23.9), DateTime.UtcNow.AddMinutes(36.1))); Assert.That(saved.AttemptCount, Is.EqualTo(4)); Assert.That(saved.OverallStatus, Is.EqualTo(PendingImportStatus.Retrying)); Assert.That(reloaded.GetDueForProcessing(), Is.Empty); @@ -210,13 +210,13 @@ public void schedule_retry_should_not_push_back_a_request_merged_in_after_the_wo // The worker processed version 5 at attempt 99; meanwhile a new request was merged // in (version 6) and made due straight away. + var dueNow = DateTime.UtcNow; var processed = new PendingAuthorImport { - Id = 42, ProviderId = "gr:42", AttemptCount = 99, Version = 5, + Id = 42, ProviderId = "gr:42", AttemptCount = 99, Version = 5, NextAttemptAt = dueNow.AddHours(-6), AudiobookStatus = PendingImportStatus.Pending, EbookStatus = PendingImportStatus.NotRequested, OverallStatus = PendingImportStatus.Retrying }; - var dueNow = DateTime.UtcNow; repositoryProxy.Active = new PendingAuthorImport { Id = 42, ProviderId = "gr:42", AttemptCount = 99, Version = 6, NextAttemptAt = dueNow, @@ -226,7 +226,11 @@ public void schedule_retry_should_not_push_back_a_request_merged_in_after_the_wo subject.ScheduleRetry(processed, PendingAuthorImportRetryReason.AuthorNotYetAvailable); - Assert.That(repositoryProxy.Updated.NextAttemptAt, Is.EqualTo(dueNow)); + Assert.That(repositoryProxy.FencedUpdateCount, Is.Zero); + Assert.That(repositoryProxy.Active.NextAttemptAt, Is.EqualTo(dueNow)); + Assert.That(repositoryProxy.Active.AttemptCount, Is.EqualTo(99)); + Assert.That(repositoryProxy.Active.LastError, Is.Null); + Assert.That(processed.Version, Is.EqualTo(6)); } [Test] @@ -250,18 +254,216 @@ public void schedule_retry_should_back_off_the_request_the_worker_processed() } [TestCase(1, 60)] - [TestCase(3, 60)] - [TestCase(4, 300)] - [TestCase(15, 300)] - [TestCase(16, 600)] - [TestCase(17, 1200)] - [TestCase(21, 19200)] - [TestCase(22, 21600)] + [TestCase(2, 300)] + [TestCase(3, 900)] + [TestCase(4, 1800)] + [TestCase(5, 3600)] + [TestCase(6, 10800)] + [TestCase(7, 21600)] + [TestCase(8, 21600)] [TestCase(8727, 21600)] [TestCase(int.MaxValue, 21600)] public void pending_import_retry_should_keep_the_first_hour_fast_then_back_off_to_a_ceiling(int attemptCount, double expectedSeconds) { - Assert.That(AuthorRetrySchedule.PendingImportDelaySeconds(attemptCount), Is.EqualTo(expectedSeconds)); + var before = DateTime.UtcNow; + var next = AuthorRetrySchedule.NextPendingImportAttempt(attemptCount); + Assert.That(next, Is.InRange(before.AddSeconds(expectedSeconds * 0.8), DateTime.UtcNow.AddSeconds(expectedSeconds * 1.2))); + } + + [Test] + [NonParallelizable] + public void pending_import_attempts_persist_the_ladder([Values(false, true)] bool postgres) + { + DualDatabaseFixture.Run(postgres, database => + { + var events = new RecordingEventAggregator(); + var repository = new PendingAuthorImportRepository(database, events); + var pending = new PendingAuthorImportService(repository, DispatchProxy.Create(), + events, LogManager.GetCurrentClassLogger()); + var id = pending.EnqueueAsync("hc:9001", new MonitoringConfig + { + AuthorName = "Queued author", CreateAudiobook = true, AudiobookBooksToAdd = new List { "hc:1001" } + }, "UserInterface").GetAwaiter().GetResult(); + var ladder = new[] { 60, 300, 900, 1800, 3600, 10800, 21600, 21600 }; + + for (var attempt = 1; attempt <= ladder.Length; attempt++) + { + var before = DateTime.UtcNow; + pending.ScheduleRetry(repository.Find(id), "Still waiting"); + var saved = repository.Find(id); + Assert.That(saved.AttemptCount, Is.EqualTo(attempt)); + Assert.That(saved.NextAttemptAt, Is.InRange(before.AddSeconds(ladder[attempt - 1] * 0.8 - 1), + DateTime.UtcNow.AddSeconds(ladder[attempt - 1] * 1.2 + 1)), $"attempt {attempt}"); + } + }); + } + + [Test] + [NonParallelizable] + public void an_identical_list_resync_preserves_pending_backoff( + [Values(false, true)] bool postgres, [Values(BookMediaType.Audiobook, BookMediaType.Ebook)] BookMediaType mediaType, + [Values("gr:5001", null)] string editionProviderId) + { + DualDatabaseFixture.Run(postgres, database => + { + var events = new RecordingEventAggregator(); + var repository = new PendingAuthorImportRepository(database, events); + var pending = new PendingAuthorImportService(repository, DispatchProxy.Create(), + events, LogManager.GetCurrentClassLogger()); + var ebook = mediaType == BookMediaType.Ebook; + + // A requested edition with no narrator names, exactly as list sync builds it on every run. + // Add Book can also send one with no edition ID (a manual edition without provider IDs). + MonitoringConfig Request() => new() + { + AuthorName = "List author", QueueIfUnavailable = true, RequestedBy = "ImportList:Shelf", + CreateAudiobook = !ebook, CreateEbook = ebook, + AudiobookBooksToMonitor = ebook ? null : new List { "hc:1001" }, + EbookBooksToMonitor = ebook ? new List { "hc:1001" } : null, + AudiobookNarrations = new List + { + new() { MediaType = mediaType, WorkProviderId = "hc:1001", EditionProviderId = editionProviderId, RequiresEdition = true, Search = true } + } + }; + + var id = pending.EnqueueAsync("hc:9001", Request(), "ImportList:Shelf").GetAwaiter().GetResult(); + var waiting = repository.Find(id); + waiting.AttemptCount = 5; + waiting.NextAttemptAt = DateTime.UtcNow.AddHours(1); + waiting.OverallStatus = PendingImportStatus.Retrying; + Assert.That(repository.TryUpdateRequest(waiting, waiting.Version), Is.True); + var before = repository.Find(id); + + for (var sync = 1; sync <= 3; sync++) + { + Assert.That(pending.EnqueueAsync("hc:9001", Request(), "ImportList:Shelf").GetAwaiter().GetResult(), Is.EqualTo(id)); + var after = repository.Find(id); + Assert.That(after.AttemptCount, Is.EqualTo(5), $"sync {sync}"); + Assert.That(after.NextAttemptAt, Is.EqualTo(before.NextAttemptAt), $"sync {sync}"); + Assert.That(after.Version, Is.EqualTo(before.Version), $"sync {sync}"); + } + }); + } + + [Test] + [NonParallelizable] + public void list_demand_that_differs_only_in_the_authors_own_choices_preserves_pending_backoff([Values(false, true)] bool postgres) + { + DualDatabaseFixture.Run(postgres, database => + { + var events = new RecordingEventAggregator(); + var repository = new PendingAuthorImportRepository(database, events); + var pending = new PendingAuthorImportService(repository, DispatchProxy.Create(), + events, LogManager.GetCurrentClassLogger()); + + // Added by hand with nothing monitored while the author's metadata was not ready. + var id = pending.EnqueueAsync("hc:9001", new MonitoringConfig + { + AuthorName = "Hand-added author", QueueIfUnavailable = true, IsAuthorSettingsRequest = true, + CreateAudiobook = true, AudiobookMonitored = false, + AudiobookMonitorExistingMode = MonitorTypes.None, AudiobookMonitorNewItems = NewItemMonitorTypes.None + }, MonitoringConfig.NativeAuthorAddOrigin).GetAwaiter().GetResult(); + + // A list that monitors one of the author's books, sent the same way on every sync. + MonitoringConfig ListRequest() => new() + { + AuthorName = "Hand-added author", QueueIfUnavailable = true, RequestedBy = "ImportList:Shelf", + CreateAudiobook = true, AudiobookMonitored = true, + AudiobookMonitorExistingMode = MonitorTypes.SpecificBook, AudiobookMonitorNewItems = NewItemMonitorTypes.All, + AudiobookBooksToMonitor = new List { "hc:1001" } + }; + + // The first sync brings new demand: the listed book. + pending.EnqueueAsync("hc:9001", ListRequest(), "ImportList:Shelf").GetAwaiter().GetResult(); + var waiting = repository.Find(id); + waiting.AttemptCount = 5; + waiting.NextAttemptAt = DateTime.UtcNow.AddHours(1); + waiting.OverallStatus = PendingImportStatus.Retrying; + Assert.That(repository.TryUpdateRequest(waiting, waiting.Version), Is.True); + var before = repository.Find(id); + + for (var sync = 1; sync <= 3; sync++) + { + Assert.That(pending.EnqueueAsync("hc:9001", ListRequest(), "ImportList:Shelf").GetAwaiter().GetResult(), Is.EqualTo(id)); + var after = repository.Find(id); + Assert.That(after.AttemptCount, Is.EqualTo(5), $"sync {sync}"); + Assert.That(after.NextAttemptAt, Is.EqualTo(before.NextAttemptAt), $"sync {sync}"); + Assert.That(after.Version, Is.EqualTo(before.Version), $"sync {sync}"); + Assert.That(after.AudiobookMonitored, Is.False, $"sync {sync}"); + Assert.That(after.AudiobookMonitorExistingMode, Is.EqualTo(MonitorTypes.None), $"sync {sync}"); + Assert.That(after.AudiobookMonitorNewItems, Is.EqualTo(NewItemMonitorTypes.None), $"sync {sync}"); + } + }); + } + + [Test] + [NonParallelizable] + public void pending_import_checks_keep_the_schedule_owned_by_the_latest_request( + [Values(false, true)] bool postgres, [Values("book", "name", "tab", "retry", "narration")] string change) + { + DualDatabaseFixture.Run(postgres, database => + { + var events = new RecordingEventAggregator(); + var repository = new PendingAuthorImportRepository(database, events); + var pending = new PendingAuthorImportService(repository, DispatchProxy.Create(), + events, LogManager.GetCurrentClassLogger()); + MonitoringConfig Request(string name, string work, string tab = "audiobook") => new() + { + AuthorName = name, LastSelectedMediaType = tab, CreateAudiobook = true, AudiobookBooksToAdd = new List { work }, + AudiobookNarrations = change == "narration" ? new List + { + new() { WorkProviderId = work, EditionProviderId = "gr:5001", RequiresEdition = true, Search = true } + } : null + }; + var id = pending.EnqueueAsync("hc:9001", Request("Original name", "hc:1001"), "UserInterface").GetAwaiter().GetResult(); + var queued = repository.Find(id); + queued.AttemptCount = 99; + queued.NextAttemptAt = DateTime.UtcNow.AddHours(1); + queued.OverallStatus = PendingImportStatus.Retrying; + Assert.That(repository.TryUpdateRequest(queued, queued.Version), Is.True); + + // The worker read this row, then the change below lands before its result is saved. + var earlierCheck = repository.Find(id); + if (change == "retry") + { + pending.RetryNow(id); + } + else + { + pending.EnqueueAsync("hc:9001", change == "tab" + ? Request("Original name", "hc:1001", "ebook") + : Request("Display name", change == "book" ? "hc:1002" : "hc:1001"), "UserInterface").GetAwaiter().GetResult(); + } + + var saved = repository.Find(id); + var before = DateTime.UtcNow; + Assert.That(saved.AttemptCount, Is.EqualTo(99)); + if (change is "name" or "tab" or "narration") + { + // A display change is not new demand: the schedule stays and the result counts. + Assert.That(saved.Version, Is.Not.EqualTo(earlierCheck.Version)); + Assert.That(saved.LastSelectedMediaType, Is.EqualTo(change == "tab" ? "ebook" : "audiobook")); + Assert.That(saved.NextAttemptAt, Is.EqualTo(earlierCheck.NextAttemptAt)); + pending.ScheduleRetry(earlierCheck, "Still waiting"); + Assert.That(repository.Find(id).NextAttemptAt, Is.InRange(before.AddHours(4.79), DateTime.UtcNow.AddHours(7.21))); + Assert.That(repository.Find(id).AttemptCount, Is.EqualTo(100)); + return; + } + + Assert.That(pending.GetDueForProcessing().ConvertAll(row => row.Id), Is.EqualTo(new[] { id })); + + pending.ScheduleRetry(earlierCheck, "Result from previous attempt"); + var afterStaleResult = repository.Find(id); + Assert.That(afterStaleResult.Version, Is.EqualTo(saved.Version)); + Assert.That(afterStaleResult.NextAttemptAt, Is.EqualTo(saved.NextAttemptAt)); + Assert.That(afterStaleResult.AttemptCount, Is.EqualTo(saved.AttemptCount)); + Assert.That(afterStaleResult.LastError, Is.EqualTo(saved.LastError)); + + pending.ScheduleRetry(afterStaleResult, "Still waiting"); + var checkedRequest = repository.Find(id); + Assert.That(checkedRequest.AttemptCount, Is.EqualTo(100)); + Assert.That(checkedRequest.NextAttemptAt, Is.InRange(before.AddHours(4.79), DateTime.UtcNow.AddHours(7.21))); + }); } [Test] @@ -846,6 +1048,8 @@ await subject.EnqueueAsync( Assert.That(repositoryProxy.Active.AudiobookMonitorNewItems, Is.EqualTo(NewItemMonitorTypes.All)); Assert.That(repositoryProxy.Active.EbookMonitorExistingMode, Is.EqualTo(MonitorTypes.All)); Assert.That(repositoryProxy.Active.EbookMonitorNewItems, Is.EqualTo(NewItemMonitorTypes.None)); + // Widening the monitor mode is the only change, and it is saved. + Assert.That(repositoryProxy.FencedUpdateCount, Is.EqualTo(1)); } [Test] diff --git a/src/Chaptarr.Core.Test/ImportLists/ImportListCommonConfigurationFixture.cs b/src/Chaptarr.Core.Test/ImportLists/ImportListCommonConfigurationFixture.cs index f723ff9d0..a593950ff 100644 --- a/src/Chaptarr.Core.Test/ImportLists/ImportListCommonConfigurationFixture.cs +++ b/src/Chaptarr.Core.Test/ImportLists/ImportListCommonConfigurationFixture.cs @@ -81,6 +81,124 @@ public void cleared_format_tags_should_not_reapply_list_classification_tags(int Verify(provider, postgres, 3, false, 1, true); } + [TestCase(false, false)] + [TestCase(true, false)] + [TestCase(false, true)] + [TestCase(true, true)] + public void repeated_list_sync_keeps_a_waiting_author_on_its_retry_schedule(bool postgres, bool handAdded) + { + DualDatabaseFixture.Run(postgres, database => + { + var logger = LogManager.GetCurrentClassLogger(); + var events = Proxy((method, args) => null); + var author = new Author { Name = "Waiting Author", GoodreadsAuthorId = "gr:7101" }; + var noAuthors = new List(); + var authorService = Proxy((method, args) => method.Name switch + { + nameof(IAuthorService.GetAllAuthors) => noAuthors, + nameof(IAuthorService.GetExistingAuthors) => noAuthors, + nameof(IAuthorService.FindByProviderId) => null, + _ => throw new AssertionException(method.Name) + }); + var editions = new EditionService(new EditionRepository(database, events), events, logger); + var books = new BookService(new BookRepository(database, events), editions, events, authorService, + Proxy((method, args) => new List()), null, + new SeriesBookLinkRepository(database, events), null, logger); + var audiobookRoot = BuildAudiobookRoot(@"C:\Audio".AsOsAgnostic()); + audiobookRoot.SetAudiobookSettings(new MediaTypeSettings + { + QualityProfileId = 3, MetadataProfileId = 4, Monitored = true, + MonitorExistingMode = MonitorTypes.Missing, MonitorNewItems = NewItemMonitorTypes.New + }); + var roots = new StubRootFolderService(audiobookRoot, BuildEbookRoot(@"C:\Ebooks".AsOsAgnostic())); + var queue = Proxy((method, args) => new CommandModel { Body = (Command)args[0] }); + var repository = new PendingAuthorImportRepository(database, events); + var pending = new PendingAuthorImportService(repository, authorService, events, logger); + if (handAdded) + { + // Added by hand with nothing monitored while the author's metadata was not ready. + pending.EnqueueAsync(author.GoodreadsAuthorId, new MonitoringConfig + { + AuthorName = author.Name, QueueIfUnavailable = true, IsAuthorSettingsRequest = true, + CreateAudiobook = true, AudiobookMonitored = false, AudiobookRootFolderPath = audiobookRoot.Path, + AudiobookMonitorExistingMode = MonitorTypes.None, AudiobookMonitorNewItems = NewItemMonitorTypes.None + }, MonitoringConfig.NativeAuthorAddOrigin).GetAwaiter().GetResult(); + } + + // A narrated edition, exactly as the list returns it on every sync. + var reports = new List + { + new() + { + ImportListId = 1, Author = author.Name, AuthorProviderId = author.GoodreadsAuthorId, + Book = "Waiting Work", BookProviderId = "gr:8101", EditionProviderId = "gr:9101", + EditionMediaType = BookMediaType.Audiobook, EditionHasNarration = true, + EditionNarratorNames = new List { "Ann Reader" } + } + }; + var sync = ImportListSyncServiceSearchOnAddFixture.BuildMissingMediaSideService(author, new Book(), BookMediaType.Audiobook, true, + authorService, books, editions, pending, roots, queue, newAuthor: true, reports: reports, keep: false); + + sync.Execute(new ImportListSyncCommand(1)); + var id = pending.GetByProviderId(author.GoodreadsAuthorId).Id; + var waiting = repository.Find(id); + waiting.AttemptCount = 5; + waiting.NextAttemptAt = DateTime.UtcNow.AddHours(1); + waiting.OverallStatus = PendingImportStatus.Retrying; + Assert.That(repository.TryUpdateRequest(waiting, waiting.Version), Is.True); + var settings = repository.Find(id); + + for (var run = 1; run <= 3; run++) + { + // The worker finds the author still not ready, then the list syncs again. + pending.ScheduleRetry(repository.Find(id), "Metadata for gr:7101 is not ready"); + var retried = repository.Find(id); + sync.Execute(new ImportListSyncCommand(1)); + var after = repository.Find(id); + Assert.Multiple(() => + { + Assert.That(after.AttemptCount, Is.EqualTo(5 + run), $"run {run}"); + Assert.That(after.NextAttemptAt, Is.EqualTo(retried.NextAttemptAt), $"run {run}"); + Assert.That(after.NextAttemptAt, Is.GreaterThan(DateTime.UtcNow.AddHours(2)), $"run {run}"); + Assert.That(after.Version, Is.EqualTo(retried.Version), $"run {run}"); + Assert.That(after.AudiobookNarrations, Is.EqualTo(settings.AudiobookNarrations), $"run {run}"); + Assert.That(after.AudiobookMonitored, Is.EqualTo(settings.AudiobookMonitored), $"run {run}"); + Assert.That(after.AudiobookMonitorExistingMode, Is.EqualTo(settings.AudiobookMonitorExistingMode), $"run {run}"); + Assert.That(after.AudiobookMonitorNewItems, Is.EqualTo(settings.AudiobookMonitorNewItems), $"run {run}"); + }); + } + + // The list gains a book: the author is checked straight away and keeps its step. + reports.Add(new ImportListItemInfo + { + ImportListId = 1, Author = author.Name, AuthorProviderId = author.GoodreadsAuthorId, + Book = "Second Work", BookProviderId = "gr:8102", EditionProviderId = "gr:9102", + EditionMediaType = BookMediaType.Audiobook, EditionHasNarration = true, + EditionNarratorNames = new List { "Ann Reader" } + }); + sync = ImportListSyncServiceSearchOnAddFixture.BuildMissingMediaSideService(author, new Book(), BookMediaType.Audiobook, true, + authorService, books, editions, pending, roots, queue, newAuthor: true, reports: reports, keep: false); + var beforeNewBook = repository.Find(id); + sync.Execute(new ImportListSyncCommand(1)); + var added = repository.Find(id); + Assert.That(added.Version, Is.Not.EqualTo(beforeNewBook.Version)); + Assert.That(added.AttemptCount, Is.EqualTo(8)); + Assert.That(pending.GetDueForProcessing().ConvertAll(row => row.Id), Is.EqualTo(new[] { id })); + var before = DateTime.UtcNow; + pending.ScheduleRetry(added, "Metadata for gr:7101 is not ready"); + var checkedRequest = repository.Find(id); + Assert.That(checkedRequest.AttemptCount, Is.EqualTo(9)); + Assert.That(checkedRequest.NextAttemptAt, Is.InRange(before.AddHours(4.79), DateTime.UtcNow.AddHours(7.21))); + + if (handAdded) + { + Assert.That(settings.AudiobookMonitored, Is.False); + Assert.That(settings.AudiobookMonitorExistingMode, Is.EqualTo(MonitorTypes.None)); + Assert.That(settings.AudiobookMonitorNewItems, Is.EqualTo(NewItemMonitorTypes.None)); + } + }); + } + private static void Verify(int provider, bool postgres, int sides, bool existingAudio, int authorCount, bool clearTags = false) { DualDatabaseFixture.Run(postgres, database => diff --git a/src/NzbDrone.Core/Books/AuthorRetrySchedule.cs b/src/NzbDrone.Core/Books/AuthorRetrySchedule.cs index 13c19850b..1b8be2040 100644 --- a/src/NzbDrone.Core/Books/AuthorRetrySchedule.cs +++ b/src/NzbDrone.Core/Books/AuthorRetrySchedule.cs @@ -1,48 +1,27 @@ using System; +using NzbDrone.Core.ThingiProvider.Status; namespace NzbDrone.Core.Books { internal static class AuthorRetrySchedule { - // Pending author imports keep the original cadence for roughly the first hour - // (three one-minute retries, then five-minute retries), then double the delay up - // to this ceiling. A request the metadata server never fulfils still retries - // forever, but a few times a day instead of 288 attempts (each a full author - // refresh) a day. - internal const int PendingImportFastAttempts = 15; - internal const double PendingImportMaxDelaySeconds = 6 * 60 * 60; - public static bool ShouldWarn(int attemptCount) => attemptCount == 1 || attemptCount == 4 || attemptCount % 10 == 0; public static DateTime NextAttempt(int attemptCount) { - // Shared with pending author requests: three short retries, then a bounded + // Author refresh and local format setup: three short retries, then a bounded // five-minute delay. Jitter keeps a recovered server from receiving a burst. var seconds = attemptCount <= 3 ? 60 : 300; return WithJitter(seconds); } - public static DateTime NextPendingImportAttempt(int attemptCount) - { - return WithJitter(PendingImportDelaySeconds(attemptCount)); - } + // Index of the six-hour step in EscalationBackOff.Periods. + private const int PendingImportCeilingStep = 7; - internal static double PendingImportDelaySeconds(int attemptCount) - { - if (attemptCount <= 3) - { - return 60; - } - - if (attemptCount <= PendingImportFastAttempts) - { - return 300; - } - - // Cap the exponent so very large legacy attempt counts cannot overflow. - var doublings = Math.Min(attemptCount - PendingImportFastAttempts, 16); - return Math.Min(300 * Math.Pow(2, doublings), PendingImportMaxDelaySeconds); - } + // A request the metadata server never fulfils still retries forever, but on the shared + // escalation ladder capped at its six-hour step instead of 288 full author refreshes a day. + public static DateTime NextPendingImportAttempt(int attemptCount) => + WithJitter(EscalationBackOff.Periods[Math.Clamp(attemptCount, 1, PendingImportCeilingStep)]); private static DateTime WithJitter(double seconds) { diff --git a/src/NzbDrone.Core/Books/Services/PendingAuthorImportService.cs b/src/NzbDrone.Core/Books/Services/PendingAuthorImportService.cs index cf42c0d2e..53fc0a641 100644 --- a/src/NzbDrone.Core/Books/Services/PendingAuthorImportService.cs +++ b/src/NzbDrone.Core/Books/Services/PendingAuthorImportService.cs @@ -124,8 +124,8 @@ public Task EnqueueAsync(string providerId, MonitoringConfig config, string existing.ExplicitBookSearches = explicitJson; updated = true; } - var nameChanged = !string.IsNullOrWhiteSpace(config.AuthorName) && config.AuthorName != existing.AuthorName; - if (nameChanged) existing.AuthorName = config.AuthorName; + var displayChanged = !string.IsNullOrWhiteSpace(config.AuthorName) && config.AuthorName != existing.AuthorName; + if (displayChanged) existing.AuthorName = config.AuthorName; if (config.CreateAudiobook && existing.HasAudiobook() && existing.AudiobookBooksToMonitor == null && config.AudiobookBooksToMonitor != null || config.CreateEbook && existing.HasEbook() && existing.EbookBooksToMonitor == null && config.EbookBooksToMonitor != null) { @@ -147,8 +147,9 @@ public Task EnqueueAsync(string providerId, MonitoringConfig config, string } if (config.AudiobookNarrations?.Any() == true) { + // Both sides in merged form, so repeating the saved request is not new demand. var json = MergeRequestedNarrations(existing.AudiobookNarrations, config.AudiobookNarrations); - if (json != existing.AudiobookNarrations) + if (json != MergeRequestedNarrations(existing.AudiobookNarrations, Array.Empty())) { existing.AudiobookNarrations = json; updated = true; @@ -212,7 +213,6 @@ public Task EnqueueAsync(string providerId, MonitoringConfig config, string out var audiobookMonitorExistingMode)) { existing.AudiobookMonitorExistingMode = audiobookMonitorExistingMode; - updated = true; } // An additional request may enable the side, but never turns an @@ -221,7 +221,6 @@ public Task EnqueueAsync(string providerId, MonitoringConfig config, string if (config.CreateAudiobook && config.AudiobookMonitored == true && existing.AudiobookMonitored != true) { existing.AudiobookMonitored = true; - updated = true; } if (config.CreateAudiobook && MergeNewItemMonitorType( @@ -230,7 +229,6 @@ public Task EnqueueAsync(string providerId, MonitoringConfig config, string out var audiobookMonitorNewItems)) { existing.AudiobookMonitorNewItems = audiobookMonitorNewItems; - updated = true; } if (config.CreateAudiobook && TryMergeTags( @@ -286,7 +284,6 @@ public Task EnqueueAsync(string providerId, MonitoringConfig config, string if (config.CreateEbook && config.EbookMonitored == true && existing.EbookMonitored != true) { existing.EbookMonitored = true; - updated = true; } if (config.CreateEbook && MergeNewItemMonitorType( @@ -295,7 +292,6 @@ public Task EnqueueAsync(string providerId, MonitoringConfig config, string out var ebookMonitorNewItems)) { existing.EbookMonitorNewItems = ebookMonitorNewItems; - updated = true; } if (config.CreateEbook && TryMergeProviderIds(existing.EbookBooksToAdd, @@ -311,7 +307,6 @@ public Task EnqueueAsync(string providerId, MonitoringConfig config, string out var ebookMonitorExistingMode)) { existing.EbookMonitorExistingMode = ebookMonitorExistingMode; - updated = true; } if (config.CreateEbook && TryMergeProviderIds( @@ -352,7 +347,7 @@ public Task EnqueueAsync(string providerId, MonitoringConfig config, string !string.Equals(existing.LastSelectedMediaType, config.LastSelectedMediaType, StringComparison.OrdinalIgnoreCase)) { existing.LastSelectedMediaType = config.LastSelectedMediaType; - updated = true; + displayChanged = true; } // Preserve discovered author folder path if provided and not already set @@ -371,6 +366,12 @@ public Task EnqueueAsync(string providerId, MonitoringConfig config, string existing.AudiobookMonitored = gates.AudiobookMonitored ?? existing.AudiobookMonitored; existing.EbookMonitored = gates.EbookMonitored ?? existing.EbookMonitored; } + + // Judged on the final values: list demand that differs only in the author's own + // choices restored above is not new demand. + updated |= (existing.AudiobookMonitorExistingMode, existing.EbookMonitorExistingMode) != initialChoices || + (existing.AudiobookMonitorNewItems, existing.EbookMonitorNewItems) != newChoices || + (existing.AudiobookMonitored, existing.EbookMonitored) != gates; if ((config.IsAuthorSettingsRequest || config.RequestedBy == MonitoringConfig.NativeAuthorAddOrigin) && config.SyncMonitoredAcrossFormats.HasValue && existing.SyncMonitoredAcrossFormats != config.SyncMonitoredAcrossFormats) { @@ -395,12 +396,13 @@ public Task EnqueueAsync(string providerId, MonitoringConfig config, string } } - if (updated || nameChanged) + if (updated || displayChanged) { existing.UpdatedAt = DateTime.UtcNow; if (updated) { - // Changed request intent needs processing; a display-name update preserves the schedule. + // New demand is checked once straight away and keeps its step on the ladder. + // A display change (the name, or the format tab last used) keeps the schedule. existing.NextAttemptAt = DateTime.UtcNow; existing.UpdateOverallStatus(); } @@ -646,12 +648,15 @@ private static List ParseRequestedNarrations(string json, bo .ThenBy(request => request.Search).ToList(); } + private static (BookMediaType MediaType, string WorkProviderId, string EditionProviderId) NarrationTargetKey(RequestedNarration request) => + (request.MediaType, request.WorkProviderId?.ToLowerInvariant(), request.EditionProviderId?.ToLowerInvariant()); + private static string MergeRequestedNarrations(string savedJson, IEnumerable incoming) { var saved = string.IsNullOrEmpty(savedJson) ? new List() : JsonConvert.DeserializeObject>(savedJson) ?? new List(); var merged = saved.Concat(incoming).Where(request => request != null) - .GroupBy(request => (request.MediaType, request.WorkProviderId.ToLowerInvariant(), request.EditionProviderId.ToLowerInvariant())) + .GroupBy(NarrationTargetKey) .Select(group => new RequestedNarration { MediaType = group.Key.MediaType, @@ -957,13 +962,11 @@ public bool SaveProgress(PendingAuthorImport item, PendingAuthorImport previous) (savedProgress.Item1, savedProgress.Item2, savedProgress.Item3, savedProgress.Item4)) { // Carry prepared metadata into later acknowledgements only after a request phase completed. - static (BookMediaType, string, string) TargetKey(RequestedNarration request) => - (request.MediaType, request.WorkProviderId?.ToLowerInvariant(), request.EditionProviderId?.ToLowerInvariant()); - var originals = before.ToLookup(TargetKey); - var prepared = after.ToLookup(TargetKey); + var originals = before.ToLookup(NarrationTargetKey); + var prepared = after.ToLookup(NarrationTargetKey); foreach (var request in saved) { - var key = TargetKey(request); + var key = NarrationTargetKey(request); if (!originals[key].Any(old => SameNarrationIntent(old, request))) continue; var next = prepared[key].FirstOrDefault(); if (next == null) continue; @@ -1005,9 +1008,7 @@ private static bool SameNarrationIntent(RequestedNarration left, RequestedNarrat (left.NarratorNames ?? new List()).ToHashSet(StringComparer.OrdinalIgnoreCase).SetEquals(right.NarratorNames ?? new List()); private static bool SameNarrationTarget(RequestedNarration left, RequestedNarration right) => - left.MediaType == right.MediaType && - string.Equals(left.WorkProviderId, right.WorkProviderId, StringComparison.OrdinalIgnoreCase) && - string.Equals(left.EditionProviderId, right.EditionProviderId, StringComparison.OrdinalIgnoreCase); + NarrationTargetKey(left) == NarrationTargetKey(right); public void ScheduleRetry(PendingAuthorImport item, string error) { @@ -1015,6 +1016,17 @@ public void ScheduleRetry(PendingAuthorImport item, string error) { var current = _repository.Find(item.Id); if (current == null || !current.IsActive()) return; + + // A merge or manual retry owns the new schedule. An older result cannot + // record a failure against it. A display change leaves the schedule alone. + // item is the row as this worker read it, so an untouched due time compares equal. + if (current.NextAttemptAt != item.NextAttemptAt) + { + _logger.Debug("Pending import {0} attempt result was not counted because a newer request rescheduled the row", item.Id); + CopyMutableState(current, item); + return; + } + // A concurrent merge can contain new search intent. Only narrow the unchanged // request that this worker processed; keep newer merged requests intact. if (current.Version == item.Version) @@ -1025,13 +1037,7 @@ public void ScheduleRetry(PendingAuthorImport item, string error) current.MaxAttempts = 0; current.LastAttemptAt = DateTime.UtcNow; current.LastError = error; - var backoff = AuthorRetrySchedule.NextPendingImportAttempt(current.AttemptCount); - - // A request merged in after this worker read the row may be due sooner; the backoff - // is for the request this worker processed, so it must not push the newer one back. - current.NextAttemptAt = current.Version != item.Version && current.NextAttemptAt < backoff - ? current.NextAttemptAt - : backoff; + current.NextAttemptAt = AuthorRetrySchedule.NextPendingImportAttempt(current.AttemptCount); current.OverallStatus = PendingImportStatus.Retrying; current.UpdatedAt = DateTime.UtcNow; From 027c802ff4863ae6483af15fd600193647e0ca61 Mon Sep 17 00:00:00 2001 From: robertlordhood <204023072+robertlordhood@users.noreply.github.com> Date: Sat, 5 Dec 2026 01:22:56 +0000 Subject: [PATCH 5/5] Keep a cancelled author setup cancelled Author lookups no longer go through a by-ID cache. It could return a setup that had just been cancelled for up to ten seconds. Plain author saves no longer write the setup options. Only the setup writer and a new author insert do. Cancelling or deleting a request withdraws only the formats that request owns. A scan that finishes after a cancel re-reads the author under its lock before applying any setup. A failed setup step goes onto the quick retry schedule. A metadata refusal that arrives after a cancel no longer queues the cancelled request again. Co-authored-by: elric667 <25038394+elric667@users.noreply.github.com> --- .../Author/AuthorController.cs | 9 + .../BookFiles/BookFileController.cs | 7 +- .../ManualImport/ManualImportController.cs | 13 +- .../Api/AuthorLookupBatchControllerFixture.cs | 95 +++ ...uthorLibraryServicePendingImportFixture.cs | 2 + ...raryServiceRootFolderInheritanceFixture.cs | 4 +- ...aryServiceSpecificBookMonitoringFixture.cs | 5 +- .../Books/AuthorMergeScalarIdentityFixture.cs | 16 +- ...orScannedHandlerSkippedLifecycleFixture.cs | 87 ++- .../AuthorServiceLookupHydrationFixture.cs | 26 +- .../AuthorSyncOptionsFixture.AuthorCache.cs | 110 ++++ ...rSyncOptionsFixture.CancelledAuthorEdit.cs | 68 ++ ...SyncOptionsFixture.CancelledInitialScan.cs | 598 ++++++++++++++++++ .../AuthorSyncOptionsFixture.Hydration.cs | 4 +- .../AuthorSyncOptionsFixture.ImportSync.cs | 6 +- ...AuthorSyncOptionsFixture.ReconcileRetry.cs | 19 +- ...thorSyncOptionsFixture.Round14Lifecycle.cs | 19 +- .../Books/AuthorSyncOptionsFixture.cs | 4 +- .../BookAddedServiceMonitoringFixture.cs | 2 +- .../Books/PendingAuthorImportRetryFixture.cs | 51 ++ ...AliasPendingLifecycleFixture.HeldSearch.cs | 10 +- ...ngLifecycleFixture.LifecycleCorrections.cs | 2 +- ...sPendingLifecycleFixture.PrimaryRouting.cs | 1 + ...edAliasPendingLifecycleFixture.Progress.cs | 2 +- .../PersistedAliasPendingLifecycleFixture.cs | 9 + ...cessPendingImportsCommandHandlerFixture.cs | 22 +- ...iceMergeEditionSelectionFixture.Refresh.cs | 6 +- .../Common/FixturePendingAuthorImports.cs | 13 + .../ImportListExistingAuthorRootsFixture.cs | 6 +- ...ngMediaSidePersistenceFixture.EbookPins.cs | 2 +- ...PersistenceFixture.LegacySetupMigration.cs | 2 +- ...ediaSidePersistenceFixture.PauseRetries.cs | 2 +- ...SidePersistenceFixture.SpecificBookScan.cs | 6 +- ...tListMissingMediaSidePersistenceFixture.cs | 13 +- ...ImportListSyncServiceSearchOnAddFixture.cs | 2 + ...ksAdditionalCopyFixture.ManualSelection.cs | 16 +- ...AdditionalCopyFixture.ProviderSelection.cs | 16 + ...ovedBooksAdditionalCopyFixture.SameGrab.cs | 6 +- ...RetryUnmappedMatchCommandHandlerFixture.cs | 2 + .../Parser/ParsingServiceMapFixture.cs | 13 +- .../PendingAuthorImportControllerFixture.cs | 2 + .../ProcessPendingImportsCommandHandler.cs | 2 +- .../Books/Handlers/AuthorScannedHandler.cs | 231 +++++-- .../Books/Model/AddAuthorOptions.cs | 43 +- .../Books/Model/PendingAuthorImport.cs | 3 + .../Books/Repositories/AuthorRepository.cs | 6 + .../Books/Services/AuthorLibraryService.cs | 2 + .../Books/Services/AuthorService.cs | 56 +- .../Books/Services/BookService.cs | 13 +- .../Services/PendingAuthorImportService.cs | 237 ++++--- 50 files changed, 1572 insertions(+), 319 deletions(-) create mode 100644 src/Chaptarr.Core.Test/Api/AuthorLookupBatchControllerFixture.cs create mode 100644 src/Chaptarr.Core.Test/Books/AuthorSyncOptionsFixture.AuthorCache.cs create mode 100644 src/Chaptarr.Core.Test/Books/AuthorSyncOptionsFixture.CancelledAuthorEdit.cs create mode 100644 src/Chaptarr.Core.Test/Books/AuthorSyncOptionsFixture.CancelledInitialScan.cs create mode 100644 src/Chaptarr.Core.Test/Common/FixturePendingAuthorImports.cs diff --git a/src/Chaptarr.Api.V1/Author/AuthorController.cs b/src/Chaptarr.Api.V1/Author/AuthorController.cs index f42230158..2b8a82858 100644 --- a/src/Chaptarr.Api.V1/Author/AuthorController.cs +++ b/src/Chaptarr.Api.V1/Author/AuthorController.cs @@ -642,6 +642,14 @@ public async Task> ImportAuthor([FromBody] AuthorIm var initializeEbook = createEbook && ShouldApplyInitialBookMonitoring(config.ExistingCatalogMediaTypes.Contains(BookMediaType.Ebook), config.EbookMonitorExistingMode); if (initializeAudio || initializeEbook || search) { + using var writer = BookService.EnterWantedEditionLock(author, _logger); + var savedAuthor = _authorService.GetAuthor(author.Id); + author.AddOptions = savedAuthor.AddOptions; + var previousScanScope = author.AddOptions?.GetInitialScanMediaType(); + var needsNewMediaFolder = initializeAudio && (!savedAuthor.HasMediaTypeSettings(BookMediaType.Audiobook) || + string.IsNullOrWhiteSpace(savedAuthor.AudiobookRootFolderPath)) || + initializeEbook && (!savedAuthor.HasMediaTypeSettings(BookMediaType.Ebook) || + string.IsNullOrWhiteSpace(savedAuthor.EbookRootFolderPath)); author.AddOptions ??= new AddAuthorOptions(); if (initializeAudio) author.AddOptions.AudiobookMonitor = config.AudiobookMonitorExistingMode; if (initializeEbook) author.AddOptions.EbookMonitor = config.EbookMonitorExistingMode; @@ -653,6 +661,7 @@ public async Task> ImportAuthor([FromBody] AuthorIm author.AddOptions.EbookSetupPending |= initializeEbook; author.AddOptions.AudiobookAwaitingMetadata |= initializeAudio && hydrationWarning != null; author.AddOptions.EbookAwaitingMetadata |= initializeEbook && hydrationWarning != null; + author.AddOptions.ResetRetryForNewScanScope(previousScanScope, needsNewMediaFolder); _authorService.SetAddOptions(author); } if (createAudio) diff --git a/src/Chaptarr.Api.V1/BookFiles/BookFileController.cs b/src/Chaptarr.Api.V1/BookFiles/BookFileController.cs index bb4421681..b62f38216 100644 --- a/src/Chaptarr.Api.V1/BookFiles/BookFileController.cs +++ b/src/Chaptarr.Api.V1/BookFiles/BookFileController.cs @@ -9,6 +9,7 @@ using Microsoft.AspNetCore.Mvc; using NLog; using NzbDrone.Core.Books; +using NzbDrone.Core.Datastore; using NzbDrone.Core.Datastore.Events; using NzbDrone.Core.DecisionEngine.Specifications; using NzbDrone.Core.Exceptions; @@ -250,11 +251,13 @@ public List GetBookFiles(int? authorId, [FromQuery] List if (bookIds.Any()) { + var booksById = _bookService.FindExistingBookRows(bookIds).ToDictionary(book => book.Id); + var authorsById = _authorService.GetExistingAuthors(booksById.Values.Select(book => book.AuthorId)).ToDictionary(author => author.Id); var result = new List(); foreach (var bookId in bookIds) { - var book = _bookService.GetBook(bookId); - var bookAuthor = _authorService.GetAuthor(book.AuthorId); + if (!booksById.TryGetValue(bookId, out var book)) throw new ModelNotFoundException(typeof(Book), bookId); + if (!authorsById.TryGetValue(book.AuthorId, out var bookAuthor)) throw new ModelNotFoundException(typeof(NzbDrone.Core.Books.Author), book.AuthorId); var bookFiles = _mediaFileService.GetFilesByBook(book.Id); _logger.Debug($"[BOOKFILE-API] Found {bookFiles.Count} files for bookId: {bookId} (Book: {book.Title} by {bookAuthor?.Name})"); result.AddRange(bookFiles.ConvertAll(f => f.ToResource(bookAuthor, _upgradableSpecification))); diff --git a/src/Chaptarr.Api.V1/ManualImport/ManualImportController.cs b/src/Chaptarr.Api.V1/ManualImport/ManualImportController.cs index 19e2f86e6..414ca56b3 100644 --- a/src/Chaptarr.Api.V1/ManualImport/ManualImportController.cs +++ b/src/Chaptarr.Api.V1/ManualImport/ManualImportController.cs @@ -11,6 +11,7 @@ using NzbDrone.Common; using NzbDrone.Common.Extensions; using NzbDrone.Core.Books; +using NzbDrone.Core.Datastore; using NzbDrone.Core.Books.Services; using NzbDrone.Core.DecisionEngine; using NzbDrone.Core.MediaFiles; @@ -201,11 +202,19 @@ private ManualImportResource AddQualityWeight(ManualImportResource item) private List UpdateImportItems(List resources) { + var authorIds = resources.Where(resource => resource.AuthorId.HasValue).Select(resource => resource.AuthorId.Value).Distinct().ToList(); + var authorsById = authorIds.Count > 0 ? _authorService.GetExistingAuthors(authorIds).ToDictionary(author => author.Id) : null; + var booksById = new Dictionary(); var items = new List(); foreach (var resource in resources) { - var author = resource.AuthorId.HasValue ? _authorService.GetAuthor(resource.AuthorId.Value) : null; - var book = resource.BookId.HasValue ? _bookService.GetBook(resource.BookId.Value) : null; + NzbDrone.Core.Books.Author author = null; + if (resource.AuthorId is int authorId && !authorsById.TryGetValue(authorId, out author)) + throw new ModelNotFoundException(typeof(NzbDrone.Core.Books.Author), authorId); + + Book book = null; + if (resource.BookId is int bookId && !booksById.TryGetValue(bookId, out book)) + booksById.Add(bookId, book = _bookService.GetBook(bookId)); var edition = ResolveLocalEdition(resource.EditionId, book); items.Add(new ManualImportItem diff --git a/src/Chaptarr.Core.Test/Api/AuthorLookupBatchControllerFixture.cs b/src/Chaptarr.Core.Test/Api/AuthorLookupBatchControllerFixture.cs new file mode 100644 index 000000000..d0eb7f9dc --- /dev/null +++ b/src/Chaptarr.Core.Test/Api/AuthorLookupBatchControllerFixture.cs @@ -0,0 +1,95 @@ +using System.Collections.Generic; +using System.Linq; +using Chaptarr.Api.V1.BookFiles; +using Chaptarr.Api.V1.ManualImport; +using Microsoft.AspNetCore.Mvc; +using NLog; +using NUnit.Framework; +using NzbDrone.Core.Books; +using NzbDrone.Core.Datastore; +using NzbDrone.Core.MediaFiles; +using NzbDrone.Core.MediaFiles.BookImport.Manual; +using NzbDrone.Core.Parser.Model; +using NzbDrone.Core.Qualities; +using static Chaptarr.Core.Test.Common.InterfaceProxy; + +namespace Chaptarr.Core.Test.Api +{ + public class AuthorLookupBatchControllerFixture + { + [Test] + public void book_file_query_reads_authors_in_one_batch_without_changing_input_order() + { + var authorsRead = new List(); + var authors = Proxy((method, args) => + { + Assert.That(method.Name, Is.EqualTo(nameof(IAuthorService.GetExistingAuthors))); + authorsRead.Add(((IEnumerable)args[0]).ToArray()); + return new List { new() { Id = 11 }, new() { Id = 12 } }; + }); + var books = Proxy((method, args) => + { + Assert.That(method.Name, Is.EqualTo(nameof(IBookService.FindExistingBookRows))); + Assert.That((IEnumerable)args[0], Is.EqualTo(new[] { 53, 51, 53 })); + return new List { new() { Id = 51, AuthorId = 11 }, new() { Id = 53, AuthorId = 12 } }; + }); + var files = Proxy((method, args) => + { + Assert.That(method.Name, Is.EqualTo(nameof(IMediaFileService.GetFilesByBook))); + return new List { new() { Id = (int)args[0], Quality = new QualityModel(Quality.M4B) } }; + }); + var controller = new BookFileController(null, files, null, null, authors, books, null, null, LogManager.GetCurrentClassLogger(), null); + + var result = controller.GetBookFiles(null, new List(), new List { 53, 51, 53 }, null); + + Assert.That(authorsRead.Single(), Is.EquivalentTo(new[] { 11, 12 })); + Assert.That(result.Select(file => (file.Id, file.AuthorId)), Is.EqualTo(new[] { (53, 12), (51, 11), (53, 12) })); + } + + [TestCase(false)] + [TestCase(true)] + public void manual_preview_resolves_authors_once_and_checks_missing_ids(bool missing) + { + var bookReads = new List(); + var authorReads = new List(); + var authors = Proxy((method, args) => + { + Assert.That(method.Name, Is.EqualTo(nameof(IAuthorService.GetExistingAuthors))); + authorReads.Add(((IEnumerable)args[0]).ToArray()); + return missing ? new List() : new List { new() { Id = 11 } }; + }); + var books = Proxy((method, args) => + { + Assert.That(method.Name, Is.EqualTo(nameof(IBookService.GetBook))); + bookReads.Add((int)args[0]); + return new Book { Id = (int)args[0], AuthorId = 11 }; + }); + var manual = Proxy((method, args) => + { + Assert.That(method.Name, Is.EqualTo(nameof(IManualImportService.UpdateItems))); + var items = (List)args[0]; + Assert.That(items.Select(item => (item.Author?.Id, item.Book?.Id)), Is.EqualTo(new (int?, int?)[] { (11, 51), (11, 51), (null, null) })); + return new List(); + }); + var controller = new ManualImportController(manual, authors, null, books, null, null, LogManager.GetCurrentClassLogger()); + var resources = new List + { + new() { AuthorId = 11, BookId = 51, Path = "/files/one.m4b" }, + new() { AuthorId = 11, BookId = 51, Path = "/files/two.m4b" }, + new() { Path = "/files/unmatched.m4b" } + }; + + if (missing) + { + Assert.That(() => controller.UpdateItems(resources), Throws.TypeOf().With.Message.Contains("Author with ID 11")); + Assert.That(bookReads, Is.Empty); + } + else + { + Assert.That(controller.UpdateItems(resources), Is.TypeOf()); + Assert.That(bookReads, Is.EqualTo(new[] { 51 })); + } + Assert.That(authorReads.Single(), Is.EqualTo(new[] { 11 })); + } + } +} diff --git a/src/Chaptarr.Core.Test/Books/AuthorLibraryServicePendingImportFixture.cs b/src/Chaptarr.Core.Test/Books/AuthorLibraryServicePendingImportFixture.cs index 41be63529..eb8ff3967 100644 --- a/src/Chaptarr.Core.Test/Books/AuthorLibraryServicePendingImportFixture.cs +++ b/src/Chaptarr.Core.Test/Books/AuthorLibraryServicePendingImportFixture.cs @@ -132,6 +132,8 @@ public Task EnqueueAsync(string providerId, MonitoringConfig config, string public bool UpdateStatus(PendingAuthorImport item, PendingImportStatus status, string error, long? expectedVersion = null) => throw new NotImplementedException(); public bool SaveProgress(PendingAuthorImport item, PendingAuthorImport previous) => throw new NotImplementedException(); public void ScheduleRetry(PendingAuthorImport item, string error) => throw new NotImplementedException(); + public void ReconcileSetupCancellation(Author author) => throw new NotSupportedException(); + public void Cancel(int id) => throw new NotImplementedException(); public bool CancelIfQueued(int id) => throw new NotImplementedException(); public void RetryNow(int id) => throw new NotImplementedException(); diff --git a/src/Chaptarr.Core.Test/Books/AuthorLibraryServiceRootFolderInheritanceFixture.cs b/src/Chaptarr.Core.Test/Books/AuthorLibraryServiceRootFolderInheritanceFixture.cs index d8b7f37cd..6e1f53589 100644 --- a/src/Chaptarr.Core.Test/Books/AuthorLibraryServiceRootFolderInheritanceFixture.cs +++ b/src/Chaptarr.Core.Test/Books/AuthorLibraryServiceRootFolderInheritanceFixture.cs @@ -88,6 +88,8 @@ public Task EnqueueAsync(string providerId, MonitoringConfig config, string public bool SaveProgress(PendingAuthorImport item, PendingAuthorImport previous) => throw new NotImplementedException(); public void ScheduleRetry(PendingAuthorImport item, string error) => throw new NotImplementedException(); public bool IsActiveRequest(int id, long version) => true; + public void ReconcileSetupCancellation(Author author) => throw new NotSupportedException(); + public void Cancel(int id) => throw new NotImplementedException(); public bool CancelIfQueued(int id) => throw new NotImplementedException(); public void RetryNow(int id) => throw new NotImplementedException(); @@ -900,7 +902,7 @@ int Import(JsonObject payload) Assert.That(commands.OfType(), Is.Empty); }); var scan = new AuthorScannedHandler(new BookMonitoredService(authors, books, logger), authors, queue, - Proxy((_, _) => null), events, logger, books); + Proxy((_, _) => null), events, logger, books, pending); scan.Handle(new NzbDrone.Core.MediaFiles.Events.AuthorScannedEvent(author)); scan.Handle(new NzbDrone.Core.MediaFiles.Events.AuthorScannedEvent(author)); Assert.That(commands.OfType().Count(), Is.EqualTo(search ? 1 : 0)); diff --git a/src/Chaptarr.Core.Test/Books/AuthorLibraryServiceSpecificBookMonitoringFixture.cs b/src/Chaptarr.Core.Test/Books/AuthorLibraryServiceSpecificBookMonitoringFixture.cs index 23936c1f9..97bd2a62b 100644 --- a/src/Chaptarr.Core.Test/Books/AuthorLibraryServiceSpecificBookMonitoringFixture.cs +++ b/src/Chaptarr.Core.Test/Books/AuthorLibraryServiceSpecificBookMonitoringFixture.cs @@ -98,7 +98,8 @@ public Author UpdateAuthorProgressiveSettings( } public Author GetAuthor(int authorId) => ExistingAuthor?.Id == authorId ? ExistingAuthor : null; - public List GetExistingAuthors(IEnumerable authorIds) => throw new NotImplementedException(); + public List GetExistingAuthors(IEnumerable authorIds) => ExistingAuthor != null && authorIds.Contains(ExistingAuthor.Id) + ? new List { ExistingAuthor } : new List(); public List GetAuthors(IEnumerable authorIds) => throw new NotImplementedException(); public List AddAuthors(List newAuthors, bool doRefresh) => throw new NotImplementedException(); public Author FindByName(string title) => null; @@ -350,7 +351,7 @@ private static void CompleteInitialScan(Author author, StubAuthorService authors new CommandModel { Body = (Command)args[0] }); var added = Chaptarr.Core.Test.Common.InterfaceProxy.Proxy((_, _) => null); new AuthorScannedHandler(new BookMonitoredService(authors, books, logger), authors, queue, added, - new StubEventAggregator(), logger, books).Handle(new AuthorScannedEvent(author)); + new StubEventAggregator(), logger, books, global::Chaptarr.Core.Test.Common.FixturePendingAuthorImports.Empty()).Handle(new AuthorScannedEvent(author)); } [Test] diff --git a/src/Chaptarr.Core.Test/Books/AuthorMergeScalarIdentityFixture.cs b/src/Chaptarr.Core.Test/Books/AuthorMergeScalarIdentityFixture.cs index 3f483bb43..fe8c2dbbd 100644 --- a/src/Chaptarr.Core.Test/Books/AuthorMergeScalarIdentityFixture.cs +++ b/src/Chaptarr.Core.Test/Books/AuthorMergeScalarIdentityFixture.cs @@ -51,10 +51,8 @@ private sealed class Harness : IDisposable public readonly List TransactionalAuthorWrites = new(); public int TransactionalBookInserts; public int TransactionalHistoryInserts; - public bool ProbeSourceCache; public bool ProbeAllAuthorCache; public readonly List AllAuthorCacheObservations = new(); - public readonly List SourceCacheObservations = new(); public readonly List<(bool SourceExists, string Scalar, int[] Owners, string[] Aliases, Author OldAuthor)> Observations = new(); private readonly RefreshAuthorService _refresh; public Func Fetch = id => RefreshResult.Error("fixture has no published response"); @@ -89,11 +87,6 @@ public Harness(IMainDatabase database, string provider = "az", bool globalFirst DependentTables.Select(table => connection.Query($"SELECT DISTINCT \"AuthorId\" FROM \"{table}\"").Single()).ToArray(), Aliases.GetAliases("Author", Survivor.Id, "author").Select(alias => $"{alias.Provider}:{alias.NormalizedProviderId}").OrderBy(id => id).ToArray(), edited.OldAuthor)); - if (ProbeSourceCache) - { - try { SourceCacheObservations.Add(Service.GetAuthor(Source.Id)); } - catch (ModelNotFoundException) { SourceCacheObservations.Add(null); } - } if (ProbeAllAuthorCache) AllAuthorCacheObservations.Add(Service.GetAllAuthors().Select(author => author.Id).ToArray()); pending.Handle(edited); } @@ -453,7 +446,7 @@ public void survivor_before_image_is_fresh_on_success_and_failure([Values(false, } [Test] - public void deleted_source_cache_is_invalidated_only_after_commit( + public void source_author_disappears_only_after_merge_commits( [Values(false, true)] bool postgres, [Values(false, true)] bool failure) { DualDatabaseFixture.Run(postgres, database => @@ -461,7 +454,6 @@ public void deleted_source_cache_is_invalidated_only_after_commit( using var h = new Harness(database); var source = h.Service.GetAuthor(h.Source.Id); Assert.That(source.Id, Is.EqualTo(h.Source.Id)); - h.ProbeSourceCache = true; if (failure) h.Abort(postgres, "alias-save"); var before = h.Snapshot(); var blocked = h.Merge(); @@ -469,13 +461,13 @@ public void deleted_source_cache_is_invalidated_only_after_commit( { Assert.That(blocked, Is.EquivalentTo(new[] { h.Source.HardcoverAuthorId, h.Canonical })); h.AssertAbort(before, "alias-save"); - Assert.That(h.Service.GetAuthor(h.Source.Id), Is.SameAs(source)); - Assert.That(h.SourceCacheObservations, Is.Empty); + Assert.That(h.Service.GetAuthor(h.Source.Id).Id, Is.EqualTo(source.Id)); + Assert.That(h.Observations, Is.Empty); } else { Assert.That(blocked, Is.Empty, h.LogDump); - Assert.That(h.SourceCacheObservations, Is.EqualTo(new Author[] { null })); + Assert.That(h.Observations.Single().SourceExists, Is.False); Assert.Throws(() => h.Service.GetAuthor(h.Source.Id)); Assert.Throws(() => h.Service.GetAuthor(h.Source.Id)); } diff --git a/src/Chaptarr.Core.Test/Books/AuthorScannedHandlerSkippedLifecycleFixture.cs b/src/Chaptarr.Core.Test/Books/AuthorScannedHandlerSkippedLifecycleFixture.cs index cdb8ad724..3511d4e1d 100644 --- a/src/Chaptarr.Core.Test/Books/AuthorScannedHandlerSkippedLifecycleFixture.cs +++ b/src/Chaptarr.Core.Test/Books/AuthorScannedHandlerSkippedLifecycleFixture.cs @@ -3,6 +3,7 @@ using System.Linq; using System.Reflection; using System.Threading; +using Chaptarr.Core.Test.Common; using NLog; using NUnit.Framework; using NzbDrone.Common.Messaging; @@ -28,10 +29,10 @@ public void rejected_initial_search_admission_retains_the_durable_request_until_ var events = new StubEventAggregator(); var subject = new AuthorScannedHandler( DispatchProxy.Create(), - DispatchProxy.Create(), queue, + AuthorServiceFor(author), queue, DispatchProxy.Create(), events, LogManager.GetCurrentClassLogger(), - Chaptarr.Core.Test.Common.InterfaceProxy.Proxy((_, _) => null)); + InterfaceProxy.Proxy((_, _) => null), FixturePendingAuthorImports.Empty()); subject.Handle(new AuthorScannedEvent(author)); Assert.That(author.AddOptions, Is.SameAs(options)); @@ -66,10 +67,10 @@ public void initial_search_keeps_its_saved_media_scope(bool audio, bool ebook, b var queue = new StubCommandQueueManager(); var subject = new AuthorScannedHandler( DispatchProxy.Create(), - DispatchProxy.Create(), queue, + AuthorServiceFor(author), queue, DispatchProxy.Create(), new StubEventAggregator(), LogManager.GetCurrentClassLogger(), - Chaptarr.Core.Test.Common.InterfaceProxy.Proxy((_, _) => null)); + InterfaceProxy.Proxy((_, _) => null), FixturePendingAuthorImports.Empty()); subject.Handle(new AuthorScannedEvent(author)); Assert.That(queue.Pushed.OfType().Single().MediaType, Is.EqualTo(expected)); Assert.That(author.AddOptions, Is.Null); @@ -84,7 +85,7 @@ public void no_folder_evidence_skip_runs_the_normal_author_scan_completion_lifec if (mode.HasValue) options.Monitor = mode; var author = new Author { Id = 7, Name = "New Author", AddOptions = options }; var monitoredService = DispatchProxy.Create(); - var authorService = DispatchProxy.Create(); + var authorService = AuthorServiceFor(author); var bookAddedService = DispatchProxy.Create(); var queue = new StubCommandQueueManager(); var events = new StubEventAggregator(); @@ -94,7 +95,7 @@ public void no_folder_evidence_skip_runs_the_normal_author_scan_completion_lifec queue, bookAddedService, events, - LogManager.GetLogger(nameof(AuthorScannedHandlerSkippedLifecycleFixture)), Chaptarr.Core.Test.Common.InterfaceProxy.Proxy((method, args) => { queue.Pushed.Add(new BulkSyncFormatMonitoringCommand((List)args[0])); return null; })); + LogManager.GetLogger(nameof(AuthorScannedHandlerSkippedLifecycleFixture)), InterfaceProxy.Proxy((method, args) => { queue.Pushed.Add(new BulkSyncFormatMonitoringCommand((List)args[0])); return null; }), FixturePendingAuthorImports.Empty()); subject.Handle(new AuthorScanSkippedEvent(author, AuthorScanSkippedReason.NoFolderEvidence)); @@ -130,14 +131,14 @@ public void media_specific_initial_modes_should_be_applied_once_after_the_scan_w } }; var monitoredService = DispatchProxy.Create(); - var authorService = DispatchProxy.Create(); + var authorService = AuthorServiceFor(author); var subject = new AuthorScannedHandler( monitoredService, authorService, new StubCommandQueueManager(), DispatchProxy.Create(), new StubEventAggregator(), - LogManager.GetLogger(nameof(AuthorScannedHandlerSkippedLifecycleFixture)), Chaptarr.Core.Test.Common.InterfaceProxy.Proxy((_, _) => throw new NotSupportedException())); + LogManager.GetLogger(nameof(AuthorScannedHandlerSkippedLifecycleFixture)), InterfaceProxy.Proxy((_, _) => throw new NotSupportedException()), FixturePendingAuthorImports.Empty()); subject.Handle(new AuthorScannedEvent(author)); @@ -173,17 +174,17 @@ public void initial_scan_should_reconcile_format_sync_after_media_defaults() var monitoredService = DispatchProxy.Create(); var subject = new AuthorScannedHandler( monitoredService, - DispatchProxy.Create(), + AuthorServiceFor(author), queue, DispatchProxy.Create(), new StubEventAggregator(), - LogManager.GetLogger(nameof(AuthorScannedHandlerSkippedLifecycleFixture)), Chaptarr.Core.Test.Common.InterfaceProxy.Proxy((method, args) => + LogManager.GetLogger(nameof(AuthorScannedHandlerSkippedLifecycleFixture)), InterfaceProxy.Proxy((method, args) => { Assert.That(method.Name, Is.EqualTo(nameof(IBookService.SyncMonitoredAcrossFormats))); Assert.That(((BookMonitoredServiceProxy)(object)monitoredService).Calls, Has.Count.EqualTo(2)); queue.Pushed.Add(new BulkSyncFormatMonitoringCommand((List)args[0])); return null; - })); + }), FixturePendingAuthorImports.Empty()); subject.Handle(new AuthorScannedEvent(author)); @@ -207,17 +208,17 @@ public void importing_ebook_side_with_none_should_leave_audiobook_side_untouched var queue = new StubCommandQueueManager(); var subject = new AuthorScannedHandler( monitoredService, - DispatchProxy.Create(), + AuthorServiceFor(author), queue, DispatchProxy.Create(), new StubEventAggregator(), - LogManager.GetLogger(nameof(AuthorScannedHandlerSkippedLifecycleFixture)), Chaptarr.Core.Test.Common.InterfaceProxy.Proxy((method, args) => + LogManager.GetLogger(nameof(AuthorScannedHandlerSkippedLifecycleFixture)), InterfaceProxy.Proxy((method, args) => { Assert.That(method.Name, Is.EqualTo(nameof(IBookService.SyncMonitoredAcrossFormats))); Assert.That(((BookMonitoredServiceProxy)(object)monitoredService).Calls, Has.Count.EqualTo(1)); queue.Pushed.Add(new BulkSyncFormatMonitoringCommand((List)args[0])); return null; - })); + }), FixturePendingAuthorImports.Empty()); subject.Handle(new AuthorScannedEvent(author)); @@ -240,15 +241,17 @@ public void one_failed_setup_backs_off_without_blocking_other_authors(string fai { var authors = new List { - new() { Id = 1, Name = "First", AddOptions = new AddAuthorOptions { Monitor = MonitorTypes.All, SearchForMissingBooks = true } }, - new() { Id = 2, Name = "Second", AddOptions = new AddAuthorOptions { Monitor = MonitorTypes.All, SearchForMissingBooks = true } } + new() { Id = 1, Name = "First", AddOptions = new AddAuthorOptions { Monitor = MonitorTypes.All, SearchForMissingBooks = true, InitialFormatSyncNotBefore = DateTime.UtcNow.AddSeconds(-1) } }, + new() { Id = 2, Name = "Second", AddOptions = new AddAuthorOptions { Monitor = MonitorTypes.All, SearchForMissingBooks = true, InitialFormatSyncNotBefore = DateTime.UtcNow.AddSeconds(-1) } } }; var saved = new Dictionary(); var monitoring = new List(); var fail = true; - var service = Chaptarr.Core.Test.Common.InterfaceProxy.Proxy((method, args) => + var service = InterfaceProxy.Proxy((method, args) => { if (method.Name == nameof(IAuthorService.GetAuthors)) return authors; + if (method.Name == nameof(IAuthorService.GetExistingAuthors)) + return authors.Where(author => ((IEnumerable)args[0]).Contains(author.Id)).ToList(); Assert.That(method.Name, Is.EqualTo(nameof(IAuthorService.SetAddOptions))); var author = (Author)args[0]; if (fail && failingStep == "clear" && author.Id == 1 && author.AddOptions == null) @@ -262,7 +265,7 @@ public void one_failed_setup_backs_off_without_blocking_other_authors(string fai throw new InvalidOperationException("Search queue unavailable"); } }; var subject = new AuthorScannedHandler( - Chaptarr.Core.Test.Common.InterfaceProxy.Proxy((_, args) => + InterfaceProxy.Proxy((_, args) => { var author = (Author)args[0]; monitoring.Add(author.Id); @@ -270,7 +273,7 @@ public void one_failed_setup_backs_off_without_blocking_other_authors(string fai return null; }), service, queue, DispatchProxy.Create(), new StubEventAggregator(), LogManager.GetCurrentClassLogger(), - Chaptarr.Core.Test.Common.InterfaceProxy.Proxy((_, _) => null)); + InterfaceProxy.Proxy((_, _) => null), FixturePendingAuthorImports.Empty()); var command = new BulkSyncFormatMonitoringCommand(new List { 1, 2 }) { InitialSetupAttempt = 1 }; subject.Execute(command); Assert.That(authors[1].AddOptions, Is.Null); @@ -290,6 +293,39 @@ public void one_failed_setup_backs_off_without_blocking_other_authors(string fai if (failingStep != "monitor") Assert.That(monitoring.Count(id => id == 1), Is.EqualTo(1)); } + [Test] + public void scan_notifies_after_a_reload_or_recent_search_failure([Values(1, 2)] int failedReads) + { + var author = new Author + { + Id = 12, + AddOptions = new AddAuthorOptions { AwaitingMetadata = true } + }; + var reads = 0; + var searches = 0; + var service = InterfaceProxy.Proxy((method, _) => + { + Assert.That(method.Name, Is.EqualTo(nameof(IAuthorService.GetExistingAuthors))); + if (++reads <= failedReads) throw new InvalidOperationException("Author read unavailable"); + return new List { author }; + }); + var events = new StubEventAggregator(); + var subject = new AuthorScannedHandler(null, service, new StubCommandQueueManager(), + InterfaceProxy.Proxy((_, _) => + { + searches++; + throw new InvalidOperationException("Recent catalog unavailable"); + }), events, LogManager.GetCurrentClassLogger(), InterfaceProxy.Proxy((_, _) => null), + FixturePendingAuthorImports.Empty()); + + subject.Handle(new AuthorScannedEvent(author)); + + Assert.That(reads, Is.EqualTo(2)); + Assert.That(searches, Is.EqualTo(failedReads == 1 ? 1 : 0)); + Assert.That(events.PublishedEvents.OfType().Single().Author.Id, Is.EqualTo(author.Id)); + Assert.That(author.AddOptions.InitialFormatSyncNotBefore, Is.Null); + } + public class BookMonitoredServiceProxy : DispatchProxy { public Author Author { get; private set; } @@ -310,12 +346,25 @@ protected override object Invoke(MethodInfo targetMethod, object[] args) } } + private static IAuthorService AuthorServiceFor(Author author) + { + var service = DispatchProxy.Create(); + ((AuthorServiceProxy)(object)service).SavedAuthor = author; + return service; + } + public class AuthorServiceProxy : DispatchProxy { + public Author SavedAuthor { get; set; } public Author RemovedAddOptionsFor { get; private set; } protected override object Invoke(MethodInfo targetMethod, object[] args) { + if (targetMethod?.Name == nameof(IAuthorService.GetExistingAuthors)) + { + var ids = (IEnumerable)args[0]; + return ids.Contains(SavedAuthor.Id) ? new List { SavedAuthor } : new List(); + } if (targetMethod?.Name == nameof(IAuthorService.SetAddOptions)) { RemovedAddOptionsFor = (Author)args[0]; diff --git a/src/Chaptarr.Core.Test/Books/AuthorServiceLookupHydrationFixture.cs b/src/Chaptarr.Core.Test/Books/AuthorServiceLookupHydrationFixture.cs index d5a8dc8d0..b97cc8f49 100644 --- a/src/Chaptarr.Core.Test/Books/AuthorServiceLookupHydrationFixture.cs +++ b/src/Chaptarr.Core.Test/Books/AuthorServiceLookupHydrationFixture.cs @@ -47,6 +47,7 @@ private sealed class StubAuthorRepository : IAuthorRepository private readonly Author _lookupAuthor; private Author _byIdAuthor; public int GetCallCount { get; private set; } + public int FindCallCount { get; private set; } public int AllCallCount { get; private set; } public List Authors { get; set; } public Action BeforeWrite { get; set; } @@ -72,10 +73,15 @@ public Author FindByName(string cleanName) => Authors public Author Get(int id) { GetCallCount++; - return Authors.Any(author => author.Id == id) - ? (id == _byIdAuthor?.Id ? _byIdAuthor : Authors.Single(author => author.Id == id)) - : null; + return FindRow(id); } + public Author Find(int id) + { + FindCallCount++; + return FindRow(id); + } + private Author FindRow(int id) => Authors.Any(author => author.Id == id) + ? (id == _byIdAuthor?.Id ? _byIdAuthor : Authors.Single(author => author.Id == id)) : null; public IEnumerable All() { AllCallCount++; @@ -86,7 +92,6 @@ public IEnumerable All() public IEnumerable Get(IEnumerable ids) => Authors.Where(author => ids.Contains(author.Id)).ToList(); public int Count() => throw new NotImplementedException(); - public Author Find(int id) => throw new NotImplementedException(); public Author Insert(Author model) { BeforeWrite?.Invoke(); @@ -897,7 +902,7 @@ public void find_by_provider_id_should_return_author_with_quality_profiles_loade } [Test] - public void find_by_name_should_prefer_cached_author_instance_when_available() + public void find_by_name_should_load_the_current_row_after_resolving_the_name() { var lookup = new Author { @@ -907,7 +912,7 @@ public void find_by_name_should_prefer_cached_author_instance_when_available() AudiobookQualityProfile = new LazyLoaded(new QualityProfile { Id = 2, Name = "Audio" }) }; - var cached = new Author + var persisted = new Author { Id = 1189, Name = "Pascale Lacelle", @@ -915,15 +920,16 @@ public void find_by_name_should_prefer_cached_author_instance_when_available() AudiobookQualityProfile = new LazyLoaded(new QualityProfile { Id = 2, Name = "Audio" }) }; - var repository = new StubAuthorRepository(lookup, cached); + var repository = new StubAuthorRepository(lookup, persisted); var subject = CreateSubject(repository); - Assert.That(subject.GetAuthor(1189), Is.SameAs(cached)); + Assert.That(subject.GetCandidates(lookup.Name), Is.EqualTo(new[] { lookup })); var result = subject.FindByName("Pascale Lacelle"); - Assert.That(result, Is.SameAs(cached)); - Assert.That(repository.GetCallCount, Is.EqualTo(1)); + Assert.That(result, Is.SameAs(persisted)); + Assert.That(repository.FindCallCount, Is.EqualTo(1)); + Assert.That(repository.GetCallCount, Is.Zero); } } } diff --git a/src/Chaptarr.Core.Test/Books/AuthorSyncOptionsFixture.AuthorCache.cs b/src/Chaptarr.Core.Test/Books/AuthorSyncOptionsFixture.AuthorCache.cs new file mode 100644 index 000000000..43a3e704a --- /dev/null +++ b/src/Chaptarr.Core.Test/Books/AuthorSyncOptionsFixture.AuthorCache.cs @@ -0,0 +1,110 @@ +using System; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Chaptarr.Core.Test.Common; +using NUnit.Framework; +using NzbDrone.Core.Books; +using NzbDrone.Core.Books.Events; +using NzbDrone.Core.Exceptions; +using NzbDrone.Core.MetadataSource; +using NzbDrone.Core.MetadataSource.BookInfo; +using static Chaptarr.Core.Test.Common.InterfaceProxy; + +namespace Chaptarr.Core.Test.Books +{ + public partial class AuthorSyncOptionsFixture + { + [Test] + public void author_reads_after_cancellation_cannot_reuse_a_read_started_before_it([Values] bool postgres) + { + DualDatabaseFixture.Run(postgres, database => + { + const string providerId = "hc:123456"; + var h = new Harness(database); + h.Import(h.Request("audiobook", false)); + h.Scan(); + h.MetadataError = new BookInfoException("Initial metadata outage"); + var request = h.Request("ebook", false); + request.SearchForMissingBooks = true; + h.Import(request); + h.Pending.Handle(new AuthorSetupMetadataRefusedEvent(h.Author, providerId, + new AuthorTerminalException("author_no_primary_works", providerId, null, "Declared author stop", true))); + var pending = h.Pending.GetByProviderId(providerId); + h.Pending.RetryNow(pending.Id); + var original = h.AuthorRows.FindByHardcoverId(providerId); + Assert.That(original.AddOptions?.EbookSetupPendingImportId, Is.EqualTo(pending.Id)); + h.Authors.SetAddOptions(original); + + using var rowRead = new ManualResetEventSlim(); + using var allowReturn = new ManualResetEventSlim(); + var captureFirstRead = 1; + Set(h.Authors, "_authorRepository", Proxy((method, args) => + { + var result = method.Invoke(h.AuthorRows, args); + if (method.Name == nameof(IAuthorRepository.Get) && args[0] is int && + Interlocked.Exchange(ref captureFirstRead, 0) == 1) + { + rowRead.Set(); + Assert.That(allowReturn.Wait(TimeSpan.FromSeconds(10)), Is.True, "The test did not release the old read."); + } + return result; + })); + + var inFlight = Task.Run(() => h.Authors.GetAuthor(original.Id)); + try + { + Assert.That(rowRead.Wait(TimeSpan.FromSeconds(10)), Is.True, "The old read did not reach the repository."); + h.Pending.Cancel(pending.Id); + Assert.That(h.AuthorRows.Get(original.Id).AddOptions, Is.Null, "Cancellation must be durable before releasing the old read."); + } + finally + { + allowReturn.Set(); + } + + Assert.That(inFlight.GetAwaiter().GetResult().AddOptions, Is.Not.Null, "The read captured its snapshot before cancellation."); + Assert.Multiple(() => + { + Assert.That(h.Authors.GetAuthor(original.Id).AddOptions, Is.Null); + Assert.That(h.Authors.FindByProviderId("hc", "123456").AddOptions, Is.Null); + Assert.That(h.Authors.FindByName(original.Name).AddOptions, Is.Null); + }); + }); + } + + [Test] + public void a_book_read_reuses_its_joined_author_and_still_loads_an_author_without_editions([Values] bool postgres) + { + DualDatabaseFixture.Run(postgres, database => + { + var h = new Harness(database); + h.Import(h.Request("audiobook", false)); + var author = h.Author; + var withEdition = h.BookRows.GetBooks(author.Id).Single(); + var withoutEdition = h.BookRows.Insert(new Book + { + AuthorId = author.Id, Title = "Awaiting editions", CleanTitle = "awaitingeditions", + TitleSlug = "awaiting-editions", MediaType = BookMediaType.Audiobook, Added = DateTime.UtcNow + }); + var singleReads = 0; + Set(h.Authors, "_authorRepository", Proxy((method, args) => + { + if (method.Name == nameof(IAuthorRepository.Get) && args[0] is int) singleReads++; + return method.Invoke(h.AuthorRows, args); + })); + + var joined = h.Books.GetBook(withEdition.Id); + Assert.Multiple(() => + { + Assert.That(joined.Author.Id, Is.EqualTo(author.Id)); + Assert.That(joined.Author.AudiobookQualityProfileId, Is.EqualTo(author.AudiobookQualityProfileId)); + Assert.That(joined.Editions, Has.Count.EqualTo(1)); + Assert.That(singleReads, Is.Zero); + }); + Assert.That(h.Books.GetBook(withoutEdition.Id).Author.Id, Is.EqualTo(author.Id)); + Assert.That(singleReads, Is.EqualTo(1)); + }); + } + } +} diff --git a/src/Chaptarr.Core.Test/Books/AuthorSyncOptionsFixture.CancelledAuthorEdit.cs b/src/Chaptarr.Core.Test/Books/AuthorSyncOptionsFixture.CancelledAuthorEdit.cs new file mode 100644 index 000000000..54140c21f --- /dev/null +++ b/src/Chaptarr.Core.Test/Books/AuthorSyncOptionsFixture.CancelledAuthorEdit.cs @@ -0,0 +1,68 @@ +using System.Collections.Generic; +using System.Threading.Tasks; +using Chaptarr.Api.V1.PendingImport; +using Chaptarr.Core.Test.Common; +using Microsoft.AspNetCore.Mvc; +using NUnit.Framework; +using NzbDrone.Core.Books; +using static Chaptarr.Core.Test.Common.InterfaceProxy; + +namespace Chaptarr.Core.Test.Books +{ + public partial class AuthorSyncOptionsFixture + { + [Test] + public void an_author_edit_cannot_store_cancelled_setup_from_its_earlier_read([Values] bool postgres, [Values] bool bulk) + { + DualDatabaseFixture.Run(postgres, database => + { + var h = new Harness(database) { Available = false }; + var request = h.Request("audiobook", false); + request.SearchForMissingBooks = true; + h.Import(request); + var pending = h.Pending.GetByProviderId("hc:123456"); + var queueRows = new PendingAuthorImportRepository(database, h.Events); + var cancel = new PendingAuthorImportController(null, h.Pending, h.Authors, null, null, h.Roots, null, h.Logger); + var intercepted = false; + int authorId = 0; + + Set(h.Pending, "_repository", Proxy((method, args) => + { + if (method.Name == nameof(IPendingAuthorImportRepository.TryDelete) && !intercepted) + { + var edited = h.AuthorRows.FindByHardcoverId(pending.ProviderId); + authorId = edited.Id; + Assert.That(edited.AddOptions?.SearchForMissingBooks, Is.True); + Assert.That(edited.AddOptions.AudiobookSetupPendingImportId, Is.EqualTo(pending.Id)); + edited.Overview = "Reviewed description"; + Set(h.Authors, "_authorRepository", Proxy((write, arguments) => + { + if (!intercepted && write.Name == (bulk ? nameof(IAuthorRepository.UpdateMany) : nameof(IAuthorRepository.Update))) + { + intercepted = true; + var result = Task.Run(() => cancel.Cancel(pending.Id)).GetAwaiter().GetResult(); + Assert.That(result.Result, Is.TypeOf()); + Assert.That(h.AuthorRows.Get(authorId).AddOptions, Is.Null); + } + return write.Invoke(h.AuthorRows, arguments); + })); + if (bulk) h.Authors.UpdateAuthors(new List { edited }, true); + else h.Authors.UpdateAuthor(edited); + } + return method.Invoke(queueRows, args); + })); + + h.Available = true; + h.ProcessPending(); + + Assert.That(intercepted, Is.True, "The cancel must commit between the edit's read and write."); + var saved = h.AuthorRows.Get(authorId); + Assert.That(saved.Overview, Is.EqualTo("Reviewed description")); + Assert.That(saved.AddOptions, Is.Null); + saved.AddOptions = new AddAuthorOptions { SearchForMissingBooks = true }; + h.Authors.SetAddOptions(saved); + Assert.That(h.AuthorRows.Get(authorId).AddOptions?.SearchForMissingBooks, Is.True, "Explicit setup saves still work."); + }); + } + } +} diff --git a/src/Chaptarr.Core.Test/Books/AuthorSyncOptionsFixture.CancelledInitialScan.cs b/src/Chaptarr.Core.Test/Books/AuthorSyncOptionsFixture.CancelledInitialScan.cs new file mode 100644 index 000000000..3be3b9ccd --- /dev/null +++ b/src/Chaptarr.Core.Test/Books/AuthorSyncOptionsFixture.CancelledInitialScan.cs @@ -0,0 +1,598 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Chaptarr.Api.V1.PendingImport; +using Chaptarr.Core.Test.Common; +using Microsoft.AspNetCore.Mvc; +using NUnit.Framework; +using NzbDrone.Common.Disk; +using NzbDrone.Core.Books; +using NzbDrone.Core.Books.Commands; +using NzbDrone.Core.Books.Events; +using NzbDrone.Core.Books.Services; +using NzbDrone.Core.Configuration; +using NzbDrone.Core.Datastore; +using NzbDrone.Core.IndexerSearch; +using NzbDrone.Core.MediaFiles; +using NzbDrone.Core.MediaFiles.Commands; +using NzbDrone.Core.MediaFiles.Events; +using NzbDrone.Core.Messaging.Commands; +using NzbDrone.Core.RootFolders; +using static Chaptarr.Core.Test.Common.InterfaceProxy; + +namespace Chaptarr.Core.Test.Books +{ + public partial class AuthorSyncOptionsFixture + { + [Test] + public void pending_initial_scan_cannot_apply_setup_after_cancel_commits([Values] bool postgres, + [Values("folder", "skipped", "retry")] string route) + { + DualDatabaseFixture.Run(postgres, database => + { + var h = new Harness(database) { Available = false }; + var request = h.Request("audiobook", false); + request.SearchForMissingBooks = true; + h.Import(request); + var pending = h.Pending.GetByProviderId("hc:123456"); + var queueRows = new PendingAuthorImportRepository(database, h.Events); + var cancel = new PendingAuthorImportController(null, h.Pending, h.Authors, null, null, h.Roots, null, h.Logger); + var cancelled = false; + int authorId = 0; + + void CancelAfterRead(Author snapshot) + { + Assert.That(snapshot.AddOptions?.AwaitingMetadata, Is.False); + Assert.That(snapshot.AddOptions?.SearchForMissingBooks, Is.True); + Assert.That(snapshot.AddOptions?.AudiobookSetupPendingImportId, Is.EqualTo(pending.Id)); + Assert.That(queueRows.Get(pending.Id).IsActive(), Is.True); + authorId = snapshot.Id; + var result = Task.Run(() => cancel.Cancel(pending.Id)).GetAwaiter().GetResult(); + Assert.That(result.Result, Is.TypeOf()); + Assert.That(h.AuthorRows.Get(authorId).AddOptions, Is.Null); + Assert.That(h.SearchTargets, Is.Empty); + cancelled = true; + } + + var scanAuthorReads = Proxy((method, args) => + { + var result = method.Invoke(h.Authors, args); + if (!cancelled && method.Name is nameof(IAuthorService.GetAuthors) or nameof(IAuthorService.GetExistingAuthors)) + CancelAfterRead(((List)result).Single()); + return result; + }); + var recentBooks = new BookAddedService(new NzbDrone.Common.Cache.CacheManager(), h.Queue, h.Books, h.Logger); + var handler = new AuthorScannedHandler(new BookMonitoredService(h.Authors, h.Books, h.Logger), scanAuthorReads, + h.Queue, recentBooks, h.Events, h.Logger, h.Books, h.Pending); + var events = (InterfaceProxy)(object)h.Events; + var publish = events.Handler; + events.Handler = (method, args) => + { + if (args[0] is AuthorScannedEvent scanned) + { + handler.Handle(scanned); + return null; + } + return publish(method, args); + }; + var disk = Proxy((method, args) => method.Name == nameof(IDiskProvider.FolderExists) + ? (string)args[0] == h.AudioRoot.Path : throw new NotSupportedException(method.Name)); + var scanner = new DiskScanService(null, disk, null, null, null, null, null, scanAuthorReads, h.Roots, null, h.Queue, h.Events, h.Logger); + + Set(h.Pending, "_repository", Proxy((method, args) => + { + if (method.Name == nameof(IPendingAuthorImportRepository.TryDelete) && !cancelled) + { + if (route == "folder") + { + h.QueueDiskScan(h.Commands.OfType().Single()); + scanner.Execute(h.Commands.OfType().Single()); + } + else + { + var snapshot = h.AuthorRows.FindByHardcoverId(pending.ProviderId); + if (route == "skipped") + { + CancelAfterRead(snapshot); + handler.Handle(new AuthorScanSkippedEvent(snapshot, AuthorScanSkippedReason.NoFolderEvidence)); + } + else + { + snapshot.AddOptions.InitialFormatSyncNotBefore = DateTime.UtcNow.AddSeconds(-1); + h.Authors.SetAddOptions(snapshot); + handler.Execute(new BulkSyncFormatMonitoringCommand(new List { snapshot.Id }) { InitialSetupAttempt = 1 }); + } + } + } + return method.Invoke(queueRows, args); + })); + + h.Available = true; + h.ProcessPending(); + + Assert.That(cancelled, Is.True, "The cancellation must complete after the scan read and before setup consumption."); + Assert.That(h.SearchTargets, Is.Empty); + Assert.That(h.AuthorRows.Get(authorId).AddOptions, Is.Null); + Assert.That(h.BookRows.GetBooks(authorId).Any(book => book.IsMonitored()), Is.False); + Assert.That(h.Commands.OfType(), Is.Empty); + }); + } + + [Test] + public void an_old_folder_scan_cannot_consume_setup_after_the_author_folder_changes([Values] bool postgres) + { + DualDatabaseFixture.Run(postgres, database => + { + var h = new Harness(database); + var request = h.Request("audiobook", false); + request.SearchForMissingBooks = true; + h.Import(request); + var scanned = h.AuthorRows.Get(h.Author.Id); + var moved = h.AuthorRows.Get(scanned.Id); + moved.AudiobookPath = System.IO.Path.Combine(h.AudioRoot.Path, "New Folder"); + h.Authors.UpdateAuthor(moved); + Assert.That(h.AuthorRows.Get(scanned.Id).AudiobookPath, Is.EqualTo(moved.AudiobookPath)); + Assert.That(moved.AudiobookPath, Is.Not.EqualTo(scanned.AudiobookPath)); + h.Commands.Clear(); + + h.Events.PublishEvent(new AuthorScannedEvent(scanned)); + + Assert.That(h.SearchTargets, Is.Empty); + Assert.That(h.AuthorRows.Get(scanned.Id).AddOptions?.SearchForMissingBooks, Is.True); + Assert.That(h.Commands, Is.Empty); + ScanSetupDuringScheduledRefresh(h, database, moved.AudiobookPath); + Assert.That(h.SearchTargets, Has.Count.EqualTo(1)); + Assert.That(h.AuthorRows.Get(scanned.Id).AddOptions, Is.Null); + }); + } + + [Test] + public void a_skipped_scan_keeps_setup_pending_when_the_media_scope_narrows([Values] bool postgres) + { + DualDatabaseFixture.Run(postgres, database => + { + var h = new Harness(database); + var request = h.Request("both", false); + request.SearchForMissingBooks = true; + h.Import(request); + var saved = h.AuthorRows.Get(h.Author.Id); + Assert.That(saved.AddOptions.GetInitialScanMediaType(), Is.EqualTo("all")); + h.Roots.All().Add(new RootFolder { Id = 10, Path = saved.AudiobookPath, FolderType = FolderType.Ebook }); + h.Roots.All().Add(new RootFolder { Id = 11, Path = saved.EbookPath, FolderType = FolderType.Audiobook }); + + AuthorScanSkippedEvent skipped = null; + var aggregator = (InterfaceProxy)(object)h.Events; + var publish = aggregator.Handler; + aggregator.Handler = (method, args) => + { + if (args[0] is AuthorScanSkippedEvent scanSkipped) skipped = scanSkipped; + return publish(method, args); + }; + h.QueueDiskScan(h.Commands.OfType().Single()); + Assert.That(skipped?.Reason, Is.EqualTo(AuthorScanSkippedReason.NoFolderEvidence)); + Assert.That(h.Commands.OfType(), Is.Empty); + h.Commands.Clear(); + + saved = h.AuthorRows.Get(saved.Id); + saved.AddOptions.EbookMonitor = null; + saved.AddOptions.EbookSetupPending = false; + saved.AddOptions.CancelInitialSearch(audiobookSetup: false, ebookSetup: true); + h.Authors.SetAddOptions(saved); + Assert.That(saved.AddOptions.GetInitialScanMediaType(), Is.EqualTo("audiobook")); + var handler = new AuthorScannedHandler(new BookMonitoredService(h.Authors, h.Books, h.Logger), h.Authors, + h.Queue, Proxy((_, _) => null), h.Events, h.Logger, h.Books, h.Pending); + + handler.Handle(skipped); + + Assert.That(h.SearchTargets, Is.Empty); + Assert.That(h.Commands, Is.Empty); + Assert.That(h.AuthorRows.Get(saved.Id).AddOptions?.SearchForMissingBooks, Is.True); + ScanSetupDuringScheduledRefresh(h, database, saved.AudiobookPath); + Assert.That(h.SearchTargets, Has.Count.EqualTo(1)); + Assert.That(h.AuthorRows.Get(saved.Id).AddOptions, Is.Null); + }); + } + + [Test] + public void scan_respects_a_committed_cancel_before_the_author_cleanup([Values] bool postgres, + [Values("all", "audiobook", "ebook", "worker-cleanup", "delete", "delete-active")] string scenario, + [Values("folder", "skipped", "retry")] string route) + { + DualDatabaseFixture.Run(postgres, database => + { + var h = new Harness(database) { Available = false }; + var cancelOneFormat = scenario is "audiobook" or "ebook" or "worker-cleanup"; + var cancelledSide = scenario == "ebook" ? BookMediaType.Ebook : BookMediaType.Audiobook; + var remainingSide = cancelledSide == BookMediaType.Audiobook ? "ebook" : "audiobook"; + var request = h.Request(cancelOneFormat ? "both" : "audiobook", false); + request.SearchForMissingBooks = true; + h.Import(request); + var pending = h.Pending.GetByProviderId("hc:123456"); + var rows = new PendingAuthorImportRepository(database, h.Events); + var reachedGap = false; + Set(h.Pending, "_repository", Proxy((method, args) => + { + if (method.Name == nameof(IPendingAuthorImportRepository.TryDelete) && !reachedGap) + { + var author = h.AuthorRows.FindByHardcoverId(pending.ProviderId); + if (scenario == "delete") + { + var incomplete = rows.Get(pending.Id); + incomplete.OverallStatus = PendingImportStatus.PartialSuccess; + incomplete.AudiobookStatus = PendingImportStatus.PartialSuccess; + Assert.That(rows.TryUpdateRequest(incomplete, incomplete.Version), Is.True); + h.Pending.Delete(pending.Id); + } + else if (scenario == "delete-active") + { + Assert.That(rows.Get(pending.Id).IsActive(), Is.True); + h.Pending.Delete(pending.Id); + } + else if (cancelOneFormat) + { + var edited = author.ShallowClone(); + if (cancelledSide == BookMediaType.Audiobook) + { + edited.AudiobookRootFolderPath = null; + edited.AudiobookQualityProfileId = null; + } + else + { + edited.EbookRootFolderPath = null; + edited.EbookQualityProfileId = null; + } + + var events = (InterfaceProxy)(object)h.Events; + var publish = events.Handler; + events.Handler = (eventMethod, eventArgs) => + { + if (eventArgs[0] is AuthorEditedEvent change) + { + var saved = h.AuthorRows.Get(change.Author.Id); + Assert.That(saved.HasMediaTypeSettings(cancelledSide), Is.False); + h.Pending.Handle(change); + } + return publish(eventMethod, eventArgs); + }; + try + { + h.Authors.UpdateAuthor(edited); + } + finally + { + events.Handler = publish; + } + } + else + { + h.Pending.Cancel(pending.Id); + } + } + + var result = method.Invoke(rows, args); + if (method.Name == nameof(IPendingAuthorImportRepository.TryUpdateRequest) && + result is true && args[0] is PendingAuthorImport { } updated && + updated.LastError?.StartsWith("Cancelled", StringComparison.Ordinal) == true) + { + var savedRequest = rows.Get(pending.Id); + Assert.That(cancelledSide == BookMediaType.Audiobook ? savedRequest.HasAudiobook() : savedRequest.HasEbook(), Is.False); + var setup = h.Author.AddOptions; + Assert.That(cancelledSide == BookMediaType.Audiobook ? setup?.AudiobookSetupPendingImportId : setup?.EbookSetupPendingImportId, + Is.EqualTo(pending.Id)); + reachedGap = true; + if (scenario == "worker-cleanup") + { + var stale = h.Author; + var finished = rows.Get(pending.Id); + finished.EbookStatus = PendingImportStatus.Succeeded; + Assert.That(h.Pending.TryDeleteIfUnchanged(finished, stale), Is.True); + Assert.That(h.Pending.TryDeleteIfUnchanged(finished, stale), Is.False); + Assert.That(h.Author.AddOptions?.EbookSetupPendingImportId, Is.EqualTo(pending.Id)); + } + var scanned = h.AuthorRows.Get(h.Author.Id); + if (route == "folder") + { + ScanFolders(h, scanned.GetScanPaths(scanned.AddOptions.GetInitialScanMediaType()), authorIds: new List { scanned.Id }); + } + else + { + var handler = new AuthorScannedHandler(new BookMonitoredService(h.Authors, h.Books, h.Logger), h.Authors, + h.Queue, Proxy((_, _) => null), h.Events, h.Logger, h.Books, h.Pending); + if (route == "skipped") + { + handler.Handle(new AuthorScanSkippedEvent(scanned, AuthorScanSkippedReason.NoFolderEvidence)); + } + else + { + scanned.AddOptions.InitialFormatSyncNotBefore = DateTime.UtcNow.AddSeconds(-1); + h.Authors.SetAddOptions(scanned); + handler.Execute(new BulkSyncFormatMonitoringCommand(new List { scanned.Id }) { InitialSetupAttempt = 1 }); + } + } + } + + return result; + })); + + h.Available = true; + h.ProcessPending(); + + Assert.That(reachedGap, Is.True); + if (route == "skipped" && cancelOneFormat && scenario != "worker-cleanup") + { + Assert.That(h.Commands.OfType(), Is.Empty); + Assert.That(h.Author.AddOptions.GetInitialScanMediaType(), Is.EqualTo(remainingSide)); + ScanFolders(h, h.Author.GetScanPaths(remainingSide), authorIds: new List { h.Author.Id }); + } + + Assert.That(h.AuthorRows.Get(h.Author.Id).AddOptions, Is.Null); + Assert.That(h.BookRows.GetBooks(h.Author.Id).Where(book => book.MediaType == cancelledSide).Any(book => book.IsMonitored()), Is.False); + Assert.That(h.Commands.OfType().Select(command => command.MediaType), + Is.EqualTo(cancelOneFormat ? new[] { remainingSide } : Array.Empty())); + }); + } + + [Test] + public void failed_owner_read_arms_a_setup_retry_only_after_a_covering_scan([Values] bool postgres, [Values] bool covering) + { + DualDatabaseFixture.Run(postgres, database => + { + var h = new Harness(database) { Available = false }; + var request = h.Request("both", false); + request.SearchForMissingBooks = true; + h.Import(request); + var pending = h.Pending.GetByProviderId("hc:123456"); + var rows = new PendingAuthorImportRepository(database, h.Events); + var failing = false; + var sawReadFailure = false; + var exercised = false; + Set(h.Pending, "_repository", Proxy((method, args) => + { + if (failing && method.Name == nameof(IPendingAuthorImportRepository.Find) && (int)args[0] == pending.Id) + { + sawReadFailure = true; + throw new InvalidOperationException("Owner row is temporarily unreadable"); + } + + if (method.Name == nameof(IPendingAuthorImportRepository.TryDelete) && !exercised) + { + exercised = true; + var author = h.AuthorRows.FindByHardcoverId(pending.ProviderId); + Assert.That(author.AddOptions.GetInitialScanMediaType(), Is.EqualTo("all")); + failing = true; + try + { + var folders = covering ? author.GetScanPaths("all") : new List { author.EbookPath }; + ScanFolders(h, folders, authorIds: new List { author.Id }); + } + finally + { + failing = false; + } + } + + return method.Invoke(rows, args); + })); + + h.Available = true; + h.ProcessPending(); + + Assert.That(exercised && sawReadFailure, Is.True); + var saved = h.AuthorRows.Get(h.Author.Id).AddOptions; + Assert.That(saved.AudiobookSetupPending, Is.True); + Assert.That(saved.EbookSetupPending, Is.True); + Assert.That(h.Commands.OfType(), Is.Empty); + + if (!covering) + { + Assert.That(saved.InitialFormatSyncNotBefore, Is.Null); + Assert.That(h.AuthorRows.GetDueInitialFormatSync(DateTime.UtcNow.AddMinutes(10)), Is.Empty); + return; + } + + Assert.That(saved.InitialFormatSyncFailureCount, Is.EqualTo(1)); + Assert.That(saved.InitialFormatSyncNotBefore, Is.InRange(DateTime.UtcNow, DateTime.UtcNow.AddSeconds(75))); + + var due = h.AuthorRows.Get(h.Author.Id); + due.AddOptions.InitialFormatSyncFailureCount = 3; + due.AddOptions.InitialFormatSyncNotBefore = DateTime.UtcNow.AddSeconds(-1); + h.Authors.SetAddOptions(due); + var handler = new AuthorScannedHandler(new BookMonitoredService(h.Authors, h.Books, h.Logger), h.Authors, + h.Queue, Proxy((_, _) => null), h.Events, h.Logger, h.Books, h.Pending); + FormatRetryTick(h, database); + var retry = h.Commands.OfType().Single(); + failing = true; + sawReadFailure = false; + handler.Execute(retry); + Assert.That(sawReadFailure, Is.True); + var rescheduled = h.AuthorRows.Get(due.Id); + Assert.That(rescheduled.AddOptions.InitialFormatSyncFailureCount, Is.EqualTo(4)); + Assert.That(rescheduled.AddOptions.InitialFormatSyncNotBefore, + Is.InRange(DateTime.UtcNow.AddMinutes(3), DateTime.UtcNow.AddMinutes(6.1))); + + failing = false; + handler.Execute(retry); + Assert.That(h.Commands.OfType(), Is.Empty, "A stale retry command must honor the newer deadline."); + rescheduled.AddOptions.InitialFormatSyncNotBefore = DateTime.UtcNow.AddSeconds(-1); + h.Authors.SetAddOptions(rescheduled); + handler.Execute(retry); + Assert.That(h.AuthorRows.Get(due.Id).AddOptions, Is.Null); + Assert.That(h.SearchTargets, Has.Count.EqualTo(1)); + }); + } + + [Test] + public void a_failed_withdrawal_save_cannot_restore_a_committed_cancellation([Values] bool postgres, [Values] bool skipped) + { + DualDatabaseFixture.Run(postgres, database => + { + var h = new Harness(database) { Available = false }; + var request = h.Request("both", false); + request.SearchForMissingBooks = true; + h.Import(request); + var pending = h.Pending.GetByProviderId("hc:123456"); + var rows = new PendingAuthorImportRepository(database, h.Events); + var failed = false; + var exercised = false; + + var writes = Proxy((method, args) => + { + var result = method.Invoke(h.Authors, args); + if (method.Name == nameof(IAuthorService.SetAddOptions) && !failed) + { + failed = true; + throw new InvalidOperationException("Connection lost after saving withdrawal"); + } + return result; + }); + + Set(h.Pending, "_repository", Proxy((method, args) => + { + if (method.Name == nameof(IPendingAuthorImportRepository.TryDelete) && !exercised) + { + exercised = true; + var savedRequest = rows.Get(pending.Id); + savedRequest.AudiobookStatus = PendingImportStatus.NotRequested; + Assert.That(rows.TryUpdateRequest(savedRequest, savedRequest.Version), Is.True); + var author = h.AuthorRows.Get(h.Author.Id); + var folders = author.GetScanPaths("all"); + Set(h.Pending, "_authorService", writes); + try + { + if (skipped) + { + var handler = new AuthorScannedHandler(new BookMonitoredService(h.Authors, h.Books, h.Logger), h.Authors, + h.Queue, Proxy((_, _) => null), h.Events, h.Logger, h.Books, h.Pending); + handler.Handle(new AuthorScanSkippedEvent(author, AuthorScanSkippedReason.NoFolderEvidence)); + } + else + { + ScanFolders(h, folders, authorIds: new List { author.Id }); + } + } + finally + { + Set(h.Pending, "_authorService", h.Authors); + } + } + + return method.Invoke(rows, args); + })); + + h.Available = true; + h.ProcessPending(); + + Assert.That(exercised && failed, Is.True); + var setup = h.AuthorRows.Get(h.Author.Id).AddOptions; + Assert.That(setup.AudiobookSetupPendingImportId, Is.Null); + Assert.That(setup.EbookSetupPendingImportId, Is.EqualTo(pending.Id)); + Assert.That(setup.InitialFormatSyncFailureCount, Is.EqualTo(skipped ? 0 : 1)); + Assert.That(setup.InitialFormatSyncNotBefore, skipped ? Is.Null : Is.Not.Null); + Assert.That(h.Commands.OfType(), Is.Empty); + }); + } + + [Test] + public void adding_a_second_format_invalidates_a_retry_from_the_first_folders([Values] bool postgres) + { + DualDatabaseFixture.Run(postgres, database => + { + var h = new Harness(database); + var first = h.Request("audiobook", false); + first.SearchForMissingBooks = true; + h.Import(first); + var audio = h.AuthorRows.Get(h.Author.Id); + Assert.That(audio.AddOptions.GetInitialScanMediaType(), Is.EqualTo("audiobook")); + audio.AddOptions.InitialFormatSyncFailureCount = 3; + audio.AddOptions.InitialFormatSyncNotBefore = DateTime.UtcNow.AddMinutes(-1); + h.Authors.SetAddOptions(audio); + Assert.That(h.AuthorRows.GetDueInitialFormatSync(DateTime.UtcNow), Is.EqualTo(new[] { audio.Id })); + h.Commands.Clear(); + + h.Import(h.Request("ebook", false)); + + var both = h.AuthorRows.Get(audio.Id); + Assert.That(both.AddOptions.GetInitialScanMediaType(), Is.EqualTo("all")); + Assert.That(both.AddOptions.InitialFormatSyncNotBefore, Is.Null); + FormatRetryTick(h, database); + Assert.That(h.Commands.OfType(), Is.Empty); + Assert.That(h.Commands.OfType(), Is.Empty); + ScanFolders(h, both.GetScanPaths("all"), authorIds: new List { both.Id }); + Assert.That(h.AuthorRows.Get(both.Id).AddOptions, Is.Null); + Assert.That(h.Commands.OfType().Single().MediaType, Is.EqualTo("audiobook")); + }); + } + + [Test] + public void author_import_does_not_restore_a_request_deleted_after_catalog_handoff([Values] bool postgres) + { + DualDatabaseFixture.Run(postgres, database => + { + var h = new Harness(database) { Available = false }; + var first = h.Request("audiobook", false); + first.SearchForMissingBooks = true; + h.Import(first); + var pending = h.Pending.GetByProviderId("hc:123456"); + var rows = new PendingAuthorImportRepository(database, h.Events); + var deleted = false; + var importStarted = false; + + async Task DeleteAfterCatalog(Task operation) + { + var added = await operation; + Assert.That(added.Id, Is.Positive); + Assert.That(added.AddOptions?.AudiobookSetupPendingImportId, Is.EqualTo(pending.Id)); + h.Pending.Delete(pending.Id); + Assert.That(h.Pending.Get(pending.Id), Is.Null); + Assert.That(h.AuthorRows.Get(added.Id).AddOptions?.AudiobookSetupPendingImportId, Is.Null); + deleted = true; + return added; + } + + Set(h.Controller, "_authorLibraryService", Proxy((method, args) => + { + var result = method.Invoke(h.Library, args); + return method.Name == nameof(IAuthorLibraryService.AddAuthorAsync) ? DeleteAfterCatalog((Task)result) : result; + })); + Set(h.Pending, "_repository", Proxy((method, args) => + { + if (!importStarted && method.Name == nameof(IPendingAuthorImportRepository.TryDelete)) + { + importStarted = true; + Assert.That(h.AuthorRows.Get(h.Author.Id).AddOptions?.AudiobookSetupPendingImportId, Is.EqualTo(pending.Id)); + var ebook = h.Request("ebook", false); + ebook.SearchForMissingBooks = true; + h.Import(ebook); + } + return method.Invoke(rows, args); + })); + h.Available = true; + h.ProcessPending(); + + Assert.That(deleted, Is.True); + var saved = h.AuthorRows.Get(h.Author.Id); + Assert.That(saved.AddOptions?.AudiobookSetupPendingImportId, Is.Null); + Assert.That(saved.AddOptions?.AudiobookSetupSearchForMissingBooks, Is.False); + ScanFolders(h, saved.GetScanPaths("ebook"), authorIds: new List { saved.Id }); + Assert.That(h.Commands.OfType().Single().MediaType, Is.EqualTo("ebook")); + }); + } + + private static void ScanSetupDuringScheduledRefresh(Harness h, IMainDatabase database, string folder) + { + HydrationRefresh(h, database, h.Info, RescanAfterRefreshType.Never).Execute(new RefreshAuthorCommand + { + RefreshMetadata = false, + Trigger = CommandTrigger.Scheduled + }); + + var scan = h.Commands.OfType().Single(); + Assert.That(scan.Folders, Is.EqualTo(new[] { folder })); + Assert.That(scan.MediaType, Is.EqualTo("audiobook")); + Assert.That(scan.Filter, Is.EqualTo(FilterFilesType.Matched)); + ScanFolders(h, scan.Folders, authorIds: scan.AuthorIds); + } + } +} diff --git a/src/Chaptarr.Core.Test/Books/AuthorSyncOptionsFixture.Hydration.cs b/src/Chaptarr.Core.Test/Books/AuthorSyncOptionsFixture.Hydration.cs index 8763a1ce7..623fdbdd8 100644 --- a/src/Chaptarr.Core.Test/Books/AuthorSyncOptionsFixture.Hydration.cs +++ b/src/Chaptarr.Core.Test/Books/AuthorSyncOptionsFixture.Hydration.cs @@ -214,7 +214,7 @@ Author AddOther(string id, bool awaiting) => h.Authors.AddAuthor(new Author Assert.That(h.SearchTargets, Is.Empty); h.Scan(); var handler = new AuthorScannedHandler(new BookMonitoredService(h.Authors, h.Books, h.Logger), h.Authors, h.Queue, - Proxy((_, _) => null), h.Events, h.Logger, h.Books); + Proxy((_, _) => null), h.Events, h.Logger, h.Books, h.Pending); handler.Handle(new AuthorScannedEvent(h.Authors.GetAuthor(ready.Id))); Assert.That(h.Author.AddOptions?.SearchForMissingBooks, Is.True); Assert.That(h.Authors.GetAuthor(ready.Id).AddOptions, Is.Null); @@ -245,7 +245,7 @@ public void failed_hydration_preserves_setup_across_scan_and_retry( for (var attempt = 0; attempt < 2; attempt++) { var handler = new AuthorScannedHandler(new BookMonitoredService(h.Authors, h.Books, h.Logger), - h.Authors, h.Queue, Proxy((_, _) => null), h.Events, h.Logger, h.Books); + h.Authors, h.Queue, Proxy((_, _) => null), h.Events, h.Logger, h.Books, h.Pending); if (skipped) handler.Handle(new AuthorScanSkippedEvent(h.Author, AuthorScanSkippedReason.NoFolderEvidence)); else diff --git a/src/Chaptarr.Core.Test/Books/AuthorSyncOptionsFixture.ImportSync.cs b/src/Chaptarr.Core.Test/Books/AuthorSyncOptionsFixture.ImportSync.cs index d23a48979..484ceb154 100644 --- a/src/Chaptarr.Core.Test/Books/AuthorSyncOptionsFixture.ImportSync.cs +++ b/src/Chaptarr.Core.Test/Books/AuthorSyncOptionsFixture.ImportSync.cs @@ -52,7 +52,7 @@ public void import_sync_explicit_enable_uses_existing_command_for_settled_author }); var command = (BulkSyncFormatMonitoringCommand)h.Commands.Single(); Assert.That(command.AuthorIds, Is.EqualTo(new[] { h.Author.Id })); - new AuthorScannedHandler(null, h.Authors, h.Queue, null, h.Events, h.Logger, h.Books).Execute(command); + new AuthorScannedHandler(null, h.Authors, h.Queue, null, h.Events, h.Logger, h.Books, h.Pending).Execute(command); Assert.That(h.BookRows.GetBooksByAuthorId(h.Author.Id).Select(book => book.IsMonitored()), Is.EqualTo(new[] { true, true })); }); } @@ -187,7 +187,7 @@ public void import_sync_repeated_enable_recovers_rejected_command_handoff([Value Assert.That(h.Author.SyncMonitoredAcrossFormats, Is.True); Set(h.Controller, "_commandQueueManager", h.Queue); h.Import(request); - new AuthorScannedHandler(null, h.Authors, h.Queue, null, h.Events, h.Logger, h.Books) + new AuthorScannedHandler(null, h.Authors, h.Queue, null, h.Events, h.Logger, h.Books, h.Pending) .Execute(h.Commands.OfType().Single()); Assert.That(h.BookRows.GetBooksByAuthorId(h.Author.Id).Select(book => book.IsMonitored()), Is.EqualTo(new[] { true, true })); Assert.That(h.MetadataFetches, Is.Zero); @@ -206,7 +206,7 @@ public void import_sync_command_honors_disable_before_execution([Values(false, t h.Import(request); request.SyncMonitoredAcrossFormats = false; h.Import(request); - new AuthorScannedHandler(null, h.Authors, h.Queue, null, h.Events, h.Logger, h.Books) + new AuthorScannedHandler(null, h.Authors, h.Queue, null, h.Events, h.Logger, h.Books, h.Pending) .Execute(h.Commands.OfType().Single()); Assert.That(h.Author.SyncMonitoredAcrossFormats, Is.False); Assert.That(h.Commands, Has.Count.EqualTo(1)); diff --git a/src/Chaptarr.Core.Test/Books/AuthorSyncOptionsFixture.ReconcileRetry.cs b/src/Chaptarr.Core.Test/Books/AuthorSyncOptionsFixture.ReconcileRetry.cs index 01bb82a79..6346da0bb 100644 --- a/src/Chaptarr.Core.Test/Books/AuthorSyncOptionsFixture.ReconcileRetry.cs +++ b/src/Chaptarr.Core.Test/Books/AuthorSyncOptionsFixture.ReconcileRetry.cs @@ -63,7 +63,7 @@ public void failed_reconcile_retries_without_reapplying_consumed_initial_default h.Import(request); var subject = new AuthorScannedHandler(new BookMonitoredService(h.Authors, h.Books, h.Logger), h.Authors, h.Queue, Proxy((_, _) => null), h.Events, h.Logger, - Proxy((_, _) => throw new InvalidOperationException("Reconcile database unavailable"))); + Proxy((_, _) => throw new InvalidOperationException("Reconcile database unavailable")), h.Pending); subject.Handle(new AuthorScannedEvent(h.Author)); var persisted = new AuthorRepository(database, h.Events, h.Logger).Get(h.Author.Id); @@ -96,7 +96,7 @@ public void failed_reconcile_retries_without_reapplying_consumed_initial_default Assert.That(retry.AuthorIds, Is.EqualTo(new[] { h.Author.Id })); Assert.That(retry.Trigger, Is.EqualTo(CommandTrigger.Scheduled)); new AuthorScannedHandler(new BookMonitoredService(h.Authors, h.Books, h.Logger), h.Authors, h.Queue, - Proxy((_, _) => null), h.Events, h.Logger, h.Books).Execute(retry); + Proxy((_, _) => null), h.Events, h.Logger, h.Books, h.Pending).Execute(retry); Assert.That(unwanted.Select(b => h.BookRows.Get(b.Id).IsMonitored()), Is.All.False); Assert.That(h.BookRows.Get(wantedTwin.Id).IsMonitored(), Is.True); @@ -121,7 +121,7 @@ public void initial_sync_retry_spacing_survives_restart_and_keeps_retrying_at_th Assert.That(method.Name, Is.EqualTo(nameof(IBookService.SyncMonitoredAcrossFormats))); syncCalls++; throw new InvalidOperationException("Reconcile unavailable"); - })); + }), h.Pending); Handler().Handle(new AuthorScannedEvent(h.Author)); var metadataReads = h.MetadataFetches; var originalCommands = h.Commands.Count; @@ -174,7 +174,7 @@ public void pending_setup_index_keeps_due_selection_exact([Values(false, true)] AwaitingMetadata = state == "waiting-metadata", MetadataUnavailable = state == "unavailable" }; - repository.Update(author); + h.Authors.SetAddOptions(author); Assert.That(repository.GetDueInitialFormatSync(now), Is.EqualTo(state == "due" ? new[] { author.Id } : Array.Empty()), state); } }); @@ -230,20 +230,23 @@ public void setup_retry_cancellation_propagates_without_backoff_or_consuming_the { var h = new Harness(database); h.Import(h.Request()); - var before = h.Author.AddOptions.InitialFormatSyncFailureCount; + var author = h.Author; + author.AddOptions.InitialFormatSyncNotBefore = DateTime.UtcNow.AddMinutes(-1); + h.Authors.SetAddOptions(author); + var before = h.AuthorRows.Get(author.Id).AddOptions; var calls = 0; var handler = new AuthorScannedHandler(Proxy((_, _) => { calls++; throw new OperationCanceledException("setup cancelled"); - }), h.Authors, h.Queue, Proxy((_, _) => null), h.Events, h.Logger, h.Books); + }), h.Authors, h.Queue, Proxy((_, _) => null), h.Events, h.Logger, h.Books, h.Pending); Assert.Throws(() => handler.Execute( new BulkSyncFormatMonitoringCommand(new() { h.Author.Id }) { InitialSetupAttempt = 1 })); Assert.That(calls, Is.EqualTo(1)); var stored = h.AuthorRows.Get(h.Author.Id).AddOptions; Assert.That(stored, Is.Not.Null); - Assert.That(stored.InitialFormatSyncFailureCount, Is.EqualTo(before)); - Assert.That(stored.InitialFormatSyncNotBefore, Is.Null); + Assert.That(stored.InitialFormatSyncFailureCount, Is.EqualTo(before.InitialFormatSyncFailureCount)); + Assert.That(stored.InitialFormatSyncNotBefore, Is.EqualTo(before.InitialFormatSyncNotBefore)); Assert.That(h.SearchTargets, Is.Empty); }); } diff --git a/src/Chaptarr.Core.Test/Books/AuthorSyncOptionsFixture.Round14Lifecycle.cs b/src/Chaptarr.Core.Test/Books/AuthorSyncOptionsFixture.Round14Lifecycle.cs index d910def33..853a8fba2 100644 --- a/src/Chaptarr.Core.Test/Books/AuthorSyncOptionsFixture.Round14Lifecycle.cs +++ b/src/Chaptarr.Core.Test/Books/AuthorSyncOptionsFixture.Round14Lifecycle.cs @@ -33,13 +33,15 @@ public void failed_monitoring_checkpoint_preserves_the_unacknowledged_choice_for var writes = 0; var authorService = Proxy((method, args) => { + if (method.Name == nameof(IAuthorService.GetExistingAuthors)) + return h.Authors.GetExistingAuthors((IEnumerable)args[0]); Assert.That(method.Name, Is.EqualTo(nameof(IAuthorService.SetAddOptions))); if (++writes == 1) throw new InvalidOperationException("Checkpoint write unavailable"); h.Authors.SetAddOptions((Author)args[0]); return null; }); new AuthorScannedHandler(new BookMonitoredService(h.Authors, h.Books, h.Logger), - authorService, h.Queue, Proxy((_, _) => null), h.Events, h.Logger, h.Books) + authorService, h.Queue, Proxy((_, _) => null), h.Events, h.Logger, h.Books, h.Pending) .Handle(new AuthorScannedEvent(author)); var stored = h.AuthorRows.Get(author.Id).AddOptions; @@ -63,7 +65,7 @@ public void first_scan_monitoring_failure_is_persisted_and_selected_by_the_minut h.Import(h.Request("both", false)); var subject = new AuthorScannedHandler(Proxy((_, _) => throw new InvalidOperationException("First monitoring write unavailable")), - h.Authors, h.Queue, Proxy((_, _) => null), h.Events, h.Logger, h.Books); + h.Authors, h.Queue, Proxy((_, _) => null), h.Events, h.Logger, h.Books, h.Pending); if (skipped) subject.Handle(new AuthorScanSkippedEvent(h.Author, AuthorScanSkippedReason.NoFolderEvidence)); else subject.Handle(new AuthorScannedEvent(h.Author)); @@ -79,7 +81,7 @@ public void first_scan_monitoring_failure_is_persisted_and_selected_by_the_minut var retry = h.Commands.OfType().Single(); Assert.That(retry.AuthorIds, Is.EqualTo(new[] { saved.Id })); new AuthorScannedHandler(new BookMonitoredService(h.Authors, h.Books, h.Logger), - h.Authors, h.Queue, Proxy((_, _) => null), h.Events, h.Logger, h.Books).Execute(retry); + h.Authors, h.Queue, Proxy((_, _) => null), h.Events, h.Logger, h.Books, h.Pending).Execute(retry); Assert.That(h.AuthorRows.Get(saved.Id).AddOptions, Is.Null); Assert.That(h.BookRows.GetBooksByAuthorId(saved.Id).All(book => book.IsMonitored()), Is.True); }); @@ -102,7 +104,7 @@ public void second_media_monitoring_failure_does_not_reapply_the_checkpointed_fi if (options.MediaType == BookMediaType.Ebook) throw new InvalidOperationException("Second media unavailable"); realMonitoring.SetBookMonitoredStatus((Author)args[0], options, initialSetup: true); return null; - }), h.Authors, h.Queue, Proxy((_, _) => null), h.Events, h.Logger, h.Books); + }), h.Authors, h.Queue, Proxy((_, _) => null), h.Events, h.Logger, h.Books, h.Pending); subject.Handle(new AuthorScannedEvent(h.Author)); var saved = h.AuthorRows.Get(h.Author.Id); @@ -118,7 +120,7 @@ public void second_media_monitoring_failure_does_not_reapply_the_checkpointed_fi FormatRetryTick(h, database); var retry = h.Commands.OfType().Single(); new AuthorScannedHandler(realMonitoring, h.Authors, h.Queue, - Proxy((_, _) => null), h.Events, h.Logger, h.Books).Execute(retry); + Proxy((_, _) => null), h.Events, h.Logger, h.Books, h.Pending).Execute(retry); var ebook = h.BookRows.GetBooksByAuthorId(saved.Id).Single(book => book.MediaType == BookMediaType.Ebook); Assert.That(h.BookRows.Get(audio.Id).IsMonitored(), Is.False, @@ -154,8 +156,11 @@ public void setup_retry_selection_is_ordered_bounded_and_leaves_the_remainder_fo var expected = authors.OrderBy(author => author.AddOptions.InitialFormatSyncNotBefore).ThenBy(author => author.Id).ToList(); var first = h.AuthorRows.GetDueInitialFormatSync(now); Assert.That(first, Is.EqualTo(expected.Take(100).Select(author => author.Id))); - foreach (var author in expected.Take(100)) author.AddOptions = null; - h.AuthorRows.UpdateMany(expected.Take(100).ToList()); + foreach (var author in expected.Take(100)) + { + author.AddOptions = null; + h.Authors.SetAddOptions(author); + } Assert.That(h.AuthorRows.GetDueInitialFormatSync(now), Is.EqualTo(expected.Skip(100).Select(author => author.Id))); }); } diff --git a/src/Chaptarr.Core.Test/Books/AuthorSyncOptionsFixture.cs b/src/Chaptarr.Core.Test/Books/AuthorSyncOptionsFixture.cs index fe2bc2815..7b9d9fc78 100644 --- a/src/Chaptarr.Core.Test/Books/AuthorSyncOptionsFixture.cs +++ b/src/Chaptarr.Core.Test/Books/AuthorSyncOptionsFixture.cs @@ -98,7 +98,7 @@ public Harness(IMainDatabase database, string fileRoot = null, Logger logger = n new AuthorEditedService(Queue, Logger).Handle(edited); if (args[0] is AuthorScannedEvent scanned) new AuthorScannedHandler(new BookMonitoredService(Authors, Books, Logger), Authors, Queue, - Proxy((_, _) => null), Events, Logger, Books).Handle(scanned); + Proxy((_, _) => null), Events, Logger, Books, Pending).Handle(scanned); return null; }); Files = new MediaFileRepository(database, Events); @@ -189,7 +189,7 @@ public Harness(IMainDatabase database, string fileRoot = null, Logger logger = n }; public void Import(AuthorImportResource request) => Controller.ImportAuthor(request).GetAwaiter().GetResult(); public void Scan() => new AuthorScannedHandler(new BookMonitoredService(Authors, Books, Logger), Authors, Queue, - Proxy((_, _) => null), Events, Logger, Books).Handle(new AuthorScannedEvent(Author)); + Proxy((_, _) => null), Events, Logger, Books, Pending).Handle(new AuthorScannedEvent(Author)); public void QueueDiskScan(RefreshAuthorCommand command) { var refresh = new RefreshAuthorService(MetadataHealthGateStub.Ready(), authorInfo: null, authorService: Authors, bookService: Books, diff --git a/src/Chaptarr.Core.Test/Books/BookAddedServiceMonitoringFixture.cs b/src/Chaptarr.Core.Test/Books/BookAddedServiceMonitoringFixture.cs index 7426a6120..ca64da909 100644 --- a/src/Chaptarr.Core.Test/Books/BookAddedServiceMonitoringFixture.cs +++ b/src/Chaptarr.Core.Test/Books/BookAddedServiceMonitoringFixture.cs @@ -150,7 +150,7 @@ public void rejected_exact_search_should_still_finish_automatic_search_and_scan_ subject.Handle(new BookInfoRefreshedEvent(author, new List { automatic }, new List(), new List())); queue.RejectPush = 1; var events = new RecordingEventAggregator(); - var handler = new AuthorScannedHandler(null, null, queue, subject, events, LogManager.GetCurrentClassLogger(), Chaptarr.Core.Test.Common.InterfaceProxy.Proxy((_, _) => throw new NotSupportedException())); + var handler = new AuthorScannedHandler(null, null, queue, subject, events, LogManager.GetCurrentClassLogger(), Chaptarr.Core.Test.Common.InterfaceProxy.Proxy((_, _) => throw new NotSupportedException()), global::Chaptarr.Core.Test.Common.FixturePendingAuthorImports.Empty()); Assert.DoesNotThrow(() => { diff --git a/src/Chaptarr.Core.Test/Books/PendingAuthorImportRetryFixture.cs b/src/Chaptarr.Core.Test/Books/PendingAuthorImportRetryFixture.cs index 6a16b3242..24a6cdaa4 100644 --- a/src/Chaptarr.Core.Test/Books/PendingAuthorImportRetryFixture.cs +++ b/src/Chaptarr.Core.Test/Books/PendingAuthorImportRetryFixture.cs @@ -13,6 +13,7 @@ using NzbDrone.Core.Books.Commands; using NzbDrone.Core.Books.Events; using NzbDrone.Core.Books.Services; +using NzbDrone.Core.Exceptions; using NzbDrone.Core.ImportLists.Exclusions; using NzbDrone.Core.Messaging.Commands; using NzbDrone.Core.Messaging.Events; @@ -1263,5 +1264,55 @@ public void retry_now_should_refetch_after_a_version_miss_and_preserve_concurren Assert.That(repositoryProxy.FencedUpdateCount, Is.EqualTo(2)); Assert.That(repositoryProxy.UnfencedUpdateCount, Is.Zero); } + + [Test] + public void metadata_refusal_does_not_restore_a_cancelled_request_with_a_stale_author_checkpoint([Values(false, true)] bool postgres) + { + DualDatabaseFixture.Run(postgres, database => + { + const string providerId = "hc:9001"; + var events = new RecordingEventAggregator(); + var repository = new PendingAuthorImportRepository(database, events); + var authorWrites = 0; + var row = repository.Insert(new PendingAuthorImport + { + ProviderId = providerId, + ProviderPrefix = "hc", + CreatedAt = DateTime.UtcNow, + NextAttemptAt = DateTime.UtcNow, + OverallStatus = PendingImportStatus.Failed, + AudiobookStatus = PendingImportStatus.NotRequested, + EbookStatus = PendingImportStatus.NotRequested + }); + var author = new Author + { + Id = 42, Name = "Author", + AddOptions = new AddAuthorOptions + { + AwaitingMetadata = true, AudiobookAwaitingMetadata = true, + AudiobookSetupPending = true, AudiobookMonitor = MonitorTypes.All, + AudiobookSetupPendingImportId = row.Id + } + }; + var authors = Proxy((method, args) => + { + if (method.Name is nameof(IAuthorService.FindByProviderId) or nameof(IAuthorService.GetAuthor)) return author; + Assert.That(method.Name, Is.EqualTo(nameof(IAuthorService.SetAddOptions))); + authorWrites++; + author = (Author)args[0]; + return null; + }); + var service = new PendingAuthorImportService(repository, authors, events, LogManager.GetCurrentClassLogger()); + service.Handle(new AuthorSetupMetadataRefusedEvent(author, providerId, + new AuthorTerminalException("author_provider_record_missing", providerId, null, "Declared stop", false))); + + Assert.That(repository.GetAll().Count, Is.EqualTo(1)); + Assert.That(authorWrites, Is.Zero); + service.Cancel(row.Id); + Assert.That(author.AddOptions, Is.Null); + service.Cancel(row.Id); + Assert.That(authorWrites, Is.EqualTo(1)); + }); + } } } diff --git a/src/Chaptarr.Core.Test/Books/PersistedAliasPendingLifecycleFixture.HeldSearch.cs b/src/Chaptarr.Core.Test/Books/PersistedAliasPendingLifecycleFixture.HeldSearch.cs index e3621cbe6..368f0ef45 100644 --- a/src/Chaptarr.Core.Test/Books/PersistedAliasPendingLifecycleFixture.HeldSearch.cs +++ b/src/Chaptarr.Core.Test/Books/PersistedAliasPendingLifecycleFixture.HeldSearch.cs @@ -36,6 +36,7 @@ public void pending_held_search_acknowledges_ready_rows_before_sibling_retries( h.Author.EbookMonitored = media == BookMediaType.Ebook; h.Author.AddOptions = new AddAuthorOptions { SearchForMissingBooks = true }; h.Authors.Update(h.Author); + h.AuthorService.SetAddOptions(h.Author); var ready = h.AddBook(media, "hc:7000", "hc:edition:7000"); ready.ReleaseDate = DateTime.UtcNow.AddDays(-1); h.Books.Update(ready); @@ -84,7 +85,6 @@ public void pending_held_search_acknowledges_ready_rows_before_sibling_retries( Assert.That(h.Commands.OfType().Single().AuthorId, Is.EqualTo(h.Author.Id)); Assert.That(h.Commands.OfType(), Is.Empty); Assert.That(h.Authors.Get(h.Author.Id).AddOptions, Is.Null); - Assert.That(h.Author.AddOptions, Is.Null); }); var late = h.AddBook(media, "hc:7001", "hc:edition:7001"); @@ -119,6 +119,7 @@ public void pending_held_search_keeps_rejected_paused_side_and_native_demand( h.Author.EbookMonitored = media != BookMediaType.Ebook || native; h.Author.AddOptions = new AddAuthorOptions { SearchForMissingBooks = true }; h.Authors.Update(h.Author); + h.AuthorService.SetAddOptions(h.Author); var requested = h.AddBook(media, "hc:7000", "hc:edition:7000"); var request = h.Request(new List { "hc:7000" }); if (media == BookMediaType.Ebook) @@ -175,6 +176,7 @@ public void pending_held_search_acknowledgment_stays_batched( h.Author.EbookMonitored = media == BookMediaType.Ebook; h.Author.AddOptions = new AddAuthorOptions { SearchForMissingBooks = true }; h.Authors.Update(h.Author); + h.AuthorService.SetAddOptions(h.Author); var ids = Enumerable.Range(0, count).Select(index => "hc:" + (7000 + index)).ToList(); foreach (var id in ids) { @@ -223,8 +225,10 @@ private static void CompleteHeldScan(Harness h) var authors = new AuthorService(h.Authors, h.EventAggregator, null, null, h.Queue, new CacheManager(), h.Books, null, logger, null, null, new Lazy(() => h.BookService), mainDatabase: h.Database, h.Aliases); new AuthorScannedHandler(new BookMonitoredService(authors, h.BookService, logger), authors, h.Queue, - new BookAddedService(new CacheManager(), h.Queue, h.BookService, logger), h.EventAggregator, logger, h.BookService) - .Handle(new AuthorScannedEvent(h.Author)); + new BookAddedService(new CacheManager(), h.Queue, h.BookService, logger), h.EventAggregator, logger, h.BookService, h.Pending) + .Handle(new AuthorScannedEvent(h.Authors.Get(h.Author.Id))); + // The fake library normally returns the same author object for every import. + h.Author.AddOptions = h.Authors.Get(h.Author.Id).AddOptions; } } } diff --git a/src/Chaptarr.Core.Test/Books/PersistedAliasPendingLifecycleFixture.LifecycleCorrections.cs b/src/Chaptarr.Core.Test/Books/PersistedAliasPendingLifecycleFixture.LifecycleCorrections.cs index 0ae05bd16..07bfea40d 100644 --- a/src/Chaptarr.Core.Test/Books/PersistedAliasPendingLifecycleFixture.LifecycleCorrections.cs +++ b/src/Chaptarr.Core.Test/Books/PersistedAliasPendingLifecycleFixture.LifecycleCorrections.cs @@ -503,7 +503,7 @@ public void withdrawn_held_searches_are_cleared_in_one_batch_unless_current_dema ids.Add("hc:8999"); var item = CorrectionRequest(h, media, ids, narrations); h.Author.AddOptions = new AddAuthorOptions { SearchForMissingBooks = true }; - h.Authors.Update(h.Author); + h.AuthorService.SetAddOptions(h.Author); var rejected = Proxy((method, args) => { if (args[0] is BookSearchCommand) throw new InvalidOperationException("Injected queue rejection"); diff --git a/src/Chaptarr.Core.Test/Books/PersistedAliasPendingLifecycleFixture.PrimaryRouting.cs b/src/Chaptarr.Core.Test/Books/PersistedAliasPendingLifecycleFixture.PrimaryRouting.cs index 4b8358230..ae1855f71 100644 --- a/src/Chaptarr.Core.Test/Books/PersistedAliasPendingLifecycleFixture.PrimaryRouting.cs +++ b/src/Chaptarr.Core.Test/Books/PersistedAliasPendingLifecycleFixture.PrimaryRouting.cs @@ -152,6 +152,7 @@ public void pending_partial_list_progress_preserves_unready_implicit_search( h.Author.AudiobookMonitored = heldAuthorSearch; h.Author.AddOptions = heldAuthorSearch ? new AddAuthorOptions { SearchForMissingBooks = true } : null; h.Authors.Update(h.Author); + h.AuthorService.SetAddOptions(h.Author); var ready = h.AddBook(work: "hc:7000", edition: "hc:edition:7000"); ready.ReleaseDate = DateTime.UtcNow.AddDays(-1); h.Books.Update(ready); diff --git a/src/Chaptarr.Core.Test/Books/PersistedAliasPendingLifecycleFixture.Progress.cs b/src/Chaptarr.Core.Test/Books/PersistedAliasPendingLifecycleFixture.Progress.cs index 7b51d74f9..be08e72c4 100644 --- a/src/Chaptarr.Core.Test/Books/PersistedAliasPendingLifecycleFixture.Progress.cs +++ b/src/Chaptarr.Core.Test/Books/PersistedAliasPendingLifecycleFixture.Progress.cs @@ -305,7 +305,7 @@ public void actual_add_book_work_scope_ignores_inherited_author_defaults_after_f h.Source.AudiobookMonitored = h.Source.EbookMonitored = true; h.Source.AudiobookMonitorNewItems = h.Source.EbookMonitorNewItems = NewItemMonitorTypes.All; h.Source.AddOptions = new AddAuthorOptions { Monitor = broadCatalog ? MonitorTypes.All : MonitorTypes.SpecificBook }; - h.Library.Authors.Update(h.Source); + h.Library.AuthorService.SetAddOptions(h.Source); var initialBooks = Proxy((method, _) => method.Name == nameof(IBookService.FindByProviderId) ? null : throw new AssertionException(method.Name)); var initialInfo = Proxy((_, args) => throw new BookNotFoundException((string)args[0])); diff --git a/src/Chaptarr.Core.Test/Books/PersistedAliasPendingLifecycleFixture.cs b/src/Chaptarr.Core.Test/Books/PersistedAliasPendingLifecycleFixture.cs index edec3d8a0..07a21ee18 100644 --- a/src/Chaptarr.Core.Test/Books/PersistedAliasPendingLifecycleFixture.cs +++ b/src/Chaptarr.Core.Test/Books/PersistedAliasPendingLifecycleFixture.cs @@ -85,6 +85,7 @@ public Harness(IMainDatabase database) AuthorService = Proxy((method, args) => method.Name switch { nameof(IAuthorService.GetAuthor) => ReadOwner((int)args[0]), + nameof(IAuthorService.SetAddOptions) => SaveSetup((Author)args[0]), nameof(IAuthorService.GetAuthors) => Authors.Get((IEnumerable)args[0]).ToList(), nameof(IAuthorService.GetExistingAuthors) => ReadOwners((IEnumerable)args[0]), nameof(IAuthorService.FindByProviderId) => Author, @@ -108,6 +109,12 @@ public Harness(IMainDatabase database) }); } + private object SaveSetup(Author author) + { + Authors.SetFields(author, row => row.AddOptions); + return null; + } + private Author ReadOwner(int id) { SingleOwnerReads++; @@ -503,6 +510,7 @@ public void rejected_list_batch_preserves_all_search_intent_before_retry(bool po { var h = new Harness(database); h.Author.AddOptions = new AddAuthorOptions(); + h.AuthorService.SetAddOptions(h.Author); var first = h.AddBook(); var second = h.AddBook(work: "hc:7000", edition: "hc:edition:7001"); var pending = h.Request(new() { "hc:698880", "hc:7000" }); @@ -595,6 +603,7 @@ public void cover_and_refresh_rejections_preserve_search_batch_progress(bool pos { var h = new Harness(database); h.Author.AddOptions = new AddAuthorOptions(); + h.AuthorService.SetAddOptions(h.Author); var first = h.AddBook(); var second = h.AddBook(work: "hc:7000", edition: "hc:edition:7001"); h.EditionService.InsertMany(new() { new() { BookId = first.Id, ForeignEditionId = "gr:44767458", Title = "Lovers", diff --git a/src/Chaptarr.Core.Test/Books/ProcessPendingImportsCommandHandlerFixture.cs b/src/Chaptarr.Core.Test/Books/ProcessPendingImportsCommandHandlerFixture.cs index 525819bfc..689403ddc 100644 --- a/src/Chaptarr.Core.Test/Books/ProcessPendingImportsCommandHandlerFixture.cs +++ b/src/Chaptarr.Core.Test/Books/ProcessPendingImportsCommandHandlerFixture.cs @@ -34,6 +34,7 @@ private sealed class StubPendingAuthorImportService : IPendingAuthorImportServic public List DeletedIds { get; } = new(); public List RetryReasons { get; } = new(); public bool DeleteIfUnchangedResult { get; set; } = true; + public Author SetupAuthorAtDelete { get; private set; } public PendingAuthorImport CurrentByProviderId { get; set; } public bool UpdateStatusResult { get; set; } = true; public long? StatusExpectedVersion { get; private set; } @@ -60,10 +61,17 @@ public Task EnqueueAsync(string providerId, MonitoringConfig config, string DueResponses.Enqueue(new List { request }); return Task.FromResult(request.Id); } - public PendingAuthorImport Get(int id) => GetAll().Find(item => item.Id == id); + public PendingAuthorImport Get(int id) => DeletedIds.Contains(id) ? null : + _processing.FirstOrDefault(item => item.Id == id) ?? QueuedRequests.Find(item => item.Id == id); public NzbDrone.Core.Datastore.PagingSpec GetPaged(NzbDrone.Core.Datastore.PagingSpec pagingSpec) => throw new NotImplementedException(); public List GetAll() => throw new NotImplementedException(); - public List GetDueForProcessing(int limit = 10) => DueResponses.Count > 0 ? DueResponses.Dequeue() : new List(); + private List _processing = new List(); + + public List GetDueForProcessing(int limit = 10) + { + _processing = DueResponses.Count > 0 ? DueResponses.Dequeue() : new List(); + return _processing; + } public PendingAuthorImport GetByProviderId(string providerId) => CurrentByProviderId; public bool UpdateStatus(PendingAuthorImport item, PendingImportStatus status, string error, long? expectedVersion = null) @@ -84,11 +92,13 @@ public void ScheduleRetry(PendingAuthorImport item, string error) public bool IsActiveRequest(int id, long version) => true; public bool SaveProgress(PendingAuthorImport item, PendingAuthorImport previous) => true; public void Cancel(int id) => throw new NotImplementedException(); + public void ReconcileSetupCancellation(Author author) => throw new NotSupportedException(); public bool CancelIfQueued(int id) => throw new NotImplementedException(); public void RetryNow(int id) => throw new NotImplementedException(); public void Delete(int id) => DeletedIds.Add(id); - public bool TryDeleteIfUnchanged(PendingAuthorImport item) + public bool TryDeleteIfUnchanged(PendingAuthorImport item, Author author = null) { + SetupAuthorAtDelete = author; if (DeleteIfUnchangedResult) { DeletedIds.Add(item.Id); @@ -754,6 +764,7 @@ public void should_not_delete_a_second_book_request_merged_while_the_first_was_p handler.Execute(new ProcessPendingImportsCommand()); + Assert.That(pendingImportService.SetupAuthorAtDelete, Is.SameAs(author)); Assert.That(pendingImportService.DeletedIds, Is.Empty); Assert.That(pendingImportService.CurrentByProviderId.EbookBooksToSearch, Does.Contain("gr:second")); Assert.That(commandQueue.Pushed.OfType().Single().BookIds, Is.EqualTo(new[] { 202 })); @@ -1235,9 +1246,10 @@ public void list_import_should_search_once_after_initial_monitoring_whether_scan var initialMonitoringApplied = false; var scan = new AuthorScannedHandler( InterfaceProxy.Proxy((method, args) => { initialMonitoringApplied = true; return null; }), - InterfaceProxy.Proxy((method, args) => null), queue, + InterfaceProxy.Proxy((method, args) => method.Name == nameof(IAuthorService.GetExistingAuthors) + ? new List { author } : null), queue, InterfaceProxy.Proxy((method, args) => null), - new RecordingEventAggregator(), LogManager.GetCurrentClassLogger(), Chaptarr.Core.Test.Common.InterfaceProxy.Proxy((_, _) => throw new NotSupportedException())); + new RecordingEventAggregator(), LogManager.GetCurrentClassLogger(), Chaptarr.Core.Test.Common.InterfaceProxy.Proxy((_, _) => throw new NotSupportedException()), global::Chaptarr.Core.Test.Common.FixturePendingAuthorImports.Empty()); void CompleteScan() => scan.Handle(new AuthorScanSkippedEvent(author, AuthorScanSkippedReason.NoFolderEvidence)); BuildHandler(pendingService, queue, new RecordingEventAggregator(), author: author, bookService: bookService, configCaptured: config => diff --git a/src/Chaptarr.Core.Test/Books/RefreshBookServiceMergeEditionSelectionFixture.Refresh.cs b/src/Chaptarr.Core.Test/Books/RefreshBookServiceMergeEditionSelectionFixture.Refresh.cs index 46e46ec9d..92921d003 100644 --- a/src/Chaptarr.Core.Test/Books/RefreshBookServiceMergeEditionSelectionFixture.Refresh.cs +++ b/src/Chaptarr.Core.Test/Books/RefreshBookServiceMergeEditionSelectionFixture.Refresh.cs @@ -148,8 +148,9 @@ public void contested_filed_row_adopts_its_edition_pocket_and_refresh_settles_in var author = authors.Get(library.Source.AuthorId); author.Overview = ""; author.Path = TestContext.CurrentContext.TestDirectory; - author.AddOptions = new AddAuthorOptions { AwaitingMetadata = true, AudiobookAwaitingMetadata = true }; authors.Update(author); + author.AddOptions = new AddAuthorOptions { AwaitingMetadata = true, AudiobookAwaitingMetadata = true }; + authors.SetFields(author, row => row.AddOptions); library.Source.GoodreadsWorkId = "gr:111"; library.Source.RemoteProviderIds = rotation ? new() { "gr:111" } : new() { "gr:111", "gr:222" }; library.Source.WantedNarratorId = 27; @@ -215,8 +216,9 @@ public void failed_refresh_publishes_committed_children_without_acknowledging_se author.Overview = ""; author.HardcoverAuthorId = "hc:123"; author.Path = TestContext.CurrentContext.TestDirectory; - author.AddOptions = new AddAuthorOptions { AwaitingMetadata = true, AudiobookAwaitingMetadata = true }; authors.Update(author); + author.AddOptions = new AddAuthorOptions { AwaitingMetadata = true, AudiobookAwaitingMetadata = true }; + authors.SetFields(author, row => row.AddOptions); library.Source.Editions = new() { library.SourceEdition }; if (!repairFailure) { diff --git a/src/Chaptarr.Core.Test/Common/FixturePendingAuthorImports.cs b/src/Chaptarr.Core.Test/Common/FixturePendingAuthorImports.cs new file mode 100644 index 000000000..4b53a0208 --- /dev/null +++ b/src/Chaptarr.Core.Test/Common/FixturePendingAuthorImports.cs @@ -0,0 +1,13 @@ +using System; +using NzbDrone.Core.Books.Services; + +namespace Chaptarr.Core.Test.Common +{ + internal static class FixturePendingAuthorImports + { + public static IPendingAuthorImportService Empty() => + InterfaceProxy.Proxy((method, _) => + method.Name == nameof(IPendingAuthorImportService.ReconcileSetupCancellation) + ? null : throw new NotSupportedException(method.Name)); + } +} diff --git a/src/Chaptarr.Core.Test/ImportLists/ImportListExistingAuthorRootsFixture.cs b/src/Chaptarr.Core.Test/ImportLists/ImportListExistingAuthorRootsFixture.cs index d56bf2211..b4fbfd665 100644 --- a/src/Chaptarr.Core.Test/ImportLists/ImportListExistingAuthorRootsFixture.cs +++ b/src/Chaptarr.Core.Test/ImportLists/ImportListExistingAuthorRootsFixture.cs @@ -318,7 +318,7 @@ public void actual_list_both_missing_sides_should_apply_each_requested_root(bool completeInitialScan = scannedAuthor => { new AuthorScannedHandler(new BookMonitoredService(authorService, books, logger), authorService, queue, - new BookAddedService(new CacheManager(), queue, books, logger), events, logger, books) + new BookAddedService(new CacheManager(), queue, books, logger), events, logger, books, pending) .Handle(new AuthorScanSkippedEvent(scannedAuthor, AuthorScanSkippedReason.NoFolderEvidence)); initialScanTargets.AddRange(bookRows.GetMissingBookSearchTargets(null, scannedAuthor.Id).Select(target => target.BookId)); }; @@ -350,7 +350,7 @@ public void actual_list_both_missing_sides_should_apply_each_requested_root(bool var heldAuthor = authorService.FindByProviderId("gr", author.GoodreadsAuthorId); Assert.That(bookRows.GetMissingBookSearchTargets(null, heldAuthor.Id), Is.Empty); new AuthorScannedHandler(new BookMonitoredService(authorService, books, logger), authorService, queue, - new BookAddedService(new CacheManager(), queue, books, logger), events, logger, books).Handle(new AuthorScannedEvent(heldAuthor)); + new BookAddedService(new CacheManager(), queue, books, logger), events, logger, books, pending).Handle(new AuthorScannedEvent(heldAuthor)); Assert.That(authors.Get(heldAuthor.Id).AddOptions, Is.Null); } Assert.That(commands.OfType(), Is.Empty); @@ -389,7 +389,7 @@ public void actual_list_both_missing_sides_should_apply_each_requested_root(bool Assert.That(savedAuthor.EbookRootFolderPath, Is.EqualTo(@"C:\Ebooks".AsOsAgnostic())); }); new AuthorScannedHandler(new BookMonitoredService(authorService, books, logger), authorService, queue, - new BookAddedService(new CacheManager(), queue, books, logger), events, logger, books).Handle(new AuthorScannedEvent(savedAuthor)); + new BookAddedService(new CacheManager(), queue, books, logger), events, logger, books, pending).Handle(new AuthorScannedEvent(savedAuthor)); Assert.That(commands.OfType().ToList(), Has.Count.EqualTo(newAuthor || consumeHeldSearchBeforeRetry ? 1 : 0)); if (newAuthor && !consumeHeldSearchBeforeRetry) { diff --git a/src/Chaptarr.Core.Test/ImportLists/ImportListMissingMediaSidePersistenceFixture.EbookPins.cs b/src/Chaptarr.Core.Test/ImportLists/ImportListMissingMediaSidePersistenceFixture.EbookPins.cs index 4abfda8e4..fa4353307 100644 --- a/src/Chaptarr.Core.Test/ImportLists/ImportListMissingMediaSidePersistenceFixture.EbookPins.cs +++ b/src/Chaptarr.Core.Test/ImportLists/ImportListMissingMediaSidePersistenceFixture.EbookPins.cs @@ -414,7 +414,7 @@ public void explicit_ebook_pin_preserves_conflicts_and_honors_profile_pruned_sou var owner = h.Authors.Get(local.AuthorId); var added = new BookAddedService(new CacheManager(), h.Queue, h.Books, h.Logger); var scanned = new AuthorScannedHandler(new BookMonitoredService(h.AuthorService, h.Books, h.Logger), - h.AuthorService, h.Queue, added, h.Events, h.Logger, h.Books); + h.AuthorService, h.Queue, added, h.Events, h.Logger, h.Books, h.Pending); for (var pass = 0; pass < 2; pass++) { added.Handle(new BookInfoRefreshedEvent(owner, new List(), new List { after }, new List())); diff --git a/src/Chaptarr.Core.Test/ImportLists/ImportListMissingMediaSidePersistenceFixture.LegacySetupMigration.cs b/src/Chaptarr.Core.Test/ImportLists/ImportListMissingMediaSidePersistenceFixture.LegacySetupMigration.cs index 52313b0f4..80cbd599e 100644 --- a/src/Chaptarr.Core.Test/ImportLists/ImportListMissingMediaSidePersistenceFixture.LegacySetupMigration.cs +++ b/src/Chaptarr.Core.Test/ImportLists/ImportListMissingMediaSidePersistenceFixture.LegacySetupMigration.cs @@ -82,7 +82,7 @@ public void legacy_initial_monitor_migration_should_preserve_listed_rows_and_com }); var added = new BookAddedService(new NzbDrone.Common.Cache.CacheManager(), stored.Queue, stored.Books, stored.Logger); var handler = new AuthorScannedHandler(new BookMonitoredService(stored.AuthorService, stored.Books, stored.Logger), - stored.AuthorService, stored.Queue, added, stored.Events, stored.Logger, stored.Books); + stored.AuthorService, stored.Queue, added, stored.Events, stored.Logger, stored.Books, stored.Pending); handler.Handle(new AuthorScannedEvent(author)); diff --git a/src/Chaptarr.Core.Test/ImportLists/ImportListMissingMediaSidePersistenceFixture.PauseRetries.cs b/src/Chaptarr.Core.Test/ImportLists/ImportListMissingMediaSidePersistenceFixture.PauseRetries.cs index f20eb4766..3422baf96 100644 --- a/src/Chaptarr.Core.Test/ImportLists/ImportListMissingMediaSidePersistenceFixture.PauseRetries.cs +++ b/src/Chaptarr.Core.Test/ImportLists/ImportListMissingMediaSidePersistenceFixture.PauseRetries.cs @@ -33,7 +33,7 @@ public void rejected_list_sync_search_followed_by_scan_must_not_bypass_author_pa stored.RejectBookSearches = false; new AuthorScannedHandler(new BookMonitoredService(stored.AuthorService, stored.Books, stored.Logger), stored.AuthorService, stored.Queue, new BookAddedService(new CacheManager(), stored.Queue, stored.Books, stored.Logger), - stored.Events, stored.Logger, stored.Books).Handle(new AuthorScannedEvent(stored.Authors.Get(stored.Author.Id))); + stored.Events, stored.Logger, stored.Books, stored.Pending).Handle(new AuthorScannedEvent(stored.Authors.Get(stored.Author.Id))); var searches = stored.Commands.OfType().ToList(); Assert.That(searches, Has.Count.EqualTo(1)); Assert.That(searches.Single().Trigger, Is.Not.EqualTo(CommandTrigger.Manual)); diff --git a/src/Chaptarr.Core.Test/ImportLists/ImportListMissingMediaSidePersistenceFixture.SpecificBookScan.cs b/src/Chaptarr.Core.Test/ImportLists/ImportListMissingMediaSidePersistenceFixture.SpecificBookScan.cs index 686a7c5e3..278854892 100644 --- a/src/Chaptarr.Core.Test/ImportLists/ImportListMissingMediaSidePersistenceFixture.SpecificBookScan.cs +++ b/src/Chaptarr.Core.Test/ImportLists/ImportListMissingMediaSidePersistenceFixture.SpecificBookScan.cs @@ -64,7 +64,7 @@ public void named_list_policy_should_not_monitor_the_opposite_media_side_from_st var selected = stored.Books.GetBooksByAuthor(author.Id).Single(book => book.MediaType == listedSide && book.GoodreadsWorkId == "gr:123"); var added = new BookAddedService(new NzbDrone.Common.Cache.CacheManager(), stored.Queue, stored.Books, stored.Logger); new AuthorScannedHandler(new BookMonitoredService(stored.AuthorService, stored.Books, stored.Logger), - stored.AuthorService, stored.Queue, added, stored.Events, stored.Logger, stored.Books) + stored.AuthorService, stored.Queue, added, stored.Events, stored.Logger, stored.Books, stored.Pending) .Handle(new AuthorScannedEvent(author)); var saved = stored.Books.GetBooksByAuthor(author.Id); @@ -110,7 +110,7 @@ public void specific_book_list_add_should_preserve_only_listed_monitoring_after_ }); var added = new BookAddedService(new NzbDrone.Common.Cache.CacheManager(), stored.Queue, stored.Books, stored.Logger); var handler = new AuthorScannedHandler(new BookMonitoredService(stored.AuthorService, stored.Books, stored.Logger), - stored.AuthorService, stored.Queue, added, stored.Events, stored.Logger, stored.Books); + stored.AuthorService, stored.Queue, added, stored.Events, stored.Logger, stored.Books, stored.Pending); handler.Handle(new AuthorScannedEvent(author)); @@ -161,7 +161,7 @@ public void specific_book_list_search_should_complete_without_a_post_scan_monito }); var added = new BookAddedService(new NzbDrone.Common.Cache.CacheManager(), stored.Queue, stored.Books, stored.Logger); var handler = new AuthorScannedHandler(monitoring, stored.AuthorService, stored.Queue, added, - stored.Events, stored.Logger, stored.Books); + stored.Events, stored.Logger, stored.Books, stored.Pending); stored.Calls.Clear(); handler.Handle(new AuthorScannedEvent(author)); diff --git a/src/Chaptarr.Core.Test/ImportLists/ImportListMissingMediaSidePersistenceFixture.cs b/src/Chaptarr.Core.Test/ImportLists/ImportListMissingMediaSidePersistenceFixture.cs index 81de66140..a52993f61 100644 --- a/src/Chaptarr.Core.Test/ImportLists/ImportListMissingMediaSidePersistenceFixture.cs +++ b/src/Chaptarr.Core.Test/ImportLists/ImportListMissingMediaSidePersistenceFixture.cs @@ -239,7 +239,7 @@ public void list_missing_side_intent_should_survive_pending_storage_and_actual_a bookAdded.Handle(new BookInfoRefreshedEvent(savedAuthor, savedBooks.Where(book => book.Id != unchanged.Id).ToList(), new List { unchanged }, new List())); var scanHandler = new AuthorScannedHandler(new BookMonitoredService(authorService, books, logger), - authorService, queue, bookAdded, events, logger, books); + authorService, queue, bookAdded, events, logger, books, pending); scanHandler.Handle(new AuthorScannedEvent(savedAuthor)); var afterScan = books.GetBooksByAuthor(author.Id); Assert.That(afterScan.Single(book => book.Id == selected.Id).IsMonitored(), Is.True); @@ -486,7 +486,7 @@ void Drain(IPendingAuthorImportService persistedPending) Assert.That(BookEditionIdentity.GetMonitoredEdition(fulfilled)?.Id, Is.EqualTo(fulfilledPin)); Assert.That(attemptedSearches, Is.Empty, "The wanted writer must suppress searches for an already fulfilled narration."); new AuthorScannedHandler(new BookMonitoredService(authorService, books, logger), authorService, queue, - new BookAddedService(new CacheManager(), queue, books, logger), events, logger, books).Handle(new AuthorScannedEvent(authors.Get(author.Id))); + new BookAddedService(new CacheManager(), queue, books, logger), events, logger, books, pending).Handle(new AuthorScannedEvent(authors.Get(author.Id))); Assert.That(commands.OfType(), Is.Empty); Assert.That(commands.OfType(), Is.Empty); return; @@ -517,7 +517,7 @@ void Drain(IPendingAuthorImportService persistedPending) if (scanBeforeRetry) { new AuthorScannedHandler(new BookMonitoredService(authorService, books, logger), authorService, queue, - new BookAddedService(new CacheManager(), queue, books, logger), events, logger, books) + new BookAddedService(new CacheManager(), queue, books, logger), events, logger, books, pending) .Handle(new AuthorScannedEvent(authors.Get(author.Id))); Assert.That(commands.OfType().Count(), Is.EqualTo(2)); Assert.That(commands.OfType().All(search => search.Trigger != CommandTrigger.Manual), Is.True); @@ -536,7 +536,7 @@ void Drain(IPendingAuthorImportService persistedPending) var persistedAuthor = authors.Get(author.Id); Assert.That(side == BookMediaType.Audiobook ? persistedAuthor.AudiobookMonitored : persistedAuthor.EbookMonitored, Is.False); var bookAdded = new BookAddedService(new CacheManager(), queue, books, logger); - new AuthorScannedHandler(new BookMonitoredService(authorService, books, logger), authorService, queue, bookAdded, events, logger, books) + new AuthorScannedHandler(new BookMonitoredService(authorService, books, logger), authorService, queue, bookAdded, events, logger, books, restartedPending) .Handle(new AuthorScannedEvent(persistedAuthor)); Assert.Multiple(() => { @@ -1061,7 +1061,7 @@ public void missing_format_without_book_targets_should_use_existing_queue_and_in Quality = new NzbDrone.Core.Qualities.QualityModel(), MediaInfo = new NzbDrone.Core.Parser.Model.MediaInfoModel() }); var scanned = new AuthorScannedHandler(new BookMonitoredService(stored.AuthorService, stored.Books, stored.Logger), - stored.AuthorService, stored.Queue, Proxy((method, args) => null), stored.Events, stored.Logger, stored.Books); + stored.AuthorService, stored.Queue, Proxy((method, args) => null), stored.Events, stored.Logger, stored.Books, stored.Pending); scanned.Handle(new AuthorScannedEvent(author)); Assert.Multiple(() => { @@ -1145,6 +1145,7 @@ public void initial_monitoring_intent_should_survive_persistence_and_initial_sca Assert.That(side == BookMediaType.Audiobook ? config.AudiobookMonitorExistingMode : config.EbookMonitorExistingMode, Is.EqualTo(initialMode)); typeof(AuthorLibraryService).GetMethod("ApplyMonitoringConfig", flags).Invoke(library, new object[] { stored.Author, config }); stored.Authors.Update(stored.Author); + stored.AuthorService.SetAddOptions(stored.Author); var requested = CatalogBook(side, "Requested Work", "123"); requested.SetMonitored(true); requested.AddOptions = new AddBookOptions { AddType = BookAddType.Manual }; @@ -1159,7 +1160,7 @@ public void initial_monitoring_intent_should_survive_persistence_and_initial_sca stored.Save(opposite); var bookAdded = Proxy((method, args) => null); var handler = new AuthorScannedHandler(new BookMonitoredService(stored.AuthorService, stored.Books, stored.Logger), - stored.AuthorService, stored.Queue, bookAdded, stored.Events, stored.Logger, stored.Books); + stored.AuthorService, stored.Queue, bookAdded, stored.Events, stored.Logger, stored.Books, stored.Pending); handler.Handle(new AuthorScannedEvent(stored.Authors.Get(stored.Author.Id))); var expectedOther = initialMode == MonitorTypes.All || initialMode != MonitorTypes.None && monitoredBeforeScan; Assert.Multiple(() => diff --git a/src/Chaptarr.Core.Test/ImportLists/ImportListSyncServiceSearchOnAddFixture.cs b/src/Chaptarr.Core.Test/ImportLists/ImportListSyncServiceSearchOnAddFixture.cs index d02c60574..6e3eff4c0 100644 --- a/src/Chaptarr.Core.Test/ImportLists/ImportListSyncServiceSearchOnAddFixture.cs +++ b/src/Chaptarr.Core.Test/ImportLists/ImportListSyncServiceSearchOnAddFixture.cs @@ -143,6 +143,8 @@ public Task EnqueueAsync(string providerId, MonitoringConfig config, string public bool SaveProgress(PendingAuthorImport item, PendingAuthorImport previous) => throw new NotImplementedException(); public void ScheduleRetry(PendingAuthorImport item, string error) => throw new NotImplementedException(); public bool IsActiveRequest(int id, long version) => true; + public void ReconcileSetupCancellation(Author author) => throw new NotSupportedException(); + public void Cancel(int id) => throw new NotImplementedException(); public bool CancelIfQueued(int id) => throw new NotImplementedException(); public void RetryNow(int id) => throw new NotImplementedException(); diff --git a/src/Chaptarr.Core.Test/MediaFiles/ImportApprovedBooksAdditionalCopyFixture.ManualSelection.cs b/src/Chaptarr.Core.Test/MediaFiles/ImportApprovedBooksAdditionalCopyFixture.ManualSelection.cs index 84568d9cc..2f62142b9 100644 --- a/src/Chaptarr.Core.Test/MediaFiles/ImportApprovedBooksAdditionalCopyFixture.ManualSelection.cs +++ b/src/Chaptarr.Core.Test/MediaFiles/ImportApprovedBooksAdditionalCopyFixture.ManualSelection.cs @@ -29,6 +29,7 @@ using NzbDrone.Core.Messaging.Commands; using NzbDrone.Core.Messaging.Events; using NzbDrone.Core.Parser.Model; +using NzbDrone.Core.Profiles.Qualities; using NzbDrone.Core.Qualities; using NzbDrone.Core.RootFolders; @@ -119,10 +120,19 @@ public void manual_selection_must_honor_target_combine_replace_and_successful_pi author.SortName = "testwriter"; author.TitleSlug = "test-writer"; author.Added = DateTime.UtcNow; - new AuthorRepository(database, events, logger).Insert(author); - author.EbookQualityProfile = profile; - author.EbookQualityProfileId = profile.Id; + profile.Id = 0; profile.UpgradeAllowed = false; + if (mediaType == BookMediaType.Ebook) + { + profile.ProfileType = ProfileType.Ebook; + profile.ConvertToQualityId = null; + profile.Items = new List { new() { Allowed = true, Quality = Quality.EPUB } }; + } + new QualityProfileRepository(database, events, null).Insert(profile); + author.AudiobookQualityProfileId = mediaType == BookMediaType.Audiobook ? profile.Id : null; + author.EbookQualityProfile = mediaType == BookMediaType.Ebook ? profile : null; + author.EbookQualityProfileId = mediaType == BookMediaType.Ebook ? profile.Id : null; + new AuthorRepository(database, events, logger).Insert(author); var persistenceFailure = scenario.EndsWith("persistence-failure", StringComparison.Ordinal); var failing = persistenceFailure || scenario is "transfer-failure" or "combine-collision" or "database-conflict"; var selectionFailure = scenario.EndsWith("save-failure", StringComparison.Ordinal); diff --git a/src/Chaptarr.Core.Test/MediaFiles/ImportApprovedBooksAdditionalCopyFixture.ProviderSelection.cs b/src/Chaptarr.Core.Test/MediaFiles/ImportApprovedBooksAdditionalCopyFixture.ProviderSelection.cs index 8fd492c6b..1f4705920 100644 --- a/src/Chaptarr.Core.Test/MediaFiles/ImportApprovedBooksAdditionalCopyFixture.ProviderSelection.cs +++ b/src/Chaptarr.Core.Test/MediaFiles/ImportApprovedBooksAdditionalCopyFixture.ProviderSelection.cs @@ -24,6 +24,7 @@ using NzbDrone.Core.Messaging.Events; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Profiles.Metadata; +using NzbDrone.Core.Profiles.Qualities; using NzbDrone.Core.Qualities; using NzbDrone.Core.RootFolders; @@ -79,15 +80,30 @@ T Optional() where T : class => InterfaceProxy.Proxy((method, _) => author.AudiobookRootFolderPath = author.EbookRootFolderPath = libraryPath; author.AudiobookMetadataProfileId = author.EbookMetadataProfileId = profile.Id; author.AudiobookMetadataProfile = author.EbookMetadataProfile = profile; + qualityProfile.Id = 0; + if (mediaType == BookMediaType.Ebook) + { + qualityProfile.ProfileType = ProfileType.Ebook; + qualityProfile.ConvertToQualityId = null; + qualityProfile.Items = new List { new() { Allowed = true, Quality = Quality.EPUB } }; + } + new QualityProfileRepository(database, events, null).Insert(qualityProfile); + author.AudiobookQualityProfileId = qualityProfile.Id; author.EbookQualityProfileId = qualityProfile.Id; author.EbookQualityProfile = qualityProfile; var authors = new AuthorRepository(database, events, logger); authors.Insert(author); + object SaveSetup(Author authorWithSetup) + { + authors.SetFields(authorWithSetup, saved => saved.AddOptions); + return null; + } var authorService = InterfaceProxy.Proxy((method, args) => method.Name switch { nameof(IAuthorService.FindByProviderId) or nameof(IAuthorService.GetAuthor) => author, nameof(IAuthorService.GetExistingAuthors) or nameof(IAuthorService.GetAuthors) or nameof(IAuthorService.GetAllAuthors) => new List { author }, nameof(IAuthorService.UpdateAuthor) => authors.Update((Author)args[0]), + nameof(IAuthorService.SetAddOptions) => SaveSetup((Author)args[0]), _ => throw new AssertionException(method.Name) }); var rootFolder = new RootFolder { Id = 1, Path = libraryPath, FolderType = FolderType.Mixed }; diff --git a/src/Chaptarr.Core.Test/MediaFiles/ImportApprovedBooksAdditionalCopyFixture.SameGrab.cs b/src/Chaptarr.Core.Test/MediaFiles/ImportApprovedBooksAdditionalCopyFixture.SameGrab.cs index 28cf0dc7d..50c6ecf1e 100644 --- a/src/Chaptarr.Core.Test/MediaFiles/ImportApprovedBooksAdditionalCopyFixture.SameGrab.cs +++ b/src/Chaptarr.Core.Test/MediaFiles/ImportApprovedBooksAdditionalCopyFixture.SameGrab.cs @@ -24,6 +24,7 @@ using NzbDrone.Core.Messaging.Commands; using NzbDrone.Core.Messaging.Events; using NzbDrone.Core.Parser.Model; +using NzbDrone.Core.Profiles.Qualities; using NzbDrone.Core.Qualities; using NzbDrone.Core.RootFolders; @@ -119,9 +120,12 @@ public void manual_import_must_honor_combine_and_confirmed_replace_for_three_par author.SortName = "testwriter"; author.TitleSlug = "test-writer"; author.Added = DateTime.UtcNow; - new AuthorRepository(database, events, logger).Insert(author); + profile.Id = 0; profile.UpgradeAllowed = false; profile.ConvertToQualityId = null; + new QualityProfileRepository(database, events, null).Insert(profile); + author.AudiobookQualityProfileId = profile.Id; + new AuthorRepository(database, events, logger).Insert(author); book.Id = 0; book.AuthorId = author.Id; book.CleanTitle = "blacksheep"; diff --git a/src/Chaptarr.Core.Test/MediaFiles/RetryUnmappedMatchCommandHandlerFixture.cs b/src/Chaptarr.Core.Test/MediaFiles/RetryUnmappedMatchCommandHandlerFixture.cs index 897f88b2a..acb01385b 100644 --- a/src/Chaptarr.Core.Test/MediaFiles/RetryUnmappedMatchCommandHandlerFixture.cs +++ b/src/Chaptarr.Core.Test/MediaFiles/RetryUnmappedMatchCommandHandlerFixture.cs @@ -199,6 +199,8 @@ public Task EnqueueAsync(string providerId, MonitoringConfig config, string public bool SaveProgress(PendingAuthorImport item, PendingAuthorImport previous) => throw new NotImplementedException(); public void ScheduleRetry(PendingAuthorImport item, string error) => throw new NotImplementedException(); public bool IsActiveRequest(int id, long version) => true; + public void ReconcileSetupCancellation(Author author) => throw new NotSupportedException(); + public void Cancel(int id) => throw new NotImplementedException(); public bool CancelIfQueued(int id) => throw new NotImplementedException(); public void RetryNow(int id) => throw new NotImplementedException(); diff --git a/src/Chaptarr.Core.Test/Parser/ParsingServiceMapFixture.cs b/src/Chaptarr.Core.Test/Parser/ParsingServiceMapFixture.cs index 91709e5b5..14d51a156 100644 --- a/src/Chaptarr.Core.Test/Parser/ParsingServiceMapFixture.cs +++ b/src/Chaptarr.Core.Test/Parser/ParsingServiceMapFixture.cs @@ -231,7 +231,7 @@ public void whole_inverted_author_must_not_be_replaced_by_a_mononym_fragment() Assert.That(remote.Books, Has.Count.EqualTo(1)); Assert.That(harness.Calls, Is.EqualTo(new[] { (nameof(IAuthorService.FindByName), "Smith, John") })); Assert.That(harness.CatalogReads(), Is.EqualTo(1)); - Assert.That(harness.AuthorReads(), Is.Zero); + Assert.That(harness.AuthorReads(), Is.EqualTo(1)); }); } @@ -272,7 +272,7 @@ public void contributor_fields_must_reach_the_service_once_without_fragment_look Assert.That(remote.Books, Has.Count.EqualTo(1)); Assert.That(harness.Calls, Is.EqualTo(new[] { (nameof(IAuthorService.FindByName), field) })); Assert.That(harness.CatalogReads(), Is.EqualTo(1)); - Assert.That(harness.AuthorReads(), Is.Zero); + Assert.That(harness.AuthorReads(), Is.EqualTo(1)); }); } @@ -301,7 +301,7 @@ public void whole_author_credit_must_use_one_canonical_lookup() Assert.That(remote.Author, Is.SameAs(author)); Assert.That(harness.Calls, Is.EqualTo(new[] { (nameof(IAuthorService.FindByName), "Alex Reed") })); Assert.That(harness.CatalogReads(), Is.EqualTo(1)); - Assert.That(harness.AuthorReads(), Is.Zero); + Assert.That(harness.AuthorReads(), Is.EqualTo(1)); } private static (ParsingService Parser, List<(string Method, string Value)> Calls, Func CatalogReads, Func AuthorReads) @@ -318,12 +318,9 @@ private static (ParsingService Parser, List<(string Method, string Value)> Calls case nameof(IAuthorRepository.All): catalogReads++; return authors; - case "FindByName": - var exact = authors.Where(author => author.Name.CleanAuthorName() == (string)args[0]).ToList(); - return exact.Count == 1 ? exact[0] : null; - case nameof(IAuthorRepository.Get): + case nameof(IAuthorRepository.Find): authorReads++; - return authors.Single(author => author.Id == (int)args[0]); + return authors.SingleOrDefault(author => author.Id == (int)args[0]); default: throw new NotSupportedException(method.Name); } diff --git a/src/Chaptarr.Core.Test/PendingImport/PendingAuthorImportControllerFixture.cs b/src/Chaptarr.Core.Test/PendingImport/PendingAuthorImportControllerFixture.cs index 080454158..181205c9c 100644 --- a/src/Chaptarr.Core.Test/PendingImport/PendingAuthorImportControllerFixture.cs +++ b/src/Chaptarr.Core.Test/PendingImport/PendingAuthorImportControllerFixture.cs @@ -110,6 +110,8 @@ public Task EnqueueAsync(string providerId, MonitoringConfig config, string public bool SaveProgress(PendingAuthorImport item, PendingAuthorImport previous) => throw new NotImplementedException(); public void ScheduleRetry(PendingAuthorImport item, string error) => throw new NotImplementedException(); public bool IsActiveRequest(int id, long version) => true; + public void ReconcileSetupCancellation(Author author) => throw new NotSupportedException(); + public void Cancel(int id) => throw new NotImplementedException(); public bool CancelIfQueued(int id) => throw new NotImplementedException(); public void RetryNow(int id) => throw new NotImplementedException(); diff --git a/src/NzbDrone.Core/Books/Commands/ProcessPendingImportsCommandHandler.cs b/src/NzbDrone.Core/Books/Commands/ProcessPendingImportsCommandHandler.cs index 050409d8c..1565de767 100644 --- a/src/NzbDrone.Core/Books/Commands/ProcessPendingImportsCommandHandler.cs +++ b/src/NzbDrone.Core/Books/Commands/ProcessPendingImportsCommandHandler.cs @@ -526,7 +526,7 @@ void SaveProgress() _logger.Info("Successfully fulfilled pending import {0} (author ID: {1})", item.ProviderId, addedAuthor?.Id); MarkSucceeded(item); - if (!_pendingImportService.TryDeleteIfUnchanged(item)) + if (!_pendingImportService.TryDeleteIfUnchanged(item, addedAuthor)) { // Another request was merged while this worker was running. Leave the row // active so the newly added target is processed rather than deleted as stale. diff --git a/src/NzbDrone.Core/Books/Handlers/AuthorScannedHandler.cs b/src/NzbDrone.Core/Books/Handlers/AuthorScannedHandler.cs index bd69e2a9d..6ab5eea33 100644 --- a/src/NzbDrone.Core/Books/Handlers/AuthorScannedHandler.cs +++ b/src/NzbDrone.Core/Books/Handlers/AuthorScannedHandler.cs @@ -1,7 +1,11 @@ +using System; using System.Collections.Generic; +using System.Linq; using NLog; +using NzbDrone.Common; using NzbDrone.Core.Books.Commands; using NzbDrone.Core.Books.Events; +using NzbDrone.Core.Books.Services; using NzbDrone.Core.IndexerSearch; using NzbDrone.Core.MediaFiles; using NzbDrone.Core.MediaFiles.Events; @@ -17,6 +21,7 @@ public class AuthorScannedHandler : IHandle, private readonly IBookMonitoredService _bookMonitoredService; private readonly IBookService _bookService; private readonly IAuthorService _authorService; + private readonly IPendingAuthorImportService _pendingImports; private readonly IManageCommandQueue _commandQueueManager; private readonly IBookAddedService _bookAddedService; private readonly IEventAggregator _eventAggregator; @@ -28,78 +33,97 @@ public AuthorScannedHandler(IBookMonitoredService bookMonitoredService, IBookAddedService bookAddedService, IEventAggregator eventAggregator, Logger logger, - IBookService bookService) + IBookService bookService, + IPendingAuthorImportService pendingImports) { _bookMonitoredService = bookMonitoredService; _bookService = bookService ?? throw new System.ArgumentNullException(nameof(bookService)); _authorService = authorService; + _pendingImports = pendingImports ?? throw new ArgumentNullException(nameof(pendingImports)); _commandQueueManager = commandQueueManager; _bookAddedService = bookAddedService; _eventAggregator = eventAggregator; _logger = logger; } - private void HandleScanEvents(Author author, bool canCompleteInitialSetup = true) + private enum SetupSource { - _logger.Debug("[FLOW-DEBUG] Processing author '{0}' (ID: {1})", author.Name, author.Id); + FolderScan, + SkippedScan, + Retry + } - if (author.AddOptions != null && !canCompleteInitialSetup) - { - _logger.Info("Retaining initial monitoring and search for author {0} ({1}); this scan did not cover its pending setup folders.", author.Name, author.Id); - return; - } + private enum ScanCompletion + { + Deferred, + Notify, + SearchAndNotify + } - if (author.AddOptions?.AwaitingMetadata == true) + private ScanCompletion CompleteInitialSetup(Author author) + { + if (author.AddOptions.AwaitingMetadata) { _logger.Info("Retaining initial monitoring and search for author {0} ({1}); the requested catalog has not loaded yet.", author.Name, author.Id); + return ScanCompletion.SearchAndNotify; } - else if (author.AddOptions != null) + + if (author.AddOptions.InitialFormatSyncNotBefore > DateTime.UtcNow) { - if (author.AddOptions.InitialFormatSyncNotBefore > System.DateTime.UtcNow) - { - _logger.Debug("Initial format-sync retry for author {0} is not due until {1:O}", author.Id, author.AddOptions.InitialFormatSyncNotBefore); - _eventAggregator.PublishEvent(new AuthorScanCompletedEvent(author)); - return; - } - var hasMediaSpecificMode = author.AddOptions.AudiobookMonitor.HasValue || author.AddOptions.EbookMonitor.HasValue; - if (author.AddOptions.AudiobookMonitor.HasValue) ApplyInitialMonitoring(author, BookMediaType.Audiobook); - if (author.AddOptions.EbookMonitor.HasValue) ApplyInitialMonitoring(author, BookMediaType.Ebook); - if (!hasMediaSpecificMode && author.AddOptions.Monitor.HasValue) ApplyInitialMonitoring(author); + _logger.Debug("Initial format-sync retry for author {0} is not due until {1:O}", author.Id, author.AddOptions.InitialFormatSyncNotBefore); + return ScanCompletion.Notify; + } - if (author.SyncMonitoredAcrossFormats == true) - { - // Reconcile after both initial media-side defaults have been applied. - _bookService.SyncMonitoredAcrossFormats(new List { author.Id }); - } + var hasMediaSpecificMode = author.AddOptions.AudiobookMonitor.HasValue || author.AddOptions.EbookMonitor.HasValue; + if (author.AddOptions.AudiobookMonitor.HasValue) ApplyInitialMonitoring(author, BookMediaType.Audiobook); + if (author.AddOptions.EbookMonitor.HasValue) ApplyInitialMonitoring(author, BookMediaType.Ebook); + if (!hasMediaSpecificMode && author.AddOptions.Monitor.HasValue) ApplyInitialMonitoring(author); - if (author.AddOptions.SearchForMissingBooks) - { - var options = author.AddOptions; - var searchSide = !options.IndependentSearchForMissingBooks && - options.AudiobookSetupSearchForMissingBooks != options.EbookSetupSearchForMissingBooks - ? options.AudiobookSetupSearchForMissingBooks ? "audiobook" : "ebook" - : null; - if (_commandQueueManager.Push(new MissingBookSearchCommand(author.Id) { MediaType = searchSide }) == null) - { - throw new System.InvalidOperationException("Initial search command admission was rejected"); - } - } + if (author.SyncMonitoredAcrossFormats == true) + { + // Reconcile after both initial media-side defaults have been applied. + _bookService.SyncMonitoredAcrossFormats(new List { author.Id }); + } - var completedOptions = author.AddOptions; - author.AddOptions = null; - try - { - _authorService.SetAddOptions(author); - } - catch + if (author.AddOptions.SearchForMissingBooks) + { + var options = author.AddOptions; + var searchSide = !options.IndependentSearchForMissingBooks && + options.AudiobookSetupSearchForMissingBooks != options.EbookSetupSearchForMissingBooks + ? options.AudiobookSetupSearchForMissingBooks ? "audiobook" : "ebook" + : null; + if (_commandQueueManager.Push(new MissingBookSearchCommand(author.Id) { MediaType = searchSide }) == null) { - author.AddOptions = completedOptions; - throw; + throw new InvalidOperationException("Initial search command admission was rejected"); } } - _bookAddedService.SearchForRecentlyAdded(author.Id); - _eventAggregator.PublishEvent(new AuthorScanCompletedEvent(author)); + var completedOptions = author.AddOptions; + author.AddOptions = null; + try + { + _authorService.SetAddOptions(author); + } + catch + { + author.AddOptions = completedOptions; + throw; + } + + return ScanCompletion.SearchAndNotify; + } + + private static bool ScanStillCoversSetup(Author scanned, Author current, SetupSource source) + { + var scannedMediaType = scanned.AddOptions.GetInitialScanMediaType(); + var currentMediaType = current.AddOptions.GetInitialScanMediaType(); + var scannedPaths = scanned.GetScanPaths(scannedMediaType).ToHashSet(PathEqualityComparer.Instance); + var currentPaths = current.GetScanPaths(currentMediaType); + // A skipped scan did not see any folders. Its absence check is scoped to that format. + if (source == SetupSource.SkippedScan) + return scannedMediaType == currentMediaType && scannedPaths.SetEquals(currentPaths); + + return (scannedMediaType == "all" || scannedMediaType == currentMediaType) && scannedPaths.IsSupersetOf(currentPaths); } private void ApplyInitialMonitoring(Author author, BookMediaType? mediaType = null) @@ -160,25 +184,118 @@ public void Execute(BulkSyncFormatMonitoringCommand message) return; } - foreach (var author in _authorService.GetAuthors(message.AuthorIds)) + foreach (var author in _authorService.GetExistingAuthors(message.AuthorIds)) { if (author.AddOptions == null) continue; - HandleScanWithRetry(author); + HandleScanWithRetry(author, source: SetupSource.Retry); } } - private void HandleScanWithRetry(Author author, bool canCompleteInitialSetup = true) + private Author ReadSetupAuthor(int id) => _authorService.GetExistingAuthors(new[] { id }).SingleOrDefault(); + + private static bool CanScheduleSetupRetry(AddAuthorOptions options) => + options is { AwaitingMetadata: false, MetadataUnavailable: false } && + !(options.InitialFormatSyncNotBefore > DateTime.UtcNow); + + private static bool IsDueSetupRetry(AddAuthorOptions options) => + options.InitialFormatSyncNotBefore.HasValue && CanScheduleSetupRetry(options); + + private ScanCompletion CompleteSavedSetup(Author scanned, bool canCompleteInitialSetup, SetupSource source, out Author author) { + author = scanned; + using var writer = BookService.EnterWantedEditionLock(scanned, _logger); + try + { + author = ReadSetupAuthor(scanned.Id); + } + catch (Exception ex) when (canCompleteInitialSetup && ex is not OperationCanceledException) + { + // A failed reload supplies no current settings. Try the read once more + // while the evidence is still available, before any setup writes. + _logger.Debug(ex, "Could not reload author {0} after scan; retrying the read", scanned.Id); + author = ReadSetupAuthor(scanned.Id); + } + + if (author == null) return ScanCompletion.Deferred; + if (author.AddOptions == null) + return source == SetupSource.Retry ? ScanCompletion.Deferred : ScanCompletion.SearchAndNotify; + + if (source == SetupSource.Retry && !IsDueSetupRetry(author.AddOptions)) + return ScanCompletion.Deferred; + try { - HandleScanEvents(author, canCompleteInitialSetup); + _pendingImports.ReconcileSetupCancellation(author); } - catch (System.Exception ex) when (ex is not System.OperationCanceledException) + catch (Exception ex) when (canCompleteInitialSetup && ex is not OperationCanceledException) { - if (author.AddOptions != null) RecordSetupFailure(author, ex); - else _logger.Warn(ex, "Author {0} setup completed but its completion handling failed", author.Id); - _eventAggregator.PublishEvent(new AuthorScanCompletedEvent(author)); + // A withdrawal save may have committed even if the caller saw an error. + // Never rewrite its old options when recording a retry. + author = ReadSetupAuthor(scanned.Id); + if (author == null) return ScanCompletion.Deferred; + if (author.AddOptions == null) + return source == SetupSource.Retry ? ScanCompletion.Deferred : ScanCompletion.SearchAndNotify; + if (!ScanStillCoversSetup(scanned, author, source)) throw; + + if (source == SetupSource.SkippedScan) + { + // No-folder evidence is valid only for its exact scope. Reconcile + // once more here so a changed scope can still invalidate that evidence. + _logger.Debug(ex, "Could not reconcile cancelled setup for author {0} after a skipped scan; retrying once", author.Id); + _pendingImports.ReconcileSetupCancellation(author); + } + else + { + var canRetry = source == SetupSource.Retry + ? IsDueSetupRetry(author.AddOptions) : CanScheduleSetupRetry(author.AddOptions); + if (!canRetry) throw; + RecordSetupFailure(author, ex); + return ScanCompletion.Notify; + } } + + if (author.AddOptions == null) + return source == SetupSource.Retry ? ScanCompletion.Deferred : ScanCompletion.SearchAndNotify; + + if (source == SetupSource.Retry && !IsDueSetupRetry(author.AddOptions)) + return ScanCompletion.Deferred; + + if (!canCompleteInitialSetup || !ScanStillCoversSetup(scanned, author, source)) + { + var setupFolders = author.GetScanPaths(author.AddOptions.GetInitialScanMediaType()); + _logger.Info("Initial monitoring and search for {0} ({1}) stay pending until a scan covers {2}. Use Rescan now on the author page or wait for the daily refresh.", + author.Name, author.Id, setupFolders.Count == 0 ? "the configured author folders" : string.Join(", ", setupFolders)); + return ScanCompletion.Deferred; + } + + try + { + return CompleteInitialSetup(author); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + RecordSetupFailure(author, ex); + return ScanCompletion.Notify; + } + } + + private void HandleScanWithRetry(Author author, bool canCompleteInitialSetup = true, SetupSource source = SetupSource.FolderScan) + { + var authorId = author.Id; + try + { + var completion = author.AddOptions == null ? ScanCompletion.SearchAndNotify + : CompleteSavedSetup(author, canCompleteInitialSetup, source, out author); + if (completion == ScanCompletion.Deferred) return; + if (completion == ScanCompletion.SearchAndNotify) + _bookAddedService.SearchForRecentlyAdded(authorId); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + _logger.Warn(ex, "Could not complete scan handling for author {0}", authorId); + } + + _eventAggregator.PublishEvent(new AuthorScanCompletedEvent(author)); } public void Handle(AuthorScannedEvent message) @@ -188,7 +305,7 @@ public void Handle(AuthorScannedEvent message) public void Handle(AuthorScanSkippedEvent message) { - HandleScanWithRetry(message.Author); + HandleScanWithRetry(message.Author, source: SetupSource.SkippedScan); } } } diff --git a/src/NzbDrone.Core/Books/Model/AddAuthorOptions.cs b/src/NzbDrone.Core/Books/Model/AddAuthorOptions.cs index 940c179ad..1d8ad83c9 100644 --- a/src/NzbDrone.Core/Books/Model/AddAuthorOptions.cs +++ b/src/NzbDrone.Core/Books/Model/AddAuthorOptions.cs @@ -10,14 +10,25 @@ public class AddAuthorOptions : MonitoringOptions public bool SearchForMissingBooks { get; set; } [System.ComponentModel.ReadOnly(true)] public bool AwaitingMetadata { get; set; } + internal AddAuthorOptions ShallowClone() => (AddAuthorOptions)MemberwiseClone(); + public AddAuthorOptions WithoutRetryState() { - var copy = (AddAuthorOptions)MemberwiseClone(); + var copy = ShallowClone(); copy.InitialFormatSyncFailureCount = 0; copy.InitialFormatSyncNotBefore = null; return copy; } + public void ResetRetryForNewScanScope(string previousMediaType, bool needsNewMediaFolder) + { + if (!needsNewMediaFolder && (previousMediaType == "all" || previousMediaType == GetInitialScanMediaType())) + return; + + InitialFormatSyncFailureCount = 0; + InitialFormatSyncNotBefore = null; + } + [System.ComponentModel.ReadOnly(true)] public int InitialFormatSyncFailureCount { get; set; } [System.ComponentModel.ReadOnly(true)] @@ -49,7 +60,7 @@ public string GetInitialScanMediaType() { var audiobook = AudiobookSetupPending || AudiobookMonitor.HasValue || AudiobookSetupSearchForMissingBooks; var ebook = EbookSetupPending || EbookMonitor.HasValue || EbookSetupSearchForMissingBooks; - if (IndependentSearchForMissingBooks || audiobook && ebook) return "all"; + if (IndependentSearchForMissingBooks || HasLegacyIndependentSearch() || audiobook && ebook) return "all"; if (audiobook) return "audiobook"; if (ebook) return "ebook"; return MediaType?.ToString().ToLowerInvariant() ?? "all"; @@ -76,9 +87,35 @@ public void CancelInitialSearch(bool audiobookSetup, bool ebookSetup) UpdateInitialSearch(); } + internal bool RemoveCancelledSetup(bool audiobook, bool ebook) + { + CancelInitialSearch(audiobook, ebook); + if (audiobook) + { + AudiobookMonitor = null; + AudiobookSetupPending = false; + AudiobookAwaitingMetadata = false; + AudiobookSetupPendingImportId = null; + } + + if (ebook) + { + EbookMonitor = null; + EbookSetupPending = false; + EbookAwaitingMetadata = false; + EbookSetupPendingImportId = null; + } + + AwaitingMetadata = AudiobookAwaitingMetadata || EbookAwaitingMetadata; + return AudiobookSetupPending || EbookSetupPending || AudiobookMonitor.HasValue || EbookMonitor.HasValue || SearchForMissingBooks; + } + + private bool HasLegacyIndependentSearch() => + SearchForMissingBooks && !AudiobookSetupSearchForMissingBooks && !EbookSetupSearchForMissingBooks; + private void PreserveLegacySearch() { - if (SearchForMissingBooks && !AudiobookSetupSearchForMissingBooks && !EbookSetupSearchForMissingBooks) + if (HasLegacyIndependentSearch()) IndependentSearchForMissingBooks = true; } diff --git a/src/NzbDrone.Core/Books/Model/PendingAuthorImport.cs b/src/NzbDrone.Core/Books/Model/PendingAuthorImport.cs index 1320116d6..a3d2c810a 100644 --- a/src/NzbDrone.Core/Books/Model/PendingAuthorImport.cs +++ b/src/NzbDrone.Core/Books/Model/PendingAuthorImport.cs @@ -123,6 +123,9 @@ public bool IsActive() OverallStatus == PendingImportStatus.Retrying; } + internal bool RefusedAuthorSetup(BookMediaType mediaType) => !IsActive() && + (mediaType == BookMediaType.Audiobook ? AudiobookStatus : EbookStatus) == PendingImportStatus.Failed; + public bool IsComplete() { return OverallStatus == PendingImportStatus.PartialSuccess || diff --git a/src/NzbDrone.Core/Books/Repositories/AuthorRepository.cs b/src/NzbDrone.Core/Books/Repositories/AuthorRepository.cs index fcff3f91f..ae18db1b0 100644 --- a/src/NzbDrone.Core/Books/Repositories/AuthorRepository.cs +++ b/src/NzbDrone.Core/Books/Repositories/AuthorRepository.cs @@ -3,6 +3,7 @@ using System.Data; using System.Diagnostics; using System.Linq; +using System.Reflection; using Dapper; using NLog; using NzbDrone.Common.Extensions; @@ -36,6 +37,7 @@ public interface IAuthorRepository : IBasicRepository public class AuthorRepository : BasicRepository, IAuthorRepository { private readonly Logger _logger; + private List _updateProperties; public AuthorRepository(IMainDatabase database, IEventAggregator eventAggregator, @@ -54,6 +56,10 @@ public static IEnumerable Query(IDatabase database, SqlBuilder builder) return database.Query(builder); } + // Setup is written explicitly by the setup lifecycle, never by a generic edit. + protected override List GetUpdateProperties() => + _updateProperties ??= base.GetUpdateProperties().Where(property => property.Name != nameof(Author.AddOptions)).ToList(); + public Author Update(Author author, IDbConnection connection, IDbTransaction transaction) { UpdateMany(new[] { author }, connection, transaction); diff --git a/src/NzbDrone.Core/Books/Services/AuthorLibraryService.cs b/src/NzbDrone.Core/Books/Services/AuthorLibraryService.cs index 4065e3b21..08c8c30db 100644 --- a/src/NzbDrone.Core/Books/Services/AuthorLibraryService.cs +++ b/src/NzbDrone.Core/Books/Services/AuthorLibraryService.cs @@ -1202,6 +1202,7 @@ private Author HandleExistingAuthor(Author existingAuthor, Author remoteAuthor, // Initial policy belongs to first media-side setup, not to the presence // of catalog rows. Aggregate author search must also survive another // route completing that setup before a queued request is replayed. + var previousScanScope = existingAuthor.AddOptions?.GetInitialScanMediaType(); existingAuthor.AddOptions ??= new AddAuthorOptions { Monitor = null }; existingAuthor.AddOptions.AudiobookMonitor ??= audiobookInitialMode; existingAuthor.AddOptions.EbookMonitor ??= ebookInitialMode; @@ -1223,6 +1224,7 @@ private Author HandleExistingAuthor(Author existingAuthor, Author remoteAuthor, (!config.PendingImportId.HasValue || existingAuthor.AddOptions.AudiobookSetupPendingImportId == config.PendingImportId), initializeEbook || config.CreateEbook && existingAuthor.AddOptions.EbookSetupPending && (!config.PendingImportId.HasValue || existingAuthor.AddOptions.EbookSetupPendingImportId == config.PendingImportId)); + existingAuthor.AddOptions.ResetRetryForNewScanScope(previousScanScope, initializeAudiobook || initializeEbook); _authorService.SetAddOptions(existingAuthor); } diff --git a/src/NzbDrone.Core/Books/Services/AuthorService.cs b/src/NzbDrone.Core/Books/Services/AuthorService.cs index 49181ab25..128775036 100644 --- a/src/NzbDrone.Core/Books/Services/AuthorService.cs +++ b/src/NzbDrone.Core/Books/Services/AuthorService.cs @@ -83,8 +83,6 @@ public class AuthorService : IAuthorService private readonly IManageCommandQueue _commandQueueManager; private readonly Logger _logger; private readonly ICached<(List Authors, Lazy Names)> _cache; - private readonly ICached _authorByIdCache; - private static readonly TimeSpan AuthorByIdCacheTtl = TimeSpan.FromSeconds(10); private readonly IBookRepository _bookRepository; private readonly IMediaFileService _mediaFileService; private readonly IProviderAliasService _providerAliasService; @@ -121,7 +119,6 @@ public AuthorService(IAuthorRepository authorRepository, // Repeated lookups must not keep an outdated author/name snapshot alive indefinitely. _cache = cacheManager.GetCache<(List Authors, Lazy Names)>( GetType(), "authorcache"); - _authorByIdCache = cacheManager.GetCache(GetType(), "authorById"); _logger = logger; _bookRepository = bookRepository; _mediaFileService = mediaFileService; @@ -227,7 +224,6 @@ public Author AddAuthor(Author newAuthor, bool doRefresh) var insertedAuthor = _authorRepository.Insert(newAuthor); InvalidateAuthorCatalog(); - _authorByIdCache.Remove(insertedAuthor.Id.ToString()); stopwatch.Stop(); _logger.Debug("[DB-TIMING] Author '{0}' inserted in {1}ms", newAuthor.Name, stopwatch.ElapsedMilliseconds); @@ -254,7 +250,6 @@ public List AddAuthors(List newAuthors, bool doRefresh) _authorRepository.InsertMany(newAuthors); InvalidateAuthorCatalog(); - _authorByIdCache.Clear(); stopwatch.Stop(); _logger.Debug("[DB-TIMING] {0} authors batch inserted in {1}ms (avg {2}ms/author)", @@ -413,10 +408,6 @@ private List DeleteAuthorsInternal( _authorRepository.DeleteMany(authors.Select(author => author.Id)); InvalidateAuthorCatalog(); - foreach (var authorId in distinctIds) - { - _authorByIdCache.Remove(authorId.ToString()); - } return retainedBookFileIds.Distinct().ToList(); } @@ -477,7 +468,7 @@ public Author FindByProviderId(string provider, string providerId) ? ProviderIdHelper.Normalize(providerId, canonicalPrefix) : ProviderIdHelper.WithPrefix(canonicalPrefix, providerId); - var direct = CacheLookupAuthor(finder(normalizedProviderId)); + var direct = finder(normalizedProviderId); if (direct != null) { return direct; @@ -487,7 +478,7 @@ public Author FindByProviderId(string provider, string providerId) .OrderBy(id => id) .FirstOrDefault(); - return aliasAuthorId.GetValueOrDefault() > 0 ? CacheLookupAuthor(_authorRepository.Get(aliasAuthorId.Value)) : null; + return aliasAuthorId.GetValueOrDefault() > 0 ? _authorRepository.Get(aliasAuthorId.Value) : null; } public Author FindByName(string title) @@ -499,25 +490,8 @@ public Author FindByName(string title) string.Join(", ", candidates.Select(author => author.Id))); } - return CacheLookupAuthor(candidates.ExclusiveOrDefault()); - } - - private Author CacheLookupAuthor(Author author) - { - if (author == null || author.Id <= 0) - { - return author; - } - - var key = author.Id.ToString(); - var cached = _authorByIdCache.Find(key); - if (cached != null) - { - return cached; - } - - _authorByIdCache.Set(key, author, AuthorByIdCacheTtl); - return author; + var match = candidates.ExclusiveOrDefault(); + return match == null ? null : _authorRepository.Find(match.Id); } public List GetCandidates(string name) @@ -731,20 +705,7 @@ public List AllForTag(int tagId) .ToList(); } - public Author GetAuthor(int authorId) - { - var key = authorId.ToString(); - var cached = _authorByIdCache.Find(key); - if (cached != null) - { - return cached; - } - - var author = _authorRepository.Get(authorId); - _authorByIdCache.Set(key, author, AuthorByIdCacheTtl); - return author; - } - + public Author GetAuthor(int authorId) => _authorRepository.Get(authorId); public List GetExistingAuthors(IEnumerable authorIds) => _authorRepository.FindExisting(authorIds); @@ -757,14 +718,12 @@ public void SetAddOptions(Author author) { _authorRepository.SetFields(author, s => s.AddOptions); InvalidateAuthorCatalog(); - _authorByIdCache.Remove(author.Id.ToString()); } public Author UpdateAuthor(Author author) => UpdateAuthor(author, null); public Author UpdateAuthor(Author author, Action beforeSave) { - _authorByIdCache.Remove(author.Id.ToString()); var storedAuthor = GetAuthor(author.Id); @@ -804,7 +763,6 @@ public Author UpdateAuthor(Author author, Action { updatedAuthor = _authorRepository.Update(author); InvalidateAuthorCatalog(); - _authorByIdCache.Remove(updatedAuthor.Id.ToString()); } else { @@ -815,7 +773,6 @@ public Author UpdateAuthor(Author author, Action updatedAuthor = _authorRepository.Update(author, connection, transaction); transaction.Commit(); InvalidateAuthorCatalog(); - _authorByIdCache.Clear(); } try { _eventAggregator.PublishEvent(new AuthorEditedEvent(updatedAuthor, storedAuthor, beforeSave != null)); } catch (Exception ex) when (beforeSave != null) @@ -957,7 +914,6 @@ public List UpdateAuthors(List author, bool useExistingRelativeF _authorRepository.UpdateMany(author); InvalidateAuthorCatalog(); - _authorByIdCache.Clear(); _logger.Debug("{0} authors updated", author.Count); return author; @@ -1248,7 +1204,6 @@ public void SetMediaTypeMonitoring(int authorId, string mediaType, bool monitore author.Monitored = author.IsMonitoredFromMediaSettings(); _authorRepository.Update(author); InvalidateAuthorCatalog(); - _authorByIdCache.Remove(authorId.ToString()); _eventAggregator.PublishEvent(new AuthorEditedEvent(author, author)); } @@ -1262,7 +1217,6 @@ public void UpdateLastSelectedMediaType(int authorId, string mediaType) { _authorRepository.UpdateLastSelectedMediaType(authorId, mediaType); InvalidateAuthorCatalog(); - _authorByIdCache.Remove(authorId.ToString()); } public List GetAuthorBooksFromCache(int authorId) diff --git a/src/NzbDrone.Core/Books/Services/BookService.cs b/src/NzbDrone.Core/Books/Services/BookService.cs index 15386e3f7..64e5820cd 100644 --- a/src/NzbDrone.Core/Books/Services/BookService.cs +++ b/src/NzbDrone.Core/Books/Services/BookService.cs @@ -88,6 +88,7 @@ public interface IBookService Book GetBook(int bookId); List GetBooks(IEnumerable bookIds); List GetExistingBooks(IEnumerable bookIds) => GetBooks(bookIds); + List FindExistingBookRows(IEnumerable bookIds) => GetExistingBooks(bookIds); List GetBooksForLookup(IEnumerable bookIds) => throw new NotImplementedException(); List GetBooksByAuthor(int authorId, bool onlyMonitoredEditions = false); List GetNextBooksByAuthorId(IEnumerable authorIds); @@ -788,10 +789,12 @@ public Book GetBook(int bookId) var book = _bookRepository.Get(bookId); if (book != null && book.AuthorId > 0) { - book.Author = _authorService.GetAuthor(book.AuthorId); - - // Load editions for the book book.Editions = _editionService.GetEditionsByBook(bookId); + // The edition query already joins the book's owning author. + var joinedAuthor = book.Editions? + .Select(edition => edition?.LazyBook?.IsLoaded == true ? edition.Book : null) + .FirstOrDefault(parent => parent?.LazyAuthor?.IsLoaded == true && parent.Author?.Id == book.AuthorId)?.Author; + book.Author = joinedAuthor ?? _authorService.GetAuthor(book.AuthorId); // Load BookFiles in one query while preserving the old edition-iteration ordering. if (book.Editions != null && book.Editions.Any()) @@ -857,6 +860,8 @@ public List GetExistingBooks(IEnumerable bookIds) return books; } + public List FindExistingBookRows(IEnumerable bookIds) => _bookRepository.FindExisting(bookIds).ToList(); + public List GetBooksForLookup(IEnumerable bookIds) { var books = _bookRepository.FindExisting(bookIds).ToList(); @@ -2448,7 +2453,7 @@ public List GetBooksByBaseId(string baseBookId) internal static object GetWantedEditionLock(int authorId) => WantedEditionLocks.GetOrAdd(authorId, _ => new object()); - internal static IDisposable EnterWantedEditionLock(Author author, Logger logger, CancellationToken cancellationToken = default) + public static IDisposable EnterWantedEditionLock(Author author, Logger logger, CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); var writerLock = GetWantedEditionLock(author.Id); diff --git a/src/NzbDrone.Core/Books/Services/PendingAuthorImportService.cs b/src/NzbDrone.Core/Books/Services/PendingAuthorImportService.cs index 53fc0a641..35a21b9ca 100644 --- a/src/NzbDrone.Core/Books/Services/PendingAuthorImportService.cs +++ b/src/NzbDrone.Core/Books/Services/PendingAuthorImportService.cs @@ -30,11 +30,12 @@ public interface IPendingAuthorImportService bool SaveProgress(PendingAuthorImport item, PendingAuthorImport previous); void ScheduleRetry(PendingAuthorImport item, string error); void Cancel(int id); + void ReconcileSetupCancellation(Author author); bool IsActiveRequest(int id, long version); void RetryNow(int id); void CleanupOldCompleted(); void Delete(int id); - bool TryDeleteIfUnchanged(PendingAuthorImport item) + bool TryDeleteIfUnchanged(PendingAuthorImport item, Author author = null) { Delete(item.Id); return true; @@ -44,6 +45,7 @@ bool TryDeleteIfUnchanged(PendingAuthorImport item) public class PendingAuthorImportService : IPendingAuthorImportService, IHandle, IHandle, IHandle, IHandle, IHandle { + private static readonly object SetupRefusalLock = new(); private readonly IPendingAuthorImportRepository _repository; private readonly IAuthorService _authorService; private readonly IEventAggregator _eventAggregator; @@ -1132,7 +1134,8 @@ public bool IsActiveRequest(int id, long version) public void Handle(AuthorSetupMetadataRefusedEvent message) { - var author = message.Author; + using var writer = BookService.EnterWantedEditionLock(message.Author, _logger); + var author = _authorService.GetAuthor(message.Author.Id); var options = author.AddOptions; if (options?.AwaitingMetadata != true) return; @@ -1147,34 +1150,62 @@ public void Handle(AuthorSetupMetadataRefusedEvent message) return; } - var config = new MonitoringConfig + int id; + lock (SetupRefusalLock) { - CreateAudiobook = audio, - CreateEbook = ebook, - IsAuthorSettingsRequest = true, - RequestedBy = "AuthorSetup", - AuthorName = author.Name, - AudiobookMonitorExistingMode = audio ? options.AudiobookMonitor : null, - EbookMonitorExistingMode = ebook ? options.EbookMonitor : null, - AudiobookMonitored = audio ? author.AudiobookMonitored : null, - EbookMonitored = ebook ? author.EbookMonitored : null, - AudiobookMonitorNewItems = audio ? author.AudiobookMonitorNewItems : null, - EbookMonitorNewItems = ebook ? author.EbookMonitorNewItems : null, - AudiobookQualityProfileId = audio ? author.AudiobookQualityProfileId : null, - EbookQualityProfileId = ebook ? author.EbookQualityProfileId : null, - AudiobookMetadataProfileId = audio ? author.AudiobookMetadataProfileId : null, - EbookMetadataProfileId = ebook ? author.EbookMetadataProfileId : null, - AudiobookRootFolderPath = audio ? author.AudiobookRootFolderPath : null, - EbookRootFolderPath = ebook ? author.EbookRootFolderPath : null, - SearchForMissingBooks = audio && options.AudiobookSetupSearchForMissingBooks || ebook && options.EbookSetupSearchForMissingBooks, - SyncMonitoredAcrossFormats = author.SyncMonitoredAcrossFormats - }; - var id = EnqueueAsync(message.ProviderId, config, config.RequestedBy).GetAwaiter().GetResult(); + // Cancel writes the row before waiting for the author writer so a + // worker's next version-checked write cannot queue a cancelled search. + bool StillRequested(int? itemId, BookMediaType mediaType) + { + if (!itemId.HasValue) return true; + var request = _repository.Find(itemId.Value); + return request != null && (mediaType == BookMediaType.Audiobook ? request.HasAudiobook() : request.HasEbook()); + } + + audio = audio && StillRequested(options.AudiobookSetupPendingImportId, BookMediaType.Audiobook); + ebook = ebook && StillRequested(options.EbookSetupPendingImportId, BookMediaType.Ebook); + if (!audio && !ebook) + { + _logger.Debug("Ignoring metadata refusal for author {0} because its setup request was cancelled", author.Id); + return; + } + + var config = new MonitoringConfig + { + CreateAudiobook = audio, + CreateEbook = ebook, + IsAuthorSettingsRequest = true, + RequestedBy = "AuthorSetup", + AuthorName = author.Name, + AudiobookMonitorExistingMode = audio ? options.AudiobookMonitor : null, + EbookMonitorExistingMode = ebook ? options.EbookMonitor : null, + AudiobookMonitored = audio ? author.AudiobookMonitored : null, + EbookMonitored = ebook ? author.EbookMonitored : null, + AudiobookMonitorNewItems = audio ? author.AudiobookMonitorNewItems : null, + EbookMonitorNewItems = ebook ? author.EbookMonitorNewItems : null, + AudiobookQualityProfileId = audio ? author.AudiobookQualityProfileId : null, + EbookQualityProfileId = ebook ? author.EbookQualityProfileId : null, + AudiobookMetadataProfileId = audio ? author.AudiobookMetadataProfileId : null, + EbookMetadataProfileId = ebook ? author.EbookMetadataProfileId : null, + AudiobookRootFolderPath = audio ? author.AudiobookRootFolderPath : null, + EbookRootFolderPath = ebook ? author.EbookRootFolderPath : null, + SearchForMissingBooks = audio && options.AudiobookSetupSearchForMissingBooks || ebook && options.EbookSetupSearchForMissingBooks, + SyncMonitoredAcrossFormats = author.SyncMonitoredAcrossFormats + }; + id = EnqueueAsync(message.ProviderId, config, config.RequestedBy).GetAwaiter().GetResult(); + } if (id <= 0) throw new InvalidOperationException("Unable to retain refused author media-side setup."); - if (audio) options.AudiobookSetupPendingImportId = id; - if (ebook) options.EbookSetupPendingImportId = id; - options.MetadataUnavailable = true; - _authorService.SetAddOptions(author); + if (!options.MetadataUnavailable || + audio && options.AudiobookSetupPendingImportId != id || + ebook && options.EbookSetupPendingImportId != id) + { + var updated = author.ShallowClone(); + updated.AddOptions = options.ShallowClone(); + if (audio) updated.AddOptions.AudiobookSetupPendingImportId = id; + if (ebook) updated.AddOptions.EbookSetupPendingImportId = id; + updated.AddOptions.MetadataUnavailable = true; + _authorService.SetAddOptions(updated); + } var pending = _repository.Find(id); if (pending == null) @@ -1216,68 +1247,60 @@ public void Handle(PendingAuthorImportCancelledEvent message) => private void SetOwnedSetupState(PendingAuthorImport item, BookMediaType? cancelledMediaType, bool cancelled) { - var author = _authorService.FindByProviderId(ExtractPrefix(item.ProviderId), ExtractIdWithoutPrefix(item.ProviderId)); + var author = FindSetupAuthor(item); if (author == null) return; lock (BookService.GetWantedEditionLock(author.Id)) { author = _authorService.GetAuthor(author.Id); - var options = author?.AddOptions; - if (options == null) return; - var audio = options.AudiobookSetupPendingImportId == item.Id && - (!cancelledMediaType.HasValue || cancelledMediaType == BookMediaType.Audiobook); - var ebook = options.EbookSetupPendingImportId == item.Id && - (!cancelledMediaType.HasValue || cancelledMediaType == BookMediaType.Ebook); - if (!audio && !ebook) return; - var currentRequest = _repository.Find(item.Id); - if (currentRequest != null) item = currentRequest; - - if (cancelled) - { - audio &= currentRequest == null || !currentRequest.HasAudiobook(); - ebook &= currentRequest == null || !currentRequest.HasEbook(); - options.CancelInitialSearch(audio, ebook); - if (audio) - { - options.AudiobookMonitor = null; - options.AudiobookSetupPending = false; - options.AudiobookAwaitingMetadata = false; - options.AudiobookSetupPendingImportId = null; - } - if (ebook) - { - options.EbookMonitor = null; - options.EbookSetupPending = false; - options.EbookAwaitingMetadata = false; - options.EbookSetupPendingImportId = null; - } + if (author?.AddOptions != null) + ReconcileSetupState(author, item, cancelledMediaType, cancelled); + } + } - if (!options.AudiobookSetupPending && !options.EbookSetupPending && - !options.AudiobookMonitor.HasValue && !options.EbookMonitor.HasValue && !options.SearchForMissingBooks) - { - author.AddOptions = null; - } - else - { - options.AwaitingMetadata = options.AudiobookAwaitingMetadata || options.EbookAwaitingMetadata; - } - } - if (author.AddOptions != null) - { - // This operation already loaded one owner. With only two media - // sides, at most one distinct remaining owner needs a lookup. - var owners = new Dictionary { [item.Id] = item }; - var otherOwnerId = new[] { options.AudiobookSetupPendingImportId, options.EbookSetupPendingImportId } - .FirstOrDefault(id => id.HasValue && id.Value != item.Id); - if (otherOwnerId.HasValue) owners[otherOwnerId.Value] = _repository.Find(otherOwnerId.Value); - - bool Refused(int? ownerId, BookMediaType mediaType) => ownerId.HasValue && - owners.TryGetValue(ownerId.Value, out var owner) && owner != null && !owner.IsActive() && - (mediaType == BookMediaType.Audiobook ? owner.AudiobookStatus : owner.EbookStatus) == PendingImportStatus.Failed; - options.MetadataUnavailable = Refused(options.AudiobookSetupPendingImportId, BookMediaType.Audiobook) || - Refused(options.EbookSetupPendingImportId, BookMediaType.Ebook); - } + // The scan already holds the author lock. A missing row can be a successful handoff. + public void ReconcileSetupCancellation(Author author) => + ReconcileSetupState(author, null, null, cancelled: true); - _authorService.SetAddOptions(author); + private void ReconcileSetupState(Author author, PendingAuthorImport request, BookMediaType? cancelledMediaType, bool cancelled) + { + var options = author.AddOptions; + var audioId = options.AudiobookSetupPendingImportId; + var ebookId = options.EbookSetupPendingImportId; + bool Applies(int? id, BookMediaType mediaType) => id.HasValue && + (request == null || request.Id == id) && + (!cancelledMediaType.HasValue || cancelledMediaType == mediaType); + + var appliesToAudio = Applies(audioId, BookMediaType.Audiobook); + var appliesToEbook = Applies(ebookId, BookMediaType.Ebook); + if (!appliesToAudio && !appliesToEbook) return; + + PendingAuthorImport ReadOwner(int? id) => id.HasValue ? _repository.Find(id.Value) : null; + var audio = ReadOwner(audioId); + var ebook = ebookId == audioId ? audio : ReadOwner(ebookId); + var withdrawAudio = cancelled && appliesToAudio && (audio == null ? request != null : !audio.HasAudiobook()); + var withdrawEbook = cancelled && appliesToEbook && (ebook == null ? request != null : !ebook.HasEbook()); + if (cancelled && !withdrawAudio && !withdrawEbook) return; + + // An explicit event can still describe a known owner after the row disappears. + bool Refused(int? id, PendingAuthorImport owner, BookMediaType mediaType) => + (owner ?? (request?.Id == id ? request : null))?.RefusedAuthorSetup(mediaType) == true; + var unavailable = + !withdrawAudio && Refused(audioId, audio, BookMediaType.Audiobook) || + !withdrawEbook && Refused(ebookId, ebook, BookMediaType.Ebook); + if (!cancelled && unavailable == options.MetadataUnavailable) return; + + var updated = author.ShallowClone(); + var remaining = options.ShallowClone(); + remaining.MetadataUnavailable = unavailable; + updated.AddOptions = !cancelled || remaining.RemoveCancelledSetup(withdrawAudio, withdrawEbook) ? remaining : null; + _authorService.SetAddOptions(updated); + author.AddOptions = updated.AddOptions; + + if (cancelled) + { + var cleared = withdrawAudio && withdrawEbook ? "audiobook and ebook" : withdrawAudio ? "audiobook" : "ebook"; + _logger.Info("Cleared cancelled {0} setup for {1} ({2}). Remaining setup: {3}.", + cleared, author.Name, author.Id, author.AddOptions?.GetInitialScanMediaType() ?? "none"); } } @@ -1310,14 +1333,27 @@ private void CancelForAuthor(Author author, BookMediaType? mediaType) public void Cancel(int id) => Cancel(id, null); - private PendingAuthorImport Cancel(int id, BookMediaType? mediaType) + private Author FindSetupAuthor(PendingAuthorImport item) => + _authorService.FindByProviderId(ExtractPrefix(item.ProviderId), ExtractIdWithoutPrefix(item.ProviderId)); + + private PendingAuthorImport Cancel(int id, BookMediaType? mediaType, bool deleting = false) { while (true) { var item = _repository.Find(id); - if (item == null || !item.IsActive()) + if (item == null) return null; + var wasActive = item.IsActive(); + if (!wasActive) { - return item; + var setup = deleting && (item.HasAudiobook() || item.HasEbook()) ? FindSetupAuthor(item)?.AddOptions : null; + if (setup?.AudiobookSetupPendingImportId != item.Id && setup?.EbookSetupPendingImportId != item.Id) + { + // A prior cancel may have saved the request before its setup write failed. + if (!item.HasAudiobook() || !item.HasEbook()) + SetOwnedSetupState(item, mediaType, cancelled: true); + + return item; + } } if (!mediaType.HasValue || mediaType == BookMediaType.Audiobook) @@ -1352,14 +1388,18 @@ private PendingAuthorImport Cancel(int id, BookMediaType? mediaType) item.UpdatedAt = DateTime.UtcNow; var expectedVersion = item.Version; - if (!_repository.TryUpdateRequest(item, expectedVersion)) + lock (SetupRefusalLock) { - continue; + if (!_repository.TryUpdateRequest(item, expectedVersion)) + { + _logger.Debug("Pending import {0} changed before cancellation saved. Re-reading the request.", id); + continue; + } } _logger.Info("Cancelled pending import {0}", id); SetOwnedSetupState(item, mediaType, cancelled: true); - if (!item.IsActive()) _eventAggregator.PublishEvent(new PendingAuthorImportCancelledEvent(item)); + if (wasActive && !item.IsActive()) _eventAggregator.PublishEvent(new PendingAuthorImportCancelledEvent(item)); return item; } } @@ -1412,14 +1452,25 @@ public void CleanupOldCompleted() public void Delete(int id) { - var item = Cancel(id, null); + // Save the withdrawal and clear any owned setup before removing its row. + Cancel(id, null, deleting: true); _repository.Delete(id); - if (item != null) SetOwnedSetupState(item, cancelledMediaType: null, cancelled: true); _logger.Info("Deleted pending author import {0}", id); } - public bool TryDeleteIfUnchanged(PendingAuthorImport item) + public bool TryDeleteIfUnchanged(PendingAuthorImport item, Author author = null) { + // The surviving side of a partly cancelled request may finish while the + // cancellation is still waiting for the author lock, or after a restart. + // Persist the withdrawal before deleting the row that records it. + if (author?.AddOptions is { } setup) + { + if (!item.HasAudiobook() && setup.AudiobookSetupPendingImportId == item.Id) + SetOwnedSetupState(item, BookMediaType.Audiobook, cancelled: true); + if (!item.HasEbook() && setup.EbookSetupPendingImportId == item.Id) + SetOwnedSetupState(item, BookMediaType.Ebook, cancelled: true); + } + if (!_repository.TryDelete(item.Id, item.Version)) { return false;