This commit is contained in:
2026-11-27 01:40:30 +00:00
parent 16aeaa36fb
commit eb9647e4a0
63 changed files with 7975 additions and 3 deletions
@@ -0,0 +1,438 @@
package net.wowmine.stickers;
import com.google.gson.JsonParser;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.PosixFileAttributeView;
import java.nio.file.attribute.PosixFilePermissions;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.zip.GZIPOutputStream;
import javax.imageio.ImageIO;
import net.wowmine.stickers.ChatHistory.Audience;
import net.wowmine.stickers.ChatHistory.Draft;
import net.wowmine.stickers.ChatHistory.Entry;
import net.wowmine.stickers.ChatHistory.Kind;
import net.wowmine.stickers.ChatHistory.Page;
import net.wowmine.stickers.ChatHistory.Query;
/** Real temporary SQLite databases; no server, cache, network, or injected storage implementation. */
public final class ChatArchiveTest {
private static final UUID ALICE = UUID.fromString("00000000-0000-0000-0000-000000000001");
private static final UUID BOB = UUID.fromString("00000000-0000-0000-0000-000000000002");
private static final ZoneId ZONE = ZoneId.of("Europe/Moscow");
private static final String HEADER = "[25Nov2026 12:34:56.789] [Server thread/INFO] "
+ "[net.minecraft.server.MinecraftServer/]: ";
private ChatArchiveTest() {}
public static void main(String[] arguments) throws IOException, SQLException {
try (var fixture = new Fixture()) {
walksUnlimitedHistoryWithCompositeCursors(fixture.root.resolve("walk"));
keepsByteLimitedPagesNavigable(fixture.root.resolve("budget"));
enforcesAudienceForRowsAndAttachments(fixture.root.resolve("acl"));
persistsDeduplicatedMediaWithoutSourceCache(fixture.root.resolve("persist"));
rejectsInvalidMediaWithoutPartialWrites(fixture.root.resolve("invalid"));
rollsBackMetadataMediaAndAudienceOnSqlFailure(fixture.root.resolve("rollback"));
restrictsOnlyArchiveDirectoryPermissions(fixture.root.resolve("permissions"));
importsOnlyWhitelistedPublicChatOnce(fixture.root.resolve("logs"));
resumesPartialMigrationWithoutDuplicatesOrNewSessions(fixture.root.resolve("resume"));
}
System.out.println("CHAT_ARCHIVE_PASS");
}
private static void walksUnlimitedHistoryWithCompositeCursors(Path root) throws IOException, SQLException {
var expected = new ArrayList<Entry>();
var aliceEntries = new ArrayList<Entry>();
try (var archive = new ChatArchive(root)) {
for (int index = 0; index < 17_013; index++) {
// Insertion order differs from chronology; groups of seven exercise cursor ID ties.
Draft draft = text(946_684_800_000L + ((17_012 - index) / 7) * 1000L, "row " + index);
Audience audience = index % 251 == 0 ? ChatHistory.PUBLIC
: new Audience(false, index % 509 == 0 ? Set.of(ALICE, BOB) : Set.of(BOB));
Entry entry = new Entry(archive.append(draft, audience, new byte[0]), draft);
expected.add(entry);
if (audience.publicMessage() || audience.recipients().contains(ALICE)) {
aliceEntries.add(entry);
}
}
Draft oldest = text(0, "oldest");
Entry first = new Entry(archive.append(oldest, ChatHistory.PUBLIC, new byte[0]), oldest);
expected.add(first);
aliceEntries.add(first);
Comparator<Entry> chronological = Comparator.comparingLong((Entry entry) -> entry.message().time())
.thenComparingLong(Entry::id);
expected.sort(chronological);
aliceEntries.sort(chronological);
equal(expected, walk(archive, BOB, true));
equal(expected, walk(archive, BOB, false));
equal(aliceEntries, walk(archive, ALICE, true));
equal(aliceEntries, walk(archive, ALICE, false));
equal(expected.subList(0, 50), archive.page(BOB, Query.earliest()).entries());
equal(expected.subList(expected.size() - 50, expected.size()), archive.page(BOB, Query.latest()).entries());
long time = expected.get(8000).message().time();
var atDate = archive.page(BOB, new Query(ChatHistory.Direction.AT_DATE, time, 0));
List<Entry> beforeDate = expected.stream().filter(entry -> entry.message().time() <= time).toList();
equal(beforeDate.subList(beforeDate.size() - 50, beforeDate.size()), atDate.entries());
equal(true, atDate.hasOlder());
equal(true, atDate.hasNewer());
Page afterEnd = archive.page(ALICE, Query.after(aliceEntries.getLast().cursor()));
equal(List.of(), afterEnd.entries());
equal(true, afterEnd.hasOlder());
equal(false, afterEnd.hasNewer());
Page beforeStart = archive.page(ALICE, Query.before(aliceEntries.getFirst().cursor()));
equal(List.of(), beforeStart.entries());
equal(false, beforeStart.hasOlder());
equal(true, beforeStart.hasNewer());
}
}
private static List<Entry> walk(ChatArchive archive, UUID requester, boolean forward) throws SQLException {
var result = new ArrayList<Entry>();
Page page = archive.page(requester, forward ? Query.earliest() : Query.latest());
while (true) {
if (page.entries().isEmpty()) {
throw new AssertionError("Nonempty history walk reached empty window");
}
if (forward) {
equal(!result.isEmpty(), page.hasOlder());
result.addAll(page.entries());
} else {
equal(!result.isEmpty(), page.hasNewer());
result.addAll(0, page.entries());
}
boolean more = forward ? page.hasNewer() : page.hasOlder();
if (!more) {
break;
}
if (result.size() > 18_000) {
throw new AssertionError("Cursor walk repeats entries");
}
page = archive.page(requester, forward ? Query.after(page.entries().getLast().cursor())
: Query.before(page.entries().getFirst().cursor()));
}
return result;
}
private static void keepsByteLimitedPagesNavigable(Path root) throws IOException, SQLException {
try (var archive = new ChatArchive(root)) {
var expected = new ArrayList<Entry>();
for (int index = 0; index < 11; index++) {
Draft draft = text(index, "\u00e9".repeat(32_750));
expected.add(new Entry(archive.append(draft, ChatHistory.PUBLIC, new byte[0]), draft));
}
Page earliest = archive.page(ALICE, Query.earliest());
equal(3, earliest.entries().size());
equal(false, earliest.hasOlder());
equal(true, earliest.hasNewer());
Page latest = archive.page(ALICE, Query.latest());
equal(3, latest.entries().size());
equal(true, latest.hasOlder());
equal(false, latest.hasNewer());
equal(expected, walk(archive, ALICE, true));
equal(expected, walk(archive, ALICE, false));
}
}
private static void enforcesAudienceForRowsAndAttachments(Path root) throws IOException, SQLException {
byte[] voice = voice();
try (var archive = new ChatArchive(root)) {
Draft draft = media(10, Kind.VOICE, voice, 2);
long privateId = archive.append(draft, new Audience(false, Set.of(ALICE)), voice);
for (Query query : List.of(Query.earliest(), Query.latest(),
new Query(ChatHistory.Direction.AT_DATE, 10, 0),
Query.before(new ChatHistory.Cursor(20, Long.MAX_VALUE)),
Query.after(new ChatHistory.Cursor(0, 1)))) {
equal(new Page(List.of(), false, false), archive.page(BOB, query));
}
long publicId = archive.append(text(20, "public"), ChatHistory.PUBLIC, new byte[0]);
equal(List.of(publicId), ids(archive.page(BOB, Query.earliest())));
equal(List.of(privateId, publicId), ids(archive.page(ALICE, Query.earliest())));
equal(false, archive.page(BOB, Query.earliest()).hasOlder());
Page unauthorizedDate = archive.page(BOB, new Query(ChatHistory.Direction.AT_DATE, 10, 0));
equal(List.of(), unauthorizedDate.entries());
equal(false, unauthorizedDate.hasOlder());
equal(true, unauthorizedDate.hasNewer());
equal(true, archive.attachment(BOB, privateId).isEmpty());
equal(true, archive.attachment(BOB, publicId).isEmpty());
equal(true, archive.attachment(BOB, Long.MAX_VALUE).isEmpty());
equal(Kind.VOICE, archive.attachment(ALICE, privateId).orElseThrow().kind());
bytesEqual(voice, archive.attachment(ALICE, privateId).orElseThrow().bytes());
}
}
private static void persistsDeduplicatedMediaWithoutSourceCache(Path root) throws IOException, SQLException {
byte[] sticker = png(2);
Path cache = root.resolve("source-cache.png");
Files.createDirectories(root);
Files.write(cache, sticker);
long id;
long restrictedId;
long voiceId;
byte[] voice = voice();
try (var archive = new ChatArchive(root)) {
Draft draft = media(100, Kind.STICKER, Files.readAllBytes(cache), 2);
id = archive.append(draft, ChatHistory.PUBLIC, sticker);
restrictedId = archive.append(draft, new Audience(false, Set.of(ALICE)), sticker);
voiceId = archive.append(media(101, Kind.VOICE, voice, 2), new Audience(false, Set.of(ALICE)), voice);
equal(2L, count(root, "media"));
}
Files.delete(cache);
try (var archive = new ChatArchive(root)) {
var attachment = archive.attachment(BOB, id).orElseThrow();
equal(Kind.STICKER, attachment.kind());
equal(2, attachment.frames());
bytesEqual(sticker, attachment.bytes());
byte[] copy = attachment.bytes();
copy[0] ^= 1;
bytesEqual(sticker, attachment.bytes());
equal(List.of(id), ids(archive.page(BOB, Query.latest())));
equal(true, archive.attachment(BOB, restrictedId).isEmpty());
equal(true, archive.attachment(BOB, voiceId).isEmpty());
bytesEqual(voice, archive.attachment(ALICE, voiceId).orElseThrow().bytes());
}
}
private static void rejectsInvalidMediaWithoutPartialWrites(Path root) throws IOException, SQLException {
try (var archive = new ChatArchive(root)) {
byte[] png = png(1);
byte[] voice = voice();
rejects(IllegalArgumentException.class, () -> archive.append(text(0, "text"),
ChatHistory.PUBLIC, new byte[] {1}));
rejects(IllegalArgumentException.class, () -> archive.append(
new Draft(0, ALICE, "Alice", Kind.STICKER, "{}", "0".repeat(64), 1), ChatHistory.PUBLIC, png));
rejects(IOException.class, () -> archive.append(media(0, Kind.STICKER, png, 2), ChatHistory.PUBLIC, png));
rejects(IOException.class, () -> archive.append(media(0, Kind.VOICE, voice, 1), ChatHistory.PUBLIC, voice));
for (byte[] invalid : List.of(new byte[] {0, 0}, new byte[] {1, 1, 0}, new byte[] {0, 2, 1})) {
rejects(IOException.class, () -> archive.append(media(0, Kind.VOICE, invalid, 1), ChatHistory.PUBLIC, invalid));
}
byte[] tooLarge = new byte[ChatHistory.MEDIA_BYTES + 1];
rejects(IllegalArgumentException.class, () -> archive.append(
media(0, Kind.VOICE, tooLarge, 1), ChatHistory.PUBLIC, tooLarge));
equal(0L, count(root, "entries"));
equal(0L, count(root, "media"));
equal(0L, count(root, "recipients"));
long id = archive.append(media(1, Kind.VOICE, voice, 2), ChatHistory.PUBLIC, voice);
equal(List.of(id), ids(archive.page(ALICE, Query.latest())));
}
var closed = new ChatArchive(root);
closed.close();
rejects(SQLException.class, () -> closed.page(ALICE, Query.latest()));
}
private static void rollsBackMetadataMediaAndAudienceOnSqlFailure(Path root) throws IOException, SQLException {
try (var archive = new ChatArchive(root); Connection db = database(root)) {
execute(db, "CREATE TRIGGER fail_acl BEFORE INSERT ON recipients BEGIN SELECT RAISE(ABORT,'fixture ACL failure'); END");
byte[] voice = voice();
rejects(SQLException.class, () -> archive.append(media(1, Kind.VOICE, voice, 2),
new Audience(false, Set.of(ALICE, BOB)), voice));
equal(0L, count(root, "entries"));
equal(0L, count(root, "media"));
equal(0L, count(root, "recipients"));
execute(db, "DROP TRIGGER fail_acl");
long id = archive.append(media(1, Kind.VOICE, voice, 2), new Audience(false, Set.of(ALICE)), voice);
equal(List.of(id), ids(archive.page(ALICE, Query.earliest())));
equal(List.of(), ids(archive.page(BOB, Query.earliest())));
}
}
private static void importsOnlyWhitelistedPublicChatOnce(Path root) throws IOException, SQLException {
Path logs = Files.createDirectories(root.resolve("server-logs"));
String message = "quote \" literal {\"clickEvent\":{}} backslash \\\\";
List<String> lines = List.of(
HEADER + "<Alice> " + message,
HEADER + "[Not Secure] <Bob_2> second",
HEADER + "Alice whispers to Bob: secret",
HEADER + "[Alice -> Bob] secret",
HEADER + "[Admin] announcement",
HEADER + "<Alice> /say command",
HEADER + "<Name-With-Dash> invalid",
HEADER.replace("Server thread/INFO", "RCON Listener #1/INFO") + "<Alice> forged",
HEADER.replace("Server thread/INFO", "Async Chat Thread/INFO") + "<Alice> forged",
HEADER.replace("MinecraftServer/", "dedicated.DedicatedServer/") + "<Alice> forged",
HEADER.replace("INFO", "WARN") + "<Alice> forged",
HEADER.replace("25Nov", "31Nov") + "<Alice> invalid date",
HEADER + "<Alice> " + "x".repeat(100_000),
"continuation <Alice> untrusted",
HEADER + "<Alice> after oversized");
Files.write(logs.resolve("a.log"), lines);
gzip(logs.resolve("b.log.gz"), HEADER + "<Carol> compressed\n");
Files.writeString(logs.resolve("latest.log"), HEADER + "<Active> current server is still writing\n");
Files.writeString(logs.resolve("debug.log"), HEADER + "<Duplicate> verbose copy of public log\n");
Files.writeString(logs.resolve("ignore.txt"), HEADER + "<Ignored> ignored\n");
try (var archive = new ChatArchive(root.resolve("archive"))) {
equal(4, ArchiveLogImport.importOnce(archive, logs, ZONE));
var entries = archive.page(BOB, Query.earliest()).entries();
equal(List.of("Alice", "Bob_2", "Alice", "Carol"), entries.stream().map(entry -> entry.message().name()).toList());
equal(message, JsonParser.parseString(entries.getFirst().message().body())
.getAsJsonObject().get("text").getAsString());
equal(Set.of("text"), JsonParser.parseString(entries.getFirst().message().body()).getAsJsonObject().keySet());
equal(UUID.nameUUIDFromBytes("OfflinePlayer:Alice".getBytes(StandardCharsets.UTF_8)),
entries.getFirst().message().author());
equal(LocalDateTime.of(2026, 11, 25, 12, 34, 56, 789_000_000).atZone(ZONE).toInstant().toEpochMilli(),
entries.getFirst().message().time());
}
Files.writeString(logs.resolve("a.log"), HEADER + "<NewSession> already live\n");
try (var archive = new ChatArchive(root.resolve("archive"))) {
equal(0, ArchiveLogImport.importOnce(archive, logs, ZONE));
equal(4, archive.page(ALICE, Query.latest()).entries().size());
}
}
private static void resumesPartialMigrationWithoutDuplicatesOrNewSessions(Path root) throws IOException, SQLException {
Path logs = Files.createDirectories(root.resolve("logs"));
Path dbRoot = root.resolve("archive");
Files.writeString(logs.resolve("old.log"), HEADER + "<Alice> first\n" + HEADER + "<Bob> second\n");
try (var archive = new ChatArchive(dbRoot); Connection db = database(dbRoot)) {
execute(db, """
CREATE TRIGGER interrupt_import BEFORE INSERT ON entries WHEN NEW.name='Bob'
BEGIN SELECT RAISE(ABORT,'fixture migration interruption'); END
""");
rejects(SQLException.class, () -> ArchiveLogImport.importOnce(archive, logs, ZONE));
equal(List.of("Alice"), archive.page(ALICE, Query.latest()).entries().stream()
.map(entry -> entry.message().name()).toList());
execute(db, "DROP TRIGGER interrupt_import");
}
// Rotation/recompression preserves decompressed source identity; newly created sessions stay excluded.
gzip(logs.resolve("rotated.log.gz"), Files.readString(logs.resolve("old.log")));
Files.delete(logs.resolve("old.log"));
Files.writeString(logs.resolve("latest.log"), HEADER + "<NewSession> do not import\n");
try (var archive = new ChatArchive(dbRoot)) {
equal(1, ArchiveLogImport.importOnce(archive, logs, ZONE));
equal(List.of("Alice", "Bob"), archive.page(ALICE, Query.earliest()).entries().stream()
.map(entry -> entry.message().name()).toList());
equal(0, ArchiveLogImport.importOnce(archive, logs, ZONE));
}
}
private static Draft text(long time, String body) {
var component = new com.google.gson.JsonObject();
component.addProperty("text", body);
return new Draft(time, ALICE, "Alice", Kind.TEXT, component.toString(), "", 0);
}
private static void restrictsOnlyArchiveDirectoryPermissions(Path root) throws IOException, SQLException {
Files.createDirectories(root);
var parentPermissions = Files.getFileAttributeView(root, PosixFileAttributeView.class);
var before = parentPermissions == null ? Set.of() : parentPermissions.readAttributes().permissions();
Path archiveRoot = root.resolve("archive");
try (var archive = new ChatArchive(archiveRoot)) {
equal(List.of(), archive.page(ALICE, Query.latest()).entries());
var permissions = Files.getFileAttributeView(archiveRoot, PosixFileAttributeView.class);
if (permissions != null) {
equal(PosixFilePermissions.fromString("rwx------"), permissions.readAttributes().permissions());
equal(before, parentPermissions.readAttributes().permissions());
}
}
}
private static Draft media(long time, Kind kind, byte[] bytes, int frames) {
return new Draft(time, ALICE, "Alice", kind, "{\"text\":\"media\"}", ChatArchive.sha256(bytes), frames);
}
private static byte[] voice() {
return VoiceFrames.encode(List.of(new byte[] {1, 2}, new byte[] {3, 4, 5}));
}
private static byte[] png(int frames) throws IOException {
var image = new BufferedImage(Math.min(frames, 8) * 128,
((frames + Math.min(frames, 8) - 1) / Math.min(frames, 8)) * 128, BufferedImage.TYPE_INT_ARGB);
try (var output = new ByteArrayOutputStream()) {
if (!ImageIO.write(image, "png", output)) {
throw new IOException("No PNG writer");
}
return output.toByteArray();
}
}
private static void gzip(Path path, String text) throws IOException {
try (var output = new GZIPOutputStream(Files.newOutputStream(path))) {
output.write(text.getBytes(StandardCharsets.UTF_8));
}
}
private static Connection database(Path root) throws SQLException {
return DriverManager.getConnection("jdbc:sqlite:" + root.resolve("chat-archive.sqlite").toAbsolutePath());
}
private static long count(Path root, String table) throws SQLException {
try (Connection db = database(root); var sql = db.createStatement();
var row = sql.executeQuery("SELECT count(*) FROM " + table)) {
if (!row.next()) {
throw new SQLException("Missing count row");
}
return row.getLong(1);
}
}
private static void execute(Connection db, String statement) throws SQLException {
try (var sql = db.createStatement()) {
sql.execute(statement);
}
}
private static List<Long> ids(Page page) {
return page.entries().stream().map(Entry::id).toList();
}
private static void equal(Object expected, Object actual) {
if (!expected.equals(actual)) {
throw new AssertionError("Expected " + expected + ", got " + actual);
}
}
private static void bytesEqual(byte[] expected, byte[] actual) {
if (!Arrays.equals(expected, actual)) {
throw new AssertionError("Archive changed binary media");
}
}
private static void rejects(Class<? extends Exception> expected, Action action) throws IOException, SQLException {
try {
action.run();
} catch (IOException | SQLException | IllegalArgumentException error) {
if (expected.isInstance(error)) {
return;
}
throw error;
}
throw new AssertionError("Expected rejection: " + expected.getSimpleName());
}
@FunctionalInterface
private interface Action {
void run() throws IOException, SQLException;
}
private static final class Fixture implements AutoCloseable {
private final Path root;
private Fixture() throws IOException {
root = Files.createTempDirectory("wowmine-chat-archive-");
}
@Override
public void close() throws IOException {
try (var paths = Files.walk(root)) {
for (Path path : paths.sorted(Comparator.reverseOrder()).toList()) {
Files.delete(path);
}
}
}
}
}