Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/API_IDENTITY_AND_LIFECYCLE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
9 changes: 9 additions & 0 deletions src/Chaptarr.Api.V1/Author/AuthorController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -642,6 +642,14 @@ public async Task<ActionResult<AuthorResource>> 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;
Expand All @@ -653,6 +661,7 @@ public async Task<ActionResult<AuthorResource>> 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)
Expand Down
7 changes: 5 additions & 2 deletions src/Chaptarr.Api.V1/BookFiles/BookFileController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -250,11 +251,13 @@ public List<BookFileResource> GetBookFiles(int? authorId, [FromQuery] List<int>

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<BookFileResource>();
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)));
Expand Down
13 changes: 11 additions & 2 deletions src/Chaptarr.Api.V1/ManualImport/ManualImportController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -201,11 +202,19 @@ private ManualImportResource AddQualityWeight(ManualImportResource item)

private List<ManualImportResource> UpdateImportItems(List<ManualImportUpdateResource> 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<int, Book>();
var items = new List<ManualImportItem>();
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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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; }
Expand Down
2 changes: 1 addition & 1 deletion src/Chaptarr.Api.V1/openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": {
Expand Down
Original file line number Diff line number Diff line change
@@ -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<int[]>();
var authors = Proxy<IAuthorService>((method, args) =>
{
Assert.That(method.Name, Is.EqualTo(nameof(IAuthorService.GetExistingAuthors)));
authorsRead.Add(((IEnumerable<int>)args[0]).ToArray());
return new List<Author> { new() { Id = 11 }, new() { Id = 12 } };
});
var books = Proxy<IBookService>((method, args) =>
{
Assert.That(method.Name, Is.EqualTo(nameof(IBookService.FindExistingBookRows)));
Assert.That((IEnumerable<int>)args[0], Is.EqualTo(new[] { 53, 51, 53 }));
return new List<Book> { new() { Id = 51, AuthorId = 11 }, new() { Id = 53, AuthorId = 12 } };
});
var files = Proxy<IMediaFileService>((method, args) =>
{
Assert.That(method.Name, Is.EqualTo(nameof(IMediaFileService.GetFilesByBook)));
return new List<BookFile> { 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<int>(), new List<int> { 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<int>();
var authorReads = new List<int[]>();
var authors = Proxy<IAuthorService>((method, args) =>
{
Assert.That(method.Name, Is.EqualTo(nameof(IAuthorService.GetExistingAuthors)));
authorReads.Add(((IEnumerable<int>)args[0]).ToArray());
return missing ? new List<Author>() : new List<Author> { new() { Id = 11 } };
});
var books = Proxy<IBookService>((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<IManualImportService>((method, args) =>
{
Assert.That(method.Name, Is.EqualTo(nameof(IManualImportService.UpdateItems)));
var items = (List<ManualImportItem>)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<ManualImportItem>();
});
var controller = new ManualImportController(manual, authors, null, books, null, null, LogManager.GetCurrentClassLogger());
var resources = new List<ManualImportUpdateResource>
{
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<ModelNotFoundException>().With.Message.Contains("Author with ID 11"));
Assert.That(bookReads, Is.Empty);
}
else
{
Assert.That(controller.UpdateItems(resources), Is.TypeOf<AcceptedResult>());
Assert.That(bookReads, Is.EqualTo(new[] { 51 }));
}
Assert.That(authorReads.Single(), Is.EqualTo(new[] { 11 }));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,8 @@ public Task<int> 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();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,8 @@ public Task<int> 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();
Expand Down Expand Up @@ -900,7 +902,7 @@ int Import(JsonObject payload)
Assert.That(commands.OfType<NzbDrone.Core.IndexerSearch.MissingBookSearchCommand>(), Is.Empty);
});
var scan = new AuthorScannedHandler(new BookMonitoredService(authors, books, logger), authors, queue,
Proxy<IBookAddedService>((_, _) => null), events, logger, books);
Proxy<IBookAddedService>((_, _) => 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<NzbDrone.Core.IndexerSearch.MissingBookSearchCommand>().Count(), Is.EqualTo(search ? 1 : 0));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,8 @@ public Author UpdateAuthorProgressiveSettings(
}

public Author GetAuthor(int authorId) => ExistingAuthor?.Id == authorId ? ExistingAuthor : null;
public List<Author> GetExistingAuthors(IEnumerable<int> authorIds) => throw new NotImplementedException();
public List<Author> GetExistingAuthors(IEnumerable<int> authorIds) => ExistingAuthor != null && authorIds.Contains(ExistingAuthor.Id)
? new List<Author> { ExistingAuthor } : new List<Author>();
public List<Author> GetAuthors(IEnumerable<int> authorIds) => throw new NotImplementedException();
public List<Author> AddAuthors(List<Author> newAuthors, bool doRefresh) => throw new NotImplementedException();
public Author FindByName(string title) => null;
Expand Down Expand Up @@ -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<IBookAddedService>((_, _) => 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]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,10 +51,8 @@ private sealed class Harness : IDisposable
public readonly List<string> TransactionalAuthorWrites = new();
public int TransactionalBookInserts;
public int TransactionalHistoryInserts;
public bool ProbeSourceCache;
public bool ProbeAllAuthorCache;
public readonly List<int[]> AllAuthorCacheObservations = new();
public readonly List<Author> SourceCacheObservations = new();
public readonly List<(bool SourceExists, string Scalar, int[] Owners, string[] Aliases, Author OldAuthor)> Observations = new();
private readonly RefreshAuthorService _refresh;
public Func<string, RefreshResult> Fetch = id => RefreshResult.Error("fixture has no published response");
Expand Down Expand Up @@ -89,11 +87,6 @@ public Harness(IMainDatabase database, string provider = "az", bool globalFirst
DependentTables.Select(table => connection.Query<int>($"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);
}
Expand Down Expand Up @@ -453,29 +446,28 @@ 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 =>
{
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();
if (failure)
{
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<ModelNotFoundException>(() => h.Service.GetAuthor(h.Source.Id));
Assert.Throws<ModelNotFoundException>(() => h.Service.GetAuthor(h.Source.Id));
}
Expand Down
Loading
Loading