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)