57 lines
2.6 KiB
Java
57 lines
2.6 KiB
Java
package games.dmg.spigotignis;
|
|
|
|
import java.util.UUID;
|
|
import java.util.concurrent.CompletableFuture;
|
|
|
|
/** Buffers observed consumed throws until acknowledged by the persistence worker. */
|
|
public final class PearlProgress {
|
|
private final StateService states;
|
|
public PearlProgress(StateService states) { this.states = states; }
|
|
private static final class Buffer {
|
|
final long generation;
|
|
long count;
|
|
CompletableFuture<IgnisState> saving;
|
|
Buffer(long generation) { this.generation = generation; }
|
|
}
|
|
private final java.util.Map<UUID, Buffer> pending = new java.util.HashMap<>();
|
|
private Buffer buffer(UUID player) {
|
|
long generation = generation(states.snapshot(), player);
|
|
return pending.compute(player, (ignored, old) -> old == null || old.generation != generation ? new Buffer(generation) : old);
|
|
}
|
|
private static long generation(IgnisState state, UUID player) {
|
|
return state.players().getOrDefault(player, PlayerState.empty()).track(Track.DAGGER).generation();
|
|
}
|
|
public synchronized void record(UUID player) {
|
|
Buffer buffer = buffer(player);
|
|
buffer.count = Math.addExact(buffer.count, 1);
|
|
}
|
|
public synchronized CompletableFuture<Void> checkpointAll() {
|
|
return CompletableFuture.allOf(new java.util.ArrayList<>(pending.keySet()).stream()
|
|
.map(this::checkpoint).toArray(CompletableFuture<?>[]::new));
|
|
}
|
|
|
|
public synchronized CompletableFuture<IgnisState> checkpoint(UUID player) {
|
|
Buffer buffer = buffer(player);
|
|
if (buffer.saving != null) return buffer.saving.thenCompose(ignored -> checkpoint(player));
|
|
long count = buffer.count;
|
|
buffer.count = 0;
|
|
if (count == 0) {
|
|
pending.remove(player, buffer);
|
|
return CompletableFuture.completedFuture(states.snapshot());
|
|
}
|
|
var acknowledgement = new CompletableFuture<IgnisState>();
|
|
buffer.saving = acknowledgement;
|
|
states.update(state -> generation(state, player) == buffer.generation
|
|
? ProgressAdministration.progress(state, player, Track.DAGGER, count, true) : state)
|
|
.whenComplete((state, error) -> {
|
|
synchronized (this) {
|
|
if (error != null) buffer.count = Math.addExact(buffer.count, count);
|
|
buffer.saving = null;
|
|
}
|
|
if (error != null) acknowledgement.completeExceptionally(error);
|
|
else acknowledgement.complete(state);
|
|
});
|
|
return acknowledgement;
|
|
}
|
|
}
|