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
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ public class StardustPlayer {
private final Map<String, PlayerSetting> settings;
private Instant createdAt;
private Instant updatedAt;
private long version;

public StardustPlayer(UUID id, UUID uniqueId, String name, Instant createdAt, Instant updatedAt) {
this(id, uniqueId, name, new HashMap<>(), createdAt, updatedAt);
Expand All @@ -46,18 +47,43 @@ public StardustPlayer(UUID id,
Map<String, PlayerSetting> settings,
Instant createdAt,
Instant updatedAt) {
this(id, uniqueId, name, settings, createdAt, updatedAt, 0L);
}

public StardustPlayer(UUID id,
UUID uniqueId,
String name,
Map<String, PlayerSetting> settings,
Instant createdAt,
Instant updatedAt,
long version) {
this.id = id;
this.uniqueId = Objects.requireNonNull(uniqueId, "uuid");
this.name = Objects.requireNonNull(name, "name");
this.settings = Objects.requireNonNull(settings, "settings");
this.createdAt = Objects.requireNonNull(createdAt, "createdAt");
this.updatedAt = Objects.requireNonNull(updatedAt, "updatedAt");
this.version = version;
}

public UUID getId() {
return id;
}

/**
* The database version this copy was loaded with or last written as. Writes are only accepted
* while it matches the stored version.
*
* @return the version of the stored player data
*/
public long getVersion() {
return version;
}

public void setVersion(long version) {
this.version = version;
}

public void setUniqueId(UUID uniqueId) {
this.uniqueId = uniqueId;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,11 @@ private void persist(StardustPlayer player) {
cache.computeIfPresent(uuid, (key, value) -> Optional.of(persisted));
}
}
} catch (StalePlayerDataException e) {
LOGGER.warn("Dropped stale write of player {}: copy version {}, stored version {}",
uuid, e.getModelVersion(), e.getStoredVersion());
StardustPlayer current = delegate.findById(uuid);
cache.computeIfPresent(uuid, (key, value) -> Optional.ofNullable(current));
} catch (RuntimeException e) {
LOGGER.error("Failed to persist player {}", uuid, e);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,15 @@
import net.onelitefeather.stardust.api.player.StardustPlayer;
import net.onelitefeather.stardust.user.User;
import net.onelitefeather.stardust.util.PlayerUtil;
import jakarta.persistence.OptimisticLockException;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.StaleObjectStateException;
import org.hibernate.Transaction;
import org.hibernate.exception.ConstraintViolationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

Expand Down Expand Up @@ -60,6 +63,11 @@ public StardustPlayer findById(UUID playerUuid) {
}
}

/**
* Inserts a new player, or updates an existing one only if the stored version equals the version of the given copy.
*
* @throws StalePlayerDataException if the stored player was changed after the copy was loaded
*/
@Override
public void saveOrUpdate(StardustPlayer player) {
Transaction transaction;
Expand All @@ -70,19 +78,46 @@ public void saveOrUpdate(StardustPlayer player) {
var entity = query.uniqueResult();

if (player.getId() == null) {
if (entity != null) {
transaction.rollback();
LOGGER.warn("Player {} already exists, keeping the stored data", player.getUniqueId());
return;
}
session.persist(mapToEntity(player));
} else {
if (entity.getVersion() != player.getVersion()) {
transaction.rollback();
throw new StalePlayerDataException(player.getUniqueId(), player.getVersion(), entity.getVersion());
}
keepPlayerNameUpdated(player, entity);
entity.setSettings(player.getSettings());
session.merge(entity);
}

transaction.commit();
if (player.getId() != null) {
player.setVersion(entity.getVersion());
}
} catch (StalePlayerDataException e) {
throw e;
} catch (OptimisticLockException | StaleObjectStateException e) {
throw new StalePlayerDataException(player.getUniqueId(), player.getVersion(), -1L);
} catch (Exception e) {
if (player.getId() == null && hasCause(e, ConstraintViolationException.class) && playerExists(player.getUniqueId())) {
LOGGER.warn("Player {} was inserted concurrently, keeping the stored data", player.getUniqueId());
return;
}
LOGGER.atError().setMessage("Failed to open a session to save or update player: {}").addArgument(player.getName()).setCause(e).log();
}
}

private static boolean hasCause(Throwable throwable, Class<? extends Throwable> type) {
for (Throwable current = throwable; current != null; current = current.getCause()) {
if (type.isInstance(current)) return true;
}
return false;
}

@Override
public void delete(StardustPlayer player) {

Expand Down Expand Up @@ -139,7 +174,8 @@ private StardustPlayer mapToModel(StardustPlayerEntity entity) {
entity.getName(),
entity.getSettings(),
entity.getCreatedAt(),
entity.getUpdatedAt());
entity.getUpdatedAt(),
entity.getVersion());
}

private StardustPlayerEntity mapToEntity(StardustPlayer model) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package net.onelitefeather.stardust.service;

import java.util.UUID;

/**
* Thrown when a player is written with a version that is no longer the stored version, i.e. the
* stored data was changed by another write (for example on another server) after the copy was loaded.
*/
public class StalePlayerDataException extends RuntimeException {

private final UUID playerUuid;
private final long modelVersion;
private final long storedVersion;

/**
* @param playerUuid the player whose write was rejected
* @param modelVersion the version the rejected copy was loaded with
* @param storedVersion the version currently stored, or -1 if it is not known
*/
public StalePlayerDataException(UUID playerUuid, long modelVersion, long storedVersion) {
super("Stale data for player " + playerUuid + ": model version " + modelVersion + ", stored version " + storedVersion);
this.playerUuid = playerUuid;
this.modelVersion = modelVersion;
this.storedVersion = storedVersion;
}

public UUID getPlayerUuid() {
return playerUuid;
}

public long getModelVersion() {
return modelVersion;
}

public long getStoredVersion() {
return storedVersion;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -299,6 +299,24 @@ void loadReadsDirectlyWhenExecutorIsClosed() {
assertTrue(loaded.isPresent(), "load must still read from the delegate when the executor is closed");
}

@Test
void staleWriteReplacesCachedEntryWithDatabaseStateAndLaterWritesStillRun() {
givenService();
online.add(PLAYER_ID);
online.add(OTHER_ID);
delegate.store(player(PLAYER_ID, "Database", UUID.randomUUID()));
delegate.staleNextSave = true;

service.saveOrUpdate(player(PLAYER_ID, "Stale", UUID.randomUUID()));
service.saveOrUpdate(player(OTHER_ID, "Alex", UUID.randomUUID()));
writer.runAll();

assertEquals("Database", service.findById(PLAYER_ID).getName(),
"a conflict must replace the cached entry with the database state");
assertEquals(2, delegate.saveCalls, "the write of another player must still run after a conflict");
assertEquals("Alex", delegate.stored.get(OTHER_ID).getName(), "the other player's write must be persisted");
}

/** Hand-written delegate backed by a map; counts calls. */
static final class FakeDelegate implements StardustPlayerService {
final Map<UUID, StardustPlayer> stored = new HashMap<>();
Expand All @@ -307,6 +325,7 @@ static final class FakeDelegate implements StardustPlayerService {
int deleteCalls;
int migrateCalls;
boolean failNextSave;
boolean staleNextSave;

void store(StardustPlayer player) {
stored.put(player.getUniqueId(), player);
Expand Down Expand Up @@ -335,6 +354,10 @@ public void saveOrUpdate(StardustPlayer player) {
failNextSave = false;
throw new IllegalStateException("simulated database failure");
}
if (staleNextSave) {
staleNextSave = false;
throw new StalePlayerDataException(player.getUniqueId(), player.getVersion(), 1L);
}
var id = player.getId() == null ? UUID.randomUUID() : player.getId();
stored.put(player.getUniqueId(), new StardustPlayer(id, player.getUniqueId(), player.getName(),
new HashMap<>(player.getSettings()), player.getCreatedAt(), player.getUpdatedAt()));
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
package net.onelitefeather.stardust.service;

import net.onelitefeather.stardust.api.player.StardustPlayer;
import net.onelitefeather.stardust.api.player.setting.PlayerSetting;
import net.onelitefeather.stardust.persistence.GsonFormatMapper;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.MappingSettings;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import java.nio.file.Path;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.UUID;

import static org.junit.jupiter.api.Assertions.*;

class DefaultStardustPlayerServiceVersionTest {

private static final Path CONFIG_PATH = Path.of("src/test/resources/test-connection.cfg.xml");
private static final UUID PLAYER_ID = UUID.fromString("df7c66a6-7876-44c2-9abd-9bd33f7d3d9e");
private static final Instant FIXED_TIME = Instant.EPOCH;

private SessionFactory sessionFactory;
private DefaultStardustPlayerService service;

@BeforeEach
void openFreshDatabase() {
Properties properties = new Properties();
properties.put(MappingSettings.JSON_FORMAT_MAPPER, new GsonFormatMapper());
sessionFactory = new Configuration()
.configure()
.configure(CONFIG_PATH.toFile())
.setProperty("connection.url", "jdbc:h2:mem:" + UUID.randomUUID() + ";DB_CLOSE_DELAY=-1;MODE=PostgreSQL")
.addProperties(properties)
.buildSessionFactory();
service = new DefaultStardustPlayerService(sessionFactory);
}

@AfterEach
void closeDatabase() {
sessionFactory.close();
}

private static StardustPlayer newPlayer(String name, String vanished) {
Map<String, PlayerSetting> settings = new HashMap<>();
settings.put("vanished", new PlayerSetting(vanished, 1, FIXED_TIME));
return new StardustPlayer(null, PLAYER_ID, name, settings, FIXED_TIME, FIXED_TIME);
}

private static void setVanished(StardustPlayer player, String value) {
player.getSettings().put("vanished", new PlayerSetting(value, 1, FIXED_TIME));
}

private static String vanished(StardustPlayer player) {
return player.getSettings().get("vanished").value();
}

@Test
void staleUpdateThrowsAndLeavesStoredRowUnchanged() {
service.saveOrUpdate(newPlayer("Steve", "false"));
var stale = service.findById(PLAYER_ID);
var fresh = service.findById(PLAYER_ID);
setVanished(fresh, "true");
service.saveOrUpdate(fresh);

setVanished(stale, "stale");

assertThrows(StalePlayerDataException.class, () -> service.saveOrUpdate(stale),
"an update based on an outdated version must be rejected");
var stored = service.findById(PLAYER_ID);
assertEquals("true", vanished(stored), "the rejected write must not change the stored settings");
assertEquals(1, stored.getVersion(), "the rejected write must not change the stored version");
}

@Test
void matchingVersionUpdateSucceedsAndAdvancesModelVersion() {
service.saveOrUpdate(newPlayer("Steve", "false"));
var model = service.findById(PLAYER_ID);
setVanished(model, "true");

service.saveOrUpdate(model);

assertEquals(1, model.getVersion(), "the model must carry the new version after a successful update");
assertEquals(1, service.findById(PLAYER_ID).getVersion(), "the stored version must have advanced");
}

@Test
void consecutiveUpdatesThroughSameModelBothSucceed() {
service.saveOrUpdate(newPlayer("Steve", "false"));
var model = service.findById(PLAYER_ID);

setVanished(model, "true");
service.saveOrUpdate(model);
model.getSettings().put("allow_flight", new PlayerSetting("true", 1, FIXED_TIME));
service.saveOrUpdate(model);

var stored = service.findById(PLAYER_ID);
assertEquals(2, stored.getVersion(), "both updates must have been stored");
assertEquals("true", vanished(stored));
assertTrue(stored.getSettings().containsKey("allow_flight"), "the second update must be stored");
}

@Test
void insertingExistingUuidKeepsStoredRowWithoutDuplicate() {
service.saveOrUpdate(newPlayer("Steve", "false"));

service.saveOrUpdate(newPlayer("Alex", "true"));

assertEquals(1, service.findAll(10).size(), "a second insert for the same UUID must not create a duplicate row");
var stored = service.findById(PLAYER_ID);
assertEquals("Steve", stored.getName(), "the existing row must be loaded unchanged");
assertEquals(0, stored.getVersion(), "the existing row must keep its version");
}

@Test
void consecutiveCachedWritesOfOnlinePlayerBothPersist() {
var writer = new CachingStardustPlayerServiceTest.ManualExecutor();
writer.runOnExecute = true;
Set<UUID> online = Set.of(PLAYER_ID);
var cache = new CachingStardustPlayerService(service, writer, online::contains, () -> online);

cache.saveOrUpdate(newPlayer("Steve", "false"));
var model = cache.findById(PLAYER_ID);
setVanished(model, "true");
cache.saveOrUpdate(model);
model.getSettings().put("allow_flight", new PlayerSetting("true", 1, FIXED_TIME));
cache.saveOrUpdate(model);

var stored = service.findById(PLAYER_ID);
assertEquals(2, stored.getVersion(), "two consecutive writes of the same online player must both succeed");
assertTrue(stored.getSettings().containsKey("allow_flight"), "the second write must be stored");
}

@Test
void staleCachedWriteIsDroppedAndCacheReloadsDatabaseState() {
service.saveOrUpdate(newPlayer("Steve", "false"));
Set<UUID> online = Set.of(PLAYER_ID);
var writer = new CachingStardustPlayerServiceTest.ManualExecutor();
writer.runOnExecute = true;
var cache = new CachingStardustPlayerService(service, writer, online::contains, () -> online);
var cached = cache.findById(PLAYER_ID);

var otherServer = service.findById(PLAYER_ID);
setVanished(otherServer, "true");
service.saveOrUpdate(otherServer);

setVanished(cached, "stale");
cache.saveOrUpdate(cached);

var current = cache.findById(PLAYER_ID);
assertEquals("true", vanished(current), "the cache must hold the database state after a conflict");
assertEquals(1, current.getVersion(), "the cached state must carry the database version");

setVanished(current, "false");
cache.saveOrUpdate(current);
assertEquals(2, service.findById(PLAYER_ID).getVersion(), "writes after a conflict must still be stored");
}
}
Loading