feat(api): add paged books random sort (#2451)

This commit is contained in:
James Ward
2026-08-24 23:01:10 -04:00
committed by GitHub
parent bc5616f414
commit 0e675495b7
10 changed files with 124 additions and 34 deletions
@@ -11,10 +11,11 @@ public record CursorState(
@JsonProperty("o") long offset,
@JsonProperty("l") int limit,
@JsonProperty("s") String sort,
@JsonProperty("f") String paramsHash
@JsonProperty("f") String paramsHash,
@JsonProperty("r") Integer randomSeed
) {
public CursorState withOffset(long newOffset) {
return new CursorState(newOffset, limit, sort, paramsHash);
return new CursorState(newOffset, limit, sort, paramsHash, randomSeed);
}
}
@@ -12,6 +12,7 @@ public record SortContext<E>(
CriteriaQuery<?> query,
CriteriaBuilder cb,
boolean descending,
Long userId
Long userId,
Integer randomSeed
) {
}
@@ -33,14 +33,14 @@ public class SortRegistry<E> {
return Collections.unmodifiableSet(builders.keySet());
}
public List<Order> toOrders(List<SortTerm> terms, Root<E> root, CriteriaQuery<?> query, CriteriaBuilder cb, Long userId) {
public List<Order> toOrders(List<SortTerm> terms, Root<E> root, CriteriaQuery<?> query, CriteriaBuilder cb, Long userId, Integer randomSeed) {
List<Order> orders = new ArrayList<>();
for (SortTerm term : terms) {
SortOrderBuilder<E> builder = builders.get(term.key());
if (builder == null) {
throw ApiError.INVALID_SORT.createException("Unknown sort key: " + term.key());
}
orders.addAll(builder.toOrders(new SortContext<>(root, query, cb, term.descending(), userId)));
orders.addAll(builder.toOrders(new SortContext<>(root, query, cb, term.descending(), userId, randomSeed)));
}
return orders;
}
@@ -45,6 +45,7 @@ public class BookBrowseService {
private static final String PAGE_PATH = "/api/v1/books/page";
private static final String FACET_PATH = "/api/v1/books/facets";
private static final int MAX_PAGE_SIZE = 100;
private static final int MAX_RANDOM_SORT_SEED = 999;
private final AuthenticationService authenticationService;
private final BookQueryService bookQueryService;
@@ -69,16 +70,19 @@ public class BookBrowseService {
long offset;
int limit;
String sortString;
Integer randomSeed;
if (cursor != null) {
CursorState state = cursorCodec.decode(cursor);
cursorCodec.verifyParamsMatch(state, paramsHash);
offset = state.offset();
limit = state.limit();
sortString = state.sort();
randomSeed = state.randomSeed();
} else {
offset = pageable.getOffset();
limit = pageable.getPageSize();
sortString = sort;
randomSeed = (int) (Math.random() * MAX_RANDOM_SORT_SEED);
}
if (limit <= 0) {
throw ApiError.INVALID_INPUT.createException("Page size must be positive.");
@@ -87,13 +91,13 @@ public class BookBrowseService {
List<SortTerm> sortTerms = SortParser.parse(sortString, sortRegistry.registry().keys());
Specification<BookEntity> filter = filterSpecifications.base(query, facets, facetLogic, userId, isAdmin, BookFilterSpecifications.libraryIds(user), null);
Specification<BookEntity> spec = withSort(filter, sortTerms, userId);
Specification<BookEntity> spec = withSort(filter, sortTerms, userId, randomSeed);
Pageable pageRequest = PageRequest.of((int) (offset / limit), limit);
Page<Book> page = bookQueryService.findBooksPaged(spec, pageRequest, userId);
enrich(page.getContent(), userId);
CursorState baseState = new CursorState(offset, limit, sortString, paramsHash);
CursorState baseState = new CursorState(offset, limit, sortString, paramsHash, randomSeed);
String currentCursor = cursorCodec.encode(baseState);
List<Link> links = linksBuilder.build(new LinksBuilder.Context(
PAGE_PATH, FACET_PATH, BrowseParams.preserved(facet, facetLogicParam, query), offset, limit, page.getTotalElements(), baseState));
@@ -119,7 +123,11 @@ public class BookBrowseService {
if (predicate != null) {
cq.where(predicate);
}
cq.orderBy(sortRegistry.registry().toOrders(sortTerms, root, cq, cb, userId));
// The `findAllIds` doesn't pass a cursor so it's a random seed every time.
int randomSeed = (int) (Math.random() * MAX_RANDOM_SORT_SEED);
cq.orderBy(sortRegistry.registry().toOrders(sortTerms, root, cq, cb, userId, randomSeed));
return entityManager.createQuery(cq).getResultList();
}
@@ -127,17 +135,22 @@ public class BookBrowseService {
public BrowsePage<Book> wrapLegacy(Page<Book> page, Pageable pageable) {
long offset = pageable.getOffset();
int limit = pageable.getPageSize();
String paramsHash = ParamsHash.compute(null, Map.of(), FacetLogic.AND);
CursorState baseState = new CursorState(offset, limit, null, paramsHash);
// Pass a null random seed for the legacy case - we don't actually store a seed value and
// this is good enough for most use cases.
CursorState baseState = new CursorState(offset, limit, null, paramsHash, null);
List<Link> links = linksBuilder.build(new LinksBuilder.Context(
PAGE_PATH, FACET_PATH, "", offset, limit, page.getTotalElements(), baseState));
return BrowsePage.of(page.getContent(), offset, limit, page.getTotalElements(), cursorCodec.encode(baseState), links);
}
private Specification<BookEntity> withSort(Specification<BookEntity> filter, List<SortTerm> sortTerms, Long userId) {
private Specification<BookEntity> withSort(Specification<BookEntity> filter, List<SortTerm> sortTerms, Long userId, Integer randomSeed) {
return (root, query, cb) -> {
if (query.getResultType() != Long.class && query.getResultType() != long.class) {
query.orderBy(sortRegistry.registry().toOrders(sortTerms, root, query, cb, userId));
query.orderBy(sortRegistry.registry().toOrders(sortTerms, root, query, cb, userId, randomSeed));
}
return filter.toPredicate(root, query, cb);
};
@@ -46,6 +46,7 @@ public class BookSortRegistry {
registry.register(field, progressField(field));
}
registry.register("readingProgress", readingProgress());
registry.register("random", random());
return registry;
}
@@ -75,6 +76,32 @@ public class BookSortRegistry {
};
}
private static SortOrderBuilder<BookEntity> random() {
return ctx -> {
CriteriaBuilder cb = ctx.cb();
// If the random seed isn't set (null) we hard code it to 0. This means
// that the "randomness" will never change until a new book is added.
// This is a decent enough fallback because:
// * We don't care if this isn't _that_ random, just that it's good enough
// * It's a reasonable approach for most folks use cases.
int randomSeed = ctx.randomSeed() == null ? 0 : ctx.randomSeed();
// This is hard coded to the mariadb "RAND" function. This has poor performance
// on larger tables but gives a consistent sort every time. This is done by
// seeding the random number generator which we use for ordering.
//
// While just the seed for the pagination "session" is sufficient for MariaDB,
// H2 will emit the same number every row - so we have to include the current ID.
Expression<Double> random = cb.function(
"RAND",
Double.class,
cb.sum(cb.literal(randomSeed), ctx.root().get("id"))
);
return List.of(order(ctx, random));
};
}
private static Expression<Float> greatestOf(CriteriaBuilder cb, Expression<Float> a, Expression<Float> b) {
return cb.<Float>selectCase()
.when(cb.greaterThanOrEqualTo(a, b), a)
@@ -13,14 +13,14 @@ class CursorCodecTest {
@Test
void roundTripsBasicState() {
CursorState state = new CursorState(80, 40, "seriesName,-seriesNumber", "abc123def456");
CursorState state = new CursorState(80, 40, "seriesName,-seriesNumber", "abc123def456", 123);
CursorState decoded = codec.decode(codec.encode(state));
assertEquals(state, decoded);
}
@Test
void producesUrlSafeUnpaddedToken() {
CursorState state = new CursorState(12345, 40, "title", "hash00000000");
CursorState state = new CursorState(12345, 40, "title", "hash00000000", 0);
String cursor = codec.encode(state);
assertEquals(cursor.indexOf('+'), -1);
assertEquals(cursor.indexOf('/'), -1);
@@ -41,13 +41,13 @@ class CursorCodecTest {
@Test
void verifyParamsMatchPassesOnEqualHash() {
CursorState state = new CursorState(0, 20, "title", "samehash0000");
CursorState state = new CursorState(0, 20, "title", "samehash0000", 0);
assertDoesNotThrow(() -> codec.verifyParamsMatch(state, "samehash0000"));
}
@Test
void verifyParamsMatchThrowsOnDifferentHash() {
CursorState state = new CursorState(0, 20, "title", "samehash0000");
CursorState state = new CursorState(0, 20, "title", "samehash0000", 0);
assertThrows(APIException.class, () -> codec.verifyParamsMatch(state, "otherhash000"));
}
}
@@ -16,7 +16,7 @@ class LinksBuilderTest {
private final LinksBuilder builder = new LinksBuilder(codec);
private LinksBuilder.Context context(long offset, int limit, long total, String preservedQuery) {
CursorState base = new CursorState(offset, limit, "title", "hash00000000");
CursorState base = new CursorState(offset, limit, "title", "hash00000000", 0);
return new LinksBuilder.Context("/api/v1/books/page", "/api/v1/books/facets", preservedQuery, offset, limit, total, base);
}
@@ -127,7 +127,7 @@ class LinksBuilderTest {
void nullPreservedQueryStillProducesValidLinks() {
List<Link> links = builder.build(new LinksBuilder.Context(
"/api/v1/books/page", "/api/v1/books/facets", null, 0, 20, 5,
new CursorState(0, 20, "title", "hash00000000")));
new CursorState(0, 20, "title", "hash00000000", 0)));
assertTrue(hasRel(links, "self"));
Link self = withRel(links, "self");
assertTrue(self.href().startsWith("/api/v1/books/page?cursor="));
@@ -7,6 +7,8 @@ import jakarta.persistence.criteria.Root;
import org.booklore.exception.APIException;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
@@ -18,6 +20,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
@@ -30,6 +33,12 @@ class SortRegistryTest {
@Mock
private CriteriaBuilder cb;
@Mock
SortOrderBuilder<Object> mockSortOrderBuilder;
@Captor
ArgumentCaptor<SortContext<Object>> sortContextCaptor;
@Test
void registersAndExposesKeysInOrder() {
SortRegistry<Object> registry = new SortRegistry<>()
@@ -49,32 +58,44 @@ class SortRegistryTest {
.register("id", ctx -> List.of(idOrder));
List<Order> orders = registry.toOrders(
List.of(new SortTerm("title", false), new SortTerm("id", false)), root, query, cb, 7L);
List.of(new SortTerm("title", false), new SortTerm("id", false)),
root,
query,
cb,
7L,
null
);
assertEquals(List.of(titleOrder, idOrder), orders);
}
@Test
void passesDirectionAndUserIdToBuilder() {
boolean[] sawDescending = {false};
Long[] sawUser = {null};
SortRegistry<Object> registry = new SortRegistry<>().register("title", ctx -> {
sawDescending[0] = ctx.descending();
sawUser[0] = ctx.userId();
return List.of(mock(Order.class));
});
void passesParametersToBuilder() {
SortRegistry<Object> registry = new SortRegistry<>().register("title", mockSortOrderBuilder);
registry.toOrders(List.of(new SortTerm("title", true)), root, query, cb, 42L);
registry.toOrders(List.of(new SortTerm("title", true)), root, query, cb, 42L, 123);
assertTrue(sawDescending[0]);
assertEquals(42L, sawUser[0]);
verify(mockSortOrderBuilder).toOrders(sortContextCaptor.capture());
var context = sortContextCaptor.getValue();
assertTrue(context.descending());
assertEquals(42L, context.userId());
assertEquals(123, context.randomSeed());
}
@Test
void unknownKeyThrows() {
SortRegistry<Object> registry = new SortRegistry<>().register("id", ascOn("id"));
assertThrows(APIException.class,
() -> registry.toOrders(List.of(new SortTerm("bogus", false)), root, query, cb, null));
() -> registry.toOrders(
List.of(new SortTerm("bogus", false)),
root,
query,
cb,
null,
null
));
}
private SortOrderBuilder<Object> ascOn(String attribute) {
@@ -152,7 +152,7 @@ class BookBrowseRegistryTest {
private List<Long> sortedIds(String sortString, Long userId) {
List<SortTerm> terms = SortParser.parse(sortString, sortRegistry.registry().keys());
Specification<BookEntity> spec = (root, query, cb) -> {
query.orderBy(sortRegistry.registry().toOrders(terms, root, query, cb, userId));
query.orderBy(sortRegistry.registry().toOrders(terms, root, query, cb, userId, null));
return cb.conjunction();
};
return bookRepository.findAll(spec).stream().map(BookEntity::getId).toList();
@@ -4,6 +4,7 @@ import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import org.booklore.BookloreApplication;
import org.booklore.browse.BrowsePage;
import org.booklore.browse.CursorCodec;
import org.booklore.browse.Link;
import org.booklore.exception.APIException;
import org.booklore.config.security.service.AuthenticationService;
@@ -205,6 +206,17 @@ class BookBrowseServiceTest {
.doesNotContainAnyElementsOf(page0.content().stream().map(Book::getId).toList());
}
@Test
void generatesRandomSeedForCursor() {
var page = browse("random", null, null, null, 0, 2);
String cursor = page.page().cursor();
var codec = new CursorCodec();
var values = codec.decode(cursor);
assertThat(values.randomSeed()).isNotNull();
}
@Test
void cursorWithConflictingFacetsIsRejected() {
book("Alpha", List.of("Horror"));
@@ -215,13 +227,28 @@ class BookBrowseServiceTest {
.hasMessageContaining("does not match");
}
@Test
void randomSortIsSameWithSameCursor() {
for (int i = 0; i < 5; i++) {
book(String.format("Book%02d", i), List.of());
}
em.flush();
var response = browse("random", null, null, null, 0, 20);
var ids = response.content().stream().map(Book::getId).toList();
assertThat(browse("random", null, null, response.page().cursor(), 0, 20)
.content().stream().map(Book::getId).toList()).isEqualTo(ids);
assertThat(browse("random", null, null, response.page().cursor(), 0, 20)
.content().stream().map(Book::getId).toList()).isEqualTo(ids);
}
@Test
void deferredSortKeyIsRejected() {
book("Alpha", List.of());
em.flush();
assertThatThrownBy(() -> browse("random", null, null, null, 0, 20))
.isInstanceOfSatisfying(APIException.class, e -> assertThat(e.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST))
.hasMessageContaining("Unknown sort key");
assertThatThrownBy(() -> browse("fileSizeKb", null, null, null, 0, 20))
.isInstanceOfSatisfying(APIException.class, e -> assertThat(e.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST))
.hasMessageContaining("Unknown sort key");