54 lines
2.1 KiB
Java
54 lines
2.1 KiB
Java
package ru.mtusi.messenger.util;
|
|
|
|
import ru.mtusi.messenger.exception.InvalidRequestException;
|
|
|
|
import java.nio.charset.StandardCharsets;
|
|
import java.time.OffsetDateTime;
|
|
import java.util.Base64;
|
|
import java.util.UUID;
|
|
|
|
/**
|
|
* Кодирует/декодирует opaque cursor для keyset-пагинации.
|
|
*
|
|
* Формат (внутри base64url): scope | createdAt.toString() | uuid
|
|
* scope — например "chat:<chat_id>", привязывает курсор к ресурсу
|
|
* createdAt — ISO-8601 строкa UTC с наносекундной точностью
|
|
* uuid — id последнего элемента
|
|
*
|
|
* Клиент видит только base64-строку и не должен её интерпретировать.
|
|
*/
|
|
public final class CursorCodec {
|
|
|
|
private CursorCodec() {}
|
|
|
|
public record Cursor(String scope, OffsetDateTime createdAt, UUID id) {}
|
|
|
|
public static String encode(String scope, OffsetDateTime createdAt, UUID id) {
|
|
String raw = scope + "|" + createdAt.toString() + "|" + id;
|
|
return Base64.getUrlEncoder().withoutPadding()
|
|
.encodeToString(raw.getBytes(StandardCharsets.UTF_8));
|
|
}
|
|
|
|
public static Cursor decode(String encoded, String expectedScope) {
|
|
try {
|
|
String raw = new String(
|
|
Base64.getUrlDecoder().decode(encoded),
|
|
StandardCharsets.UTF_8
|
|
);
|
|
String[] parts = raw.split("\\|", 3);
|
|
if (parts.length != 3) {
|
|
throw new InvalidRequestException("Invalid cursor");
|
|
}
|
|
if (!parts[0].equals(expectedScope)) {
|
|
throw new InvalidRequestException("Cursor belongs to another resource");
|
|
}
|
|
OffsetDateTime createdAt = OffsetDateTime.parse(parts[1]);
|
|
UUID id = UUID.fromString(parts[2]);
|
|
return new Cursor(parts[0], createdAt, id);
|
|
} catch (InvalidRequestException e) {
|
|
throw e;
|
|
} catch (Exception e) {
|
|
throw new InvalidRequestException("Invalid cursor");
|
|
}
|
|
}
|
|
} |