Compare commits

..
330 changed files with 8192 additions and 27620 deletions

No files matched your search

-6
View File
@@ -26,8 +26,6 @@ mvn -B -f VotingPlugin/pom.xml -Dtest=BackendControlConnectorProtocolTest,Contro
CI runs `mvn -B -f VotingPlugin/pom.xml package`; see `.github/workflows/maven.yml`. Do not use the `dev` Maven profile in
automation because it copies a JAR into a developer-specific server directory.
All project tests and test-only helpers belong under `VotingPlugin/src/test/java/com/bencodez/votingplugin/tests/`, with package `com.bencodez.votingplugin.tests` or a meaningful subpackage. Keep paths and package declarations aligned, and update cross-test imports, resources, and build selectors when moving tests. Preserve package-phase artifact checks and test discovery. Do not widen production APIs to make tests accessible; use narrowly scoped test-only reflection for non-public seams. Platform API fixtures that must retain an external runtime class identity (such as `net.minecraft.network.chat.Component`) stay in that platform package and must not contain test cases.
Assign one owner to Maven validation in each worktree. Never run concurrent Maven commands in the same worktree, including focused tests alongside a clean/package build: compilation and cleanup share `target/` and can invalidate each other. Reviewers must inspect source only while that owner builds, or run validation in a separate worktree.
Keep the downloadable VotingPlugin JAR as small as practical. The 10 MiB size target is advisory:
@@ -60,10 +58,6 @@ For compatibility-sensitive changes, add regression coverage that exercises the
- `com.bencodez.votingplugin.core` and its subpackages are platform-independent. Classes there must not import Bukkit, Paper, Fabric, Forge, or NeoForge APIs. Keep loader-specific adapters outside this package and enforce the boundary with `CorePlatformIsolationTest`.
- `proxy/VotingPluginProxy` and the Bungee/Velocity platform packages own proxy lifecycle and vote routing.
- `listeners/` receives Bukkit-side vote/player events; `proxy/cache/` owns proxy pending-vote queues.
- `commands/CommandLoader` captures `VoteCommandEnabled`, `VoteCommandName` and `LoadCommandAliases` at startup.
Configuration reload must not change the registered player root or generated help/navigation. Preserve exact command
ownership, admin roots/aliases and canonical `VotingPlugin.Commands.Vote.*` permissions when disabling or renaming;
standalone player aliases retain their `vote...`/`v...` identities. See `docs/player-command-root.md`.
- `votesites/` resolves configured service names. Be alert to the distinction between read-only resolution and paths that
may auto-create a site.
- `user/` owns player totals, points, streaks, last-vote values, and backend offline rewards.
+9 -16
View File
@@ -271,7 +271,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.6.1</version>
<version>3.5.4</version>
<executions>
<execution>
<id>default-test</id>
@@ -316,13 +316,6 @@
<enabled>false</enabled>
</releases>
</repository>
<repository>
<id>tcoded-releases</id>
<url>https://repo.tcoded.com/releases</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
<repository>
<id>velocity</id>
<url>https://nexus.velocitypowered.com/repository/maven-public/</url>
@@ -389,7 +382,7 @@
<dependency>
<groupId>net.neoforged</groupId>
<artifactId>mergetool</artifactId>
<version>2.0.7</version>
<version>2.0.0</version>
<classifier>api</classifier>
<scope>provided</scope>
</dependency>
@@ -408,12 +401,12 @@
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
<version>2.7</version>
<version>2.6</version>
</dependency>
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot-api</artifactId>
<version>26.3-R0.1-SNAPSHOT</version>
<version>26.2-R0.1-SNAPSHOT</version>
<scope>provided</scope>
<exclusions>
<exclusion>
@@ -431,7 +424,7 @@
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.15.0</version>
<version>2.14.0</version>
<scope>provided</scope>
</dependency>
<dependency>
@@ -482,7 +475,7 @@
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>8.0.2</version>
<version>7.5.3</version>
</dependency>
<dependency>
<groupId>me.clip</groupId>
@@ -532,7 +525,7 @@
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>6.1.3</version>
<version>5.12.2</version>
<scope>test</scope>
</dependency>
<dependency>
@@ -544,13 +537,13 @@
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>6.1.3</version>
<version>5.12.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<version>5.24.0</version>
<version>5.23.0</version>
<scope>test</scope>
</dependency>
<dependency>
@@ -71,9 +71,11 @@ import com.bencodez.votingplugin.broadcast.BroadcastSettings;
import com.bencodez.votingplugin.proxy.BungeeMethod;
import com.bencodez.votingplugin.commands.CommandLoader;
import com.bencodez.votingplugin.commands.executers.CommandAdminVote;
import com.bencodez.votingplugin.commands.executers.CommandVote;
import com.bencodez.votingplugin.commands.gui.AdminGUI;
import com.bencodez.votingplugin.commands.tabcompleter.AdminVoteTabCompleter;
import com.bencodez.votingplugin.commands.tabcompleter.AliasCommandFilterListener;
import com.bencodez.votingplugin.commands.tabcompleter.VoteTabCompleter;
import com.bencodez.votingplugin.config.BungeeSettings;
import com.bencodez.votingplugin.config.Config;
import com.bencodez.votingplugin.config.ConfigVoteSites;
@@ -85,9 +87,6 @@ import com.bencodez.votingplugin.cooldown.CoolDownCheck;
import com.bencodez.votingplugin.control.BackendControlAutoEnrollment;
import com.bencodez.votingplugin.control.BackendControlConnector;
import com.bencodez.votingplugin.data.ServerData;
import com.bencodez.votingplugin.maintenance.AutoCreateVoteSitesReminderService;
import com.bencodez.votingplugin.maintenance.AutoCreateVoteSitesReminderService.Settings;
import com.bencodez.votingplugin.core.maintenance.AutoCreateVoteSitesReminderState;
import com.bencodez.votingplugin.discord.DiscordHandler;
import com.bencodez.votingplugin.listeners.BlockBreak;
import com.bencodez.votingplugin.integration.votifier.VotifierIntegration;
@@ -157,6 +156,49 @@ import lombok.Setter;
public class VotingPluginMain extends AdvancedCorePlugin {
private final Object votingNPCLifecycle = new Object();
private final java.util.concurrent.atomic.AtomicLong votingNPCConfiguration = new java.util.concurrent.atomic.AtomicLong();
private volatile com.bencodez.votingplugin.npc.VotingNPCManager votingNPCManager;
public com.bencodez.votingplugin.npc.VotingNPCManager getVotingNPCManager() { return votingNPCManager; }
/** Optional NPC storage is lazy and asynchronous; configuration only schedules owner work. */
private void refreshVotingNPCs() {
boolean requested = getConfigFile().isVotingNPCsEnabled();
long generation = votingNPCConfiguration.incrementAndGet();
if (!requested && votingNPCManager == null) return;
getBukkitScheduler().runTask(this, () -> {
com.bencodez.votingplugin.npc.VotingNPCManager manager;
synchronized (votingNPCLifecycle) {
if (!isEnabled() || generation != votingNPCConfiguration.get()) return;
if (votingNPCManager == null && requested) {
try {
var created = new com.bencodez.votingplugin.npc.VotingNPCManager(this);
Bukkit.getPluginManager().registerEvents(created, this);
votingNPCManager = created;
} catch (RuntimeException | LinkageError unsupported) {
getLogger().warning("Voting NPCs are unavailable on this server; normal voting is unaffected.");
return;
}
}
manager = votingNPCManager;
}
if (manager != null) manager.configure(requested);
});
}
private void closeVotingNPCs() {
com.bencodez.votingplugin.npc.VotingNPCManager manager;
synchronized (votingNPCLifecycle) {
votingNPCConfiguration.incrementAndGet();
manager = votingNPCManager;
votingNPCManager = null;
}
if (manager != null) {
try { manager.close(); } catch (RuntimeException | LinkageError failure) { debug(failure); }
}
}
@Getter
public static VotingPluginMain plugin;
@@ -175,9 +217,6 @@ public class VotingPluginMain extends AdvancedCorePlugin {
@Getter
private BroadcastHandler broadcastHandler;
@Getter
private com.bencodez.votingplugin.streaks.VoteStreaksMenu voteStreaksMenu;
@Getter
private BackendProxyHandler backendProxyHandler;
private ProcessedVoteCache backendProcessedVoteCache;
@@ -217,21 +256,6 @@ public class VotingPluginMain extends AdvancedCorePlugin {
@Getter
private CommandLoader commandLoader;
/** Runtime command identity is captured at startup; configuration reload does not rename it. */
public String getVoteCommandPrefix() {
return "/" + (commandLoader == null ? "vote" : commandLoader.getVoteCommandName());
}
public boolean isVoteCommandEnabled() {
return commandLoader == null || commandLoader.isVoteCommandEnabled();
}
/** Retarget the built-in invalid-command help hint, including existing Config.yml text. */
public String formatVoteCommandMessage(String message) {
return message.replace("%votecommand%", getVoteCommandPrefix())
.replaceAll("(?i)/vote(?=\\s|$|[!.,])", getVoteCommandPrefix());
}
@Getter
private NameMCLikeCheckerTask nameMCLikeCheckerTask;
@@ -287,7 +311,6 @@ public class VotingPluginMain extends AdvancedCorePlugin {
@Getter
private TopVoterState topVoterState;
private volatile com.bencodez.votingplugin.topvoter.TopVoterDisplayFilter topVoterDisplayFilter;
@Getter
@@ -316,8 +339,6 @@ public class VotingPluginMain extends AdvancedCorePlugin {
@Getter
private ScheduledExecutorService voteTimer;
private volatile AutoCreateVoteSitesReminderService autoCreateVoteSitesSetupReminder;
private ScheduledExecutorService autoCreateVoteSitesReminderWorker;
@Getter
private UserManager votingPluginUserManager;
@@ -339,9 +360,6 @@ public class VotingPluginMain extends AdvancedCorePlugin {
private volatile VotingPluginBackgroundTask backgroundTask;
private volatile AtomicBoolean basicBungeeUpdateRunning;
private final AtomicBoolean unloadInProgress = new AtomicBoolean();
private Set<String> completedUnloadSteps;
private java.util.concurrent.CompletionStage<Void> signShutdownPublication;
private synchronized AtomicBoolean basicBungeeUpdateAdmission() {
if (basicBungeeUpdateRunning == null) basicBungeeUpdateRunning = new AtomicBoolean();
@@ -530,84 +548,6 @@ public class VotingPluginMain extends AdvancedCorePlugin {
return topVoterState.getLastMonthTopVoters();
}
/** Display-only snapshots; raw getters remain the award/accounting contract. */
public LinkedHashMap<TopVoterPlayer, Integer> getTopVoterDisplay(TopVoter top) {
return projectTopVoterDisplay(getTopVoter(top));
}
public java.util.concurrent.CompletionStage<LinkedHashMap<TopVoterPlayer, Integer>> getTopVoterDisplayAsync(TopVoter top) {
var filter = topVoterDisplayFilter;
var raw = new LinkedHashMap<>(getTopVoter(top));
return filter == null || !isEnabled() ? java.util.concurrent.CompletableFuture.completedFuture(raw)
: filter.projectAsync(raw, configFile != null && configFile.isHideTopVoterIfNotPlayedBefore());
}
private final java.util.concurrent.atomic.AtomicLong topVoterDisplayGeneration = new java.util.concurrent.atomic.AtomicLong();
public long getTopVoterDisplayGeneration() { return topVoterDisplayGeneration.get(); }
public LinkedHashMap<TopVoterPlayer, Integer> getLastMonthTopVoterDisplay() {
return projectTopVoterDisplay(getLastMonthTopVoter());
}
public LinkedHashMap<TopVoterPlayer, Integer> getPreviousMonthTopVoterDisplay(YearMonth month) {
return projectTopVoterDisplay(getPreviousMonthsTopVoters().getOrDefault(month, new LinkedHashMap<>()));
}
private LinkedHashMap<TopVoterPlayer, Integer> projectTopVoterDisplay(LinkedHashMap<TopVoterPlayer, Integer> raw) {
var filter = topVoterDisplayFilter;
return filter == null || !isEnabled() ? new LinkedHashMap<>(raw)
: filter.project(raw, configFile != null && configFile.isHideTopVoterIfNotPlayedBefore());
}
public void initializeTopVoterDisplayFilter() {
retireTopVoterDisplayFilter();
boolean onlineMode = getOptions().isOnlineMode();
var filter = new com.bencodez.votingplugin.topvoter.TopVoterDisplayFilter(row ->
com.bencodez.votingplugin.topvoter.TopVoterPresenceIdentity
.identities(row, onlineMode, UuidLookup.getInstance()::getCachedUUID),
(row, aliases) -> checkTopVoterPresence(aliases, onlineMode), System::nanoTime,
this::topVoterDisplayRankingRows);
registerEvents(filter);
topVoterDisplayFilter = filter;
}
/** Cache capacity follows already loaded rankings, including disjoint historical identities. */
private long topVoterDisplayRankingRows() {
var state = topVoterState;
if (state == null) return 0L;
long rows = state.getLastMonthTopVoters().size();
for (var board : state.getTopVoters().values()) if (board != null) rows += board.size();
for (var board : state.getPreviousMonthsTopVoters().values()) if (board != null) rows += board.size();
return rows;
}
private java.util.concurrent.CompletionStage<com.bencodez.advancedcore.api.user.presence.PlayerPresence>
checkTopVoterPresence(java.util.List<java.util.UUID> aliases, boolean onlineMode) {
boolean completeOnlineHistory = onlineMode || aliases.stream().anyMatch(alias ->
alias != null && alias.version() == 4 && alias.variant() == 2);
if (!completeOnlineHistory) return checkPlayerPresenceIdentitiesAsync(aliases);
try {
return checkPlayerPresenceIdentitiesAsync(aliases, true);
} catch (NoSuchMethodError | AbstractMethodError unsupported) {
// Older SDKs can retain a positive but cannot certify the wider absence scope.
return checkPlayerPresenceIdentitiesAsync(aliases).thenApply(evidence ->
evidence == com.bencodez.advancedcore.api.user.presence.PlayerPresence.NEVER_JOINED
? com.bencodez.advancedcore.api.user.presence.PlayerPresence.UNKNOWN : evidence);
}
}
private void retireTopVoterDisplayFilter() {
topVoterDisplayGeneration.incrementAndGet();
if (discordHandler != null) discordHandler.retireLeaderboardPublications();
var filter = topVoterDisplayFilter;
topVoterDisplayFilter = null;
if (filter != null) {
filter.close();
org.bukkit.event.HandlerList.unregisterAll(filter);
}
}
public LinkedHashMap<YearMonth, LinkedHashMap<TopVoterPlayer, Integer>> getPreviousMonthsTopVoters() {
return topVoterState.getPreviousMonthsTopVoters();
}
@@ -797,7 +737,6 @@ public class VotingPluginMain extends AdvancedCorePlugin {
@Override
public void onPostLoad() {
serverData.refreshVotePartyDisplay();
ensureCommunicationSecret();
// auto conversion for Shop.yml
if (plugin.getShopFile().isJustCreated()) {
@@ -826,16 +765,6 @@ public class VotingPluginMain extends AdvancedCorePlugin {
voteTester = new VoteTester(plugin);
loadVoteTimer();
BoundedScheduledExecutor setupReminderWorker = new BoundedScheduledExecutor(1, 4);
setupReminderWorker.setThreadFactory(runnable -> {
Thread worker = new Thread(runnable, "VotingPlugin-SiteSetupReminder");
worker.setDaemon(true);
return worker;
});
autoCreateVoteSitesReminderWorker = setupReminderWorker;
autoCreateVoteSitesSetupReminder = new AutoCreateVoteSitesReminderService(getDataFolder().toPath(),
setupReminderWorker, getLogger(), autoCreateVoteSitesReminderSettings());
autoCreateVoteSitesSetupReminder.start();
getVotingPluginUserManager().startSharedPointTransferRecovery();
if (bungeeSettings.isUseBungeecoord()) {
@@ -862,6 +791,7 @@ public class VotingPluginMain extends AdvancedCorePlugin {
checkVotifier();
registerEvents();
refreshPlaceholderPlayerPresence();
refreshVotingNPCs();
loadVoteBroadcast();
@@ -885,7 +815,6 @@ public class VotingPluginMain extends AdvancedCorePlugin {
});
topVoterState = new TopVoterState();
initializeTopVoterDisplayFilter();
topVoterHandler = new TopVoterHandler(this);
new AdminGUI(this).loadHook();
@@ -2015,95 +1944,9 @@ public class VotingPluginMain extends AdvancedCorePlugin {
configFile.saveData();
}
@Getter
private volatile com.bencodez.votingplugin.util.ServerDataPublicationFence serverDataPublicationFence;
private volatile com.bencodez.votingplugin.data.GenerationFencedServerDataFile fencedServerDataFile;
private java.util.concurrent.CompletableFuture<Void> serverDataFinalPublication;
private boolean serverDataFinalPublicationReserved;
private boolean serverDataFinalStageAttached;
private volatile boolean serverDataEnableCleanupStarted;
private volatile boolean serverDataEnableAdmissionRejected;
@Override
public com.bencodez.advancedcore.data.ServerData getServerDataFile() {
var file = super.getServerDataFile();
var current = fencedServerDataFile;
if (current != null && current.wraps(file)) {
// The SDK replaces its file after pre-load. A failed new generation has
// no file to finalize; never expose the predecessor as its current owner.
return current.belongsTo(serverDataPublicationFence) ? current : null;
}
synchronized (this) {
file = super.getServerDataFile();
var owner = serverDataPublicationFence;
if (file == null || owner == null) return file;
current = fencedServerDataFile;
if (current != null && current.wraps(file) && !current.belongsTo(owner)) return null;
if (current == null || !current.wraps(file)) {
current = new com.bencodez.votingplugin.data.GenerationFencedServerDataFile(this, file, owner);
fencedServerDataFile = current;
}
return current;
}
}
/** Capture the existing AdvancedCore executors which can still publish server-data state. */
public ScheduledExecutorService[] getServerDataWriterExecutors() {
var checker = getTimeChecker();
return new ScheduledExecutorService[] { getTimer(), getLoginTimer(), getInventoryTimer(),
checker == null ? null : checker.getTimer() };
}
@Override
public void onEnable() {
synchronized (this) {
// Bind a retained SDK file before changing owner. AdvancedCore replaces its
// private file only later in loadHook(), after onPreLoad().
if (serverDataPublicationFence != null) getServerDataFile();
serverDataPublicationFence = com.bencodez.votingplugin.util.ServerDataPublicationFence.beginGeneration(
getDataFolder().toPath().resolve("ServerData.yml"));
try { serverDataPublicationFence.retainForProcessExit(); }
catch (RuntimeException | Error registrationFailure) {
serverDataEnableAdmissionRejected = true;
try { serverDataPublicationFence.retire(); }
catch (RuntimeException | Error cleanupFailure) {
if (cleanupFailure != registrationFailure) registrationFailure.addSuppressed(cleanupFailure);
}
throw registrationFailure;
}
serverDataFinalPublication = new java.util.concurrent.CompletableFuture<>();
serverDataFinalPublicationReserved = false;
serverDataFinalStageAttached = false;
serverDataEnableCleanupStarted = false;
serverDataEnableAdmissionRejected = false;
}
// Failed startup can already own SDK writers; disable must retire them before replacement.
try { super.onEnable(); }
catch (RuntimeException | Error failure) {
// SDK admission can fail before its startup-cleanup try/catch. Such an
// attempt admitted no new writers and must not strand an empty plugin owner.
// An admitted startup failure already entered our onDisable; preserve its drain.
if (!serverDataEnableCleanupStarted) {
serverDataEnableAdmissionRejected = true;
try {
serverDataPublicationFence.retire();
serverDataFinalPublication.complete(null);
} catch (RuntimeException | Error cleanupFailure) {
if (cleanupFailure != failure) failure.addSuppressed(cleanupFailure);
}
}
throw failure;
}
}
@Override
public void onPreLoad() {
plugin = this;
unloadInProgress.set(false);
completedUnloadSteps = new java.util.HashSet<>();
signShutdownPublication = null;
setupFiles();
if ("SQLITE".equalsIgnoreCase(configFile.getData().getString("DataStorage", "SQLITE"))) {
@@ -2145,83 +1988,11 @@ public class VotingPluginMain extends AdvancedCorePlugin {
@Override
public void onDisable() {
// The rejected enable owns no SDK shutdown stage to complete a new reservation.
if (serverDataEnableAdmissionRejected) return;
runShutdownStep("server-data process drain", this::beginServerDataProcessDrain);
serverDataEnableCleanupStarted = true;
runShutdownStep("Discord leaderboards", () -> {
if (discordHandler != null) discordHandler.close();
});
runShutdownStep("setup reminder", this::stopAutoCreateVoteSitesSetupReminder);
runShutdownStep("server-data writer retirement", () -> {
if (serverDataPublicationFence != null) {
retainServerDataFinalPublication();
var coreWriters = getServerDataWriterExecutors();
var writers = java.util.Arrays.copyOf(coreWriters, coreWriters.length + 1);
writers[coreWriters.length] = voteTimer;
serverDataPublicationFence.retainUntilTermination(writers);
}
});
if (offlineVoteOwnerHandoffs != null) offlineVoteOwnerHandoffs.close();
try {
runShutdownStep("offline vote handoffs", () -> {
if (offlineVoteOwnerHandoffs != null) offlineVoteOwnerHandoffs.close();
});
shutdownVoteReminders();
} finally {
try { shutdownVoteReminders(); }
finally {
try { super.onDisable(); }
finally { runShutdownStep("server-data publication owner", () -> {
if (serverDataPublicationFence != null) serverDataPublicationFence.retire();
}); }
}
}
}
/** Reserve before SDK shutdown can enqueue a final file publication. No YAML lock or wait. */
private void retainServerDataFinalPublication() {
synchronized (this) {
if (serverDataFinalPublicationReserved) return;
if (serverDataFinalPublication == null)
serverDataFinalPublication = new java.util.concurrent.CompletableFuture<>();
serverDataPublicationFence.retainUntilSuccessfulPublication(serverDataFinalPublication);
serverDataFinalPublicationReserved = true;
}
}
@Override
public void onShutdownComplete(java.util.concurrent.CompletionStage<Void> finalFilesStage) {
java.util.concurrent.CompletableFuture<Void> publication;
synchronized (this) {
publication = serverDataFinalStageAttached ? null : serverDataFinalPublication;
serverDataFinalStageAttached = true;
}
try {
if (publication != null) {
try {
java.util.Objects.requireNonNull(finalFilesStage).whenComplete((ignored, failure) -> {
if (failure == null) publication.complete(null);
else publication.completeExceptionally(failure);
});
} catch (Throwable failure) { publication.completeExceptionally(failure); }
}
} finally { super.onShutdownComplete(finalFilesStage); }
}
private Settings autoCreateVoteSitesReminderSettings() {
return new Settings(true, configFile.isAutoCreateVoteSites(),
AutoCreateVoteSitesReminderState.DEFAULT_THRESHOLD_MILLIS,
AutoCreateVoteSitesReminderState.DEFAULT_REPEAT_MILLIS);
}
private void stopAutoCreateVoteSitesSetupReminder() {
AutoCreateVoteSitesReminderService current = autoCreateVoteSitesSetupReminder;
autoCreateVoteSitesSetupReminder = null;
ScheduledExecutorService worker = autoCreateVoteSitesReminderWorker;
autoCreateVoteSitesReminderWorker = null;
try {
if (current != null) current.closeAsync();
} finally {
if (worker != null) worker.shutdown();
super.onDisable();
}
}
@@ -2234,107 +2005,49 @@ public class VotingPluginMain extends AdvancedCorePlugin {
@Override
public void onUnLoad() {
runShutdownStep("server-data process drain", this::beginServerDataProcessDrain);
if (!unloadInProgress.compareAndSet(false, true)) {
runShutdownStep("time queue retry", () -> {
if (timeQueueHandler != null) timeQueueHandler.saveForShutdown();
});
return;
}
try {
if (completedUnloadSteps == null) completedUnloadSteps = new java.util.HashSet<>();
runUnloadStep("Discord leaderboards", () -> {
if (discordHandler != null) discordHandler.close();
});
runUnloadStep("top voter display", this::retireTopVoterDisplayFilter);
runUnloadStep("streak menu", () -> {
if (voteStreaksMenu != null) voteStreaksMenu.close();
});
runUnloadStep("setup reminder", this::stopAutoCreateVoteSitesSetupReminder);
runUnloadStep("player presence", placeholderPlayerPresence::clear);
runUnloadStep("backend hosted Control", this::stopBackendHostedControlLifecycle);
runUnloadStep("backend Control connector", this::stopBackendControlConnectorLifecycle);
runUnloadStep("backend proxy", () -> {
if (getBackendProxyHandler() != null) getBackendProxyHandler().closeForShutdown();
});
runUnloadStep("backend ordered vote queue", () -> {
if (backendOrderedVoteOverflowQueue != null) {
backendOrderedVoteOverflowQueue.close();
backendOrderedVoteOverflowQueue = null;
}
});
runUnloadStep("webhook manager", () -> {
if (webhookManager != null) webhookManager.shutdown();
});
runUnloadStep("vote timer", this::shutdownVoteTimer);
runUnloadStep("Votifier vote queue", () -> {
if (votifierVoteOverflowQueue != null) {
votifierVoteOverflowQueue.close();
votifierVoteOverflowQueue = null;
}
});
runShutdownStep("time queue", () -> {
if (timeQueueHandler != null) timeQueueHandler.saveForShutdown();
});
runUnloadStep("vote reminders", this::shutdownVoteReminders);
runUnloadStep("cooldown checker", () -> {
if (coolDownCheck != null) {
coolDownCheck.shutdown();
coolDownCheck = null;
}
});
runShutdownStep("signs", this::shutdownSigns);
runUnloadStep("event handlers", () -> HandlerList.unregisterAll(this));
// Late producers must see rejection until their overflow and handler cleanup finishes.
if (completedUnloadSteps.contains("vote timer")) voteTimer = null;
if (plugin == this) plugin = null;
} finally { unloadInProgress.set(false); }
}
private void beginServerDataProcessDrain() {
var owner = serverDataPublicationFence;
if (owner != null) owner.beginShutdown(System.nanoTime());
}
private void shutdownSigns() {
if (signs == null) return;
var previous = signShutdownPublication;
if (previous != null && !previous.toCompletableFuture().isCompletedExceptionally()) return;
signShutdownPublication = java.util.Objects.requireNonNull(signs.storeSignsForShutdown());
}
private void runUnloadStep(String name, Runnable step) {
if (!completedUnloadSteps.contains(name) && runShutdownStep(name, step)) completedUnloadSteps.add(name);
}
private boolean runShutdownStep(String name, Runnable step) {
try {
step.run();
return true;
} catch (RuntimeException | Error failure) {
closeVotingNPCs();
placeholderPlayerPresence.clear();
stopBackendHostedControlLifecycle();
stopBackendControlConnectorLifecycle();
if (getBackendProxyHandler() != null) {
try {
getLogger().log(java.util.logging.Level.WARNING, "Failed to shut down " + name, failure);
} catch (RuntimeException | Error ignored) {
// Logging must not prevent the next independent cleanup step.
getBackendProxyHandler().closeForShutdown();
} catch (Exception e) {
debug(e);
}
return false;
}
}
private void shutdownVoteTimer() {
if (voteTimer == null) return;
if (backendOrderedVoteOverflowQueue != null) {
backendOrderedVoteOverflowQueue.close();
backendOrderedVoteOverflowQueue = null;
}
if (webhookManager != null) {
webhookManager.shutdown();
}
voteTimer.shutdown();
try {
voteTimer.shutdown();
if (!voteTimer.awaitTermination(1, TimeUnit.SECONDS)) voteTimer.shutdownNow();
} catch (InterruptedException interrupted) {
Thread.currentThread().interrupt();
voteTimer.shutdownNow();
} catch (RuntimeException failure) {
try {
getLogger().log(java.util.logging.Level.WARNING, "Failed to shut down vote timer", failure);
} catch (RuntimeException | Error ignored) { }
voteTimer.shutdownNow();
voteTimer.awaitTermination(1, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
voteTimer.shutdownNow();
if (votifierVoteOverflowQueue != null) {
votifierVoteOverflowQueue.close();
votifierVoteOverflowQueue = null;
}
if (timeQueueHandler != null) {
timeQueueHandler.save();
}
shutdownVoteReminders();
if (coolDownCheck != null) {
coolDownCheck.shutdown();
coolDownCheck = null;
}
getSigns().storeSigns();
HandlerList.unregisterAll(plugin);
plugin = null;
}
/**
@@ -2345,6 +2058,12 @@ public class VotingPluginMain extends AdvancedCorePlugin {
commandLoader.loadCommands();
commandLoader.loadAliases();
// /vote, /v
getCommand("vote").setExecutor(new CommandVote(this));
getCommand("vote").setTabCompleter(new VoteTabCompleter());
// getCommand("v").setExecutor(new CommandVote(this));
// getCommand("v").setTabCompleter(new VoteTabCompleter());
// /adminvote, /av
getCommand("adminvote").setExecutor(new CommandAdminVote(this));
getCommand("adminvote").setTabCompleter(new AdminVoteTabCompleter());
@@ -2371,8 +2090,6 @@ public class VotingPluginMain extends AdvancedCorePlugin {
* Register events.
*/
private void registerEvents() {
voteStreaksMenu = new com.bencodez.votingplugin.streaks.VoteStreaksMenu(this);
getServer().getPluginManager().registerEvents(voteStreaksMenu, this);
PluginManager pm = getServer().getPluginManager();
pm.registerEvents(new PlayerJoinEvent(this), this);
@@ -2428,19 +2145,15 @@ public class VotingPluginMain extends AdvancedCorePlugin {
/** Captures Bukkit presence while the lifecycle caller owns platform access. */
public void refreshPlaceholderPlayerPresence() {
boolean onlineMode = getOptions().isOnlineMode();
placeholderPlayerPresence.refresh(Bukkit::getOnlinePlayers, (player, capture) ->
com.bencodez.votingplugin.util.BukkitCompletionScheduler.run(this, player, () -> {
if (!player.isOnline()) return;
UUID storageUuid = placeholderPlayerPresence.storageUuid(player);
capture.accept(storageUuid == null ? placeholderStorageUuid(player, onlineMode) : storageUuid);
}, () -> { }, () -> { }));
placeholderPlayerPresence.replace(Bukkit::getOnlinePlayers,
player -> placeholderStorageUuid(player, onlineMode));
}
static UUID placeholderStorageUuid(Player player, boolean onlineMode) {
if (onlineMode) return player.getUniqueId();
String resolvedUuid = UuidLookup.getInstance().getUUIDWithoutStorage(player.getName());
String cachedUuid = UuidLookup.getInstance().getCachedUUID(player.getName());
try {
return UUID.fromString(resolvedUuid);
return UUID.fromString(cachedUuid);
} catch (IllegalArgumentException | NullPointerException ignored) {
return player.getUniqueId();
}
@@ -2456,13 +2169,9 @@ public class VotingPluginMain extends AdvancedCorePlugin {
private void reloadPlugin(boolean userStorage, boolean reconcileHostedControl,
boolean updateActiveBackendRuntime) {
if (offlineVoteOwnerHandoffs != null) offlineVoteOwnerHandoffs.pause();
retireTopVoterDisplayFilter();
try {
if (voteStreaksMenu != null) voteStreaksMenu.suspend();
configFile.reloadData();
configFile.loadValues();
AutoCreateVoteSitesReminderService setupReminder = autoCreateVoteSitesSetupReminder;
if (setupReminder != null) setupReminder.reload(autoCreateVoteSitesReminderSettings());
configVoteSites.reloadData();
@@ -2477,7 +2186,6 @@ public class VotingPluginMain extends AdvancedCorePlugin {
updateAdvancedCoreHook();
reloadAdvancedCore(userStorage);
initializeTopVoterDisplayFilter();
// PerServerPoints can switch shared point storage on during a live reload.
// Re-evaluate after storage has reloaded; UserManager keeps this lifecycle task unique.
getVotingPluginUserManager().startSharedPointTransferRecovery();
@@ -2509,11 +2217,11 @@ public class VotingPluginMain extends AdvancedCorePlugin {
loadDirectlyDefined();
refreshVotingNPCs();
if (reconcileHostedControl) restartBackendControlConnector();
setUpdate(true);
} finally {
if (voteStreaksMenu != null) voteStreaksMenu.resume();
if (offlineVoteOwnerHandoffs != null) offlineVoteOwnerHandoffs.resume();
}
}
@@ -56,7 +56,6 @@ import com.bencodez.simpleapi.valuerequest.ValueRequest;
import com.bencodez.votingplugin.VotingPluginMain;
import com.bencodez.votingplugin.core.maintenance.MaintenanceConfirmation;
import com.bencodez.votingplugin.commands.executers.CommandAliases;
import com.bencodez.votingplugin.commands.executers.CommandVote;
import com.bencodez.votingplugin.commands.gui.AdminGUI;
import com.bencodez.votingplugin.commands.gui.admin.AdminVoteHelp;
import com.bencodez.votingplugin.commands.gui.admin.AdminVotePerms;
@@ -83,7 +82,6 @@ import com.bencodez.votingplugin.commands.gui.player.VoteTotal;
import com.bencodez.votingplugin.commands.gui.player.VoteURL;
import com.bencodez.votingplugin.commands.gui.player.VoteURLVoteSite;
import com.bencodez.votingplugin.commands.tabcompleter.AliasesTabCompleter;
import com.bencodez.votingplugin.commands.tabcompleter.VoteTabCompleter;
import com.bencodez.votingplugin.events.PlayerVoteEvent;
import com.bencodez.votingplugin.events.PlayerVoteSiteCoolDownEndEvent;
import com.bencodez.votingplugin.presets.VoteSitePresetSetupHandler;
@@ -117,13 +115,6 @@ public class CommandLoader {
private String playerPerm = "VotingPlugin.Player";
private VotingPluginMain plugin;
private final boolean startupVoteCommandEnabled;
private final String startupVoteCommandName;
private final boolean startupLoadCommandAliases;
private boolean playerCommandConfigured;
private PluginCommand playerRootCommand;
private boolean voteCommandEnabled;
private String voteCommandName = "vote";
/**
* Constructs a new CommandLoader.
@@ -132,131 +123,6 @@ public class CommandLoader {
*/
public CommandLoader(VotingPluginMain plugin) {
this.plugin = plugin;
var config = plugin.getConfigFile();
startupVoteCommandEnabled = config == null || config.isVoteCommandEnabled();
startupVoteCommandName = config == null ? "vote" : config.getVoteCommandName();
startupLoadCommandAliases = config == null || config.isLoadCommandAliases();
voteCommandEnabled = startupVoteCommandEnabled;
}
/** The label actually registered at startup, including its namespace on conflict. */
public String getVoteCommandName() {
return voteCommandName;
}
public boolean isVoteCommandEnabled() {
return voteCommandEnabled;
}
/** Runs a generated player navigation action only while its command is available. */
public void performVoteCommand(Player player, String arguments) {
if (voteCommandEnabled) {
player.performCommand(voteCommandName + (arguments.isEmpty() ? "" : " " + arguments));
}
}
/** Configure only once: reloading configuration must not change command ownership. */
private void configurePlayerCommand() {
if (playerCommandConfigured) return;
playerCommandConfigured = true;
try {
CommandMap commandMap = getCommandMap();
PluginCommand root = ownedCommand("vote");
playerRootCommand = root;
if (!startupVoteCommandEnabled) {
for (String name : plugin.getDescription().getCommands().keySet()) {
if (name.equalsIgnoreCase("vote") || name.toLowerCase(Locale.ROOT).startsWith("vote")) {
PluginCommand command = ownedCommand(name);
if (command != null) unregisterCommand(commandMap, command);
}
}
voteCommandEnabled = false;
return;
}
if (root == null) {
voteCommandEnabled = false;
plugin.getLogger().warning("Unable to locate VotingPlugin's player command; player commands were not enabled.");
return;
}
String name = startupVoteCommandName == null ? "" : startupVoteCommandName.trim().toLowerCase(Locale.ROOT);
if (!name.matches("[a-z0-9][a-z0-9_-]{0,63}") || isReservedCommandName(name)) {
plugin.getLogger().warning("Invalid or reserved VoteCommandName; using vote. Command settings require a restart.");
name = "vote";
}
String namespace = plugin.getDescription().getName().toLowerCase(Locale.ROOT);
String fallback = namespace + ":" + name;
org.bukkit.command.Command existingFallback = commandMap.getCommand(fallback);
org.bukkit.command.Command existingLabel = commandMap.getCommand(name);
boolean ownedLabelCollision = existingLabel instanceof PluginCommand owned
&& owned.getPlugin() == plugin && owned != root;
if (!name.equals("vote") && ((existingFallback != null && existingFallback != root) || ownedLabelCollision)) {
plugin.getLogger().warning("VoteCommandName namespace is already owned; keeping vote. Command settings require a restart.");
name = "vote";
fallback = namespace + ":vote";
}
if (!name.equals("vote")) {
// Bukkit's register writes the fallback even when the bare label collides.
// Check it before unregistering or publishing the renamed command.
unregisterCommand(commandMap, root);
root.setName(name);
root.setLabel(name);
root.setAliases(List.of());
if (existingLabel != null && existingLabel != root) {
// SimpleCommandMap may overwrite another command's bare alias. Register
// only our free fallback in that case, preserving the alias owner too.
root.setLabel(fallback);
if (!root.register(commandMap)) throw new IllegalStateException("Player command registration was rejected");
Map<String, org.bukkit.command.Command> registrations = getKnownCommands(commandMap);
// Paper forwards put/get to Brigadier; HashMap.putIfAbsent can bypass it.
if (registrations.get(fallback) != null) throw new IllegalStateException("Player command namespace became occupied");
registrations.put(fallback, root);
} else {
commandMap.register(namespace, root);
}
}
voteCommandName = commandMap.getCommand(name) == root ? name : fallback;
voteCommandEnabled = commandMap.getCommand(voteCommandName) == root;
if (voteCommandEnabled) {
root.setExecutor(new CommandVote(plugin));
root.setTabCompleter(new VoteTabCompleter());
if (!voteCommandName.equals(name)) {
plugin.getLogger().warning("Player command label is already owned; use /" + voteCommandName + " instead.");
}
} else {
plugin.getLogger().warning("Unable to register VotingPlugin's player command without replacing another owner.");
}
} catch (ReflectiveOperationException | RuntimeException failure) {
throw new IllegalStateException("Unable to configure VotingPlugin's player command safely", failure);
}
}
private boolean isReservedCommandName(String name) {
for (var entry : plugin.getDescription().getCommands().entrySet()) {
if (entry.getKey().equalsIgnoreCase("vote")) continue;
if (entry.getKey().equalsIgnoreCase(name)) return true;
Object aliases = entry.getValue().get("aliases");
if (aliases instanceof String alias && alias.equalsIgnoreCase(name)) return true;
if (aliases instanceof Iterable<?> values) {
for (Object alias : values) if (name.equalsIgnoreCase(String.valueOf(alias))) return true;
}
}
return false;
}
private PluginCommand ownedCommand(String name) {
PluginCommand command = plugin.getCommand(name);
if (command != null && command.getPlugin() == plugin) return command;
try {
// A plugin may have displaced the primary and fallback labels while a short
// alias still points at our command. Disable must remove that object too.
for (org.bukkit.command.Command candidate : getKnownCommands(getCommandMap()).values()) {
if (candidate instanceof PluginCommand owned && owned.getPlugin() == plugin
&& owned.getName().equalsIgnoreCase(name)) return owned;
}
} catch (ReflectiveOperationException failure) {
throw new IllegalStateException("Unable to inspect owned command registrations", failure);
}
return null;
}
void runForCommandSender(CommandSender sender, Runnable task) {
@@ -354,7 +220,7 @@ public class CommandLoader {
java.util.List<VotingPluginUser> users = new java.util.ArrayList<>();
try {
for (String uuidString : plugin.getUserManager().getAllUUIDs()) {
users.add(plugin.getVotingPluginUserManager().getVotingPluginUser(UUID.fromString(uuidString), true));
users.add(plugin.getVotingPluginUserManager().getVotingPluginUser(UUID.fromString(uuidString)));
}
} catch (Throwable failure) {
plugin.debug(failure);
@@ -537,28 +403,26 @@ public class CommandLoader {
* @return true if player has permission
*/
public boolean hasPermission(Player player, String cmd) {
cmd = cmd.toLowerCase(Locale.ROOT);
if (cmd.startsWith("votingplugin:")) {
cmd = cmd.substring("votingplugin:".length());
}
for (var entry : commands.entrySet()) {
if (entry.getKey().equalsIgnoreCase(cmd)) return entry.getValue().hasPerm(player);
if (commands.containsKey(cmd)) {
return commands.get(cmd).hasPerm(player);
}
boolean adminCommand = false;
String rootLabel = voteCommandName.substring(voteCommandName.indexOf(':') + 1);
if (cmd.equals("adminvote") || cmd.startsWith("adminvote ")) {
if (cmd.startsWith("vote")) {
cmd = cmd.substring("vote".length());
} else if (cmd.startsWith("v")) {
cmd = cmd.substring(1);
} else if (cmd.startsWith("av")) {
adminCommand = true;
cmd = cmd.substring("adminvote".length()).trim();
} else if (cmd.equals("av") || cmd.startsWith("av ")) {
cmd = cmd.substring("av".length());
} else if (cmd.startsWith("adminvote")) {
adminCommand = true;
cmd = cmd.substring("av".length()).trim();
} else if (voteCommandEnabled && (cmd.equals(rootLabel) || cmd.startsWith(rootLabel + " "))) {
cmd = cmd.substring(rootLabel.length()).trim();
} else {
return false;
cmd = cmd.substring("adminvote".length());
}
// plugin.debug(cmd);
if (!adminCommand) {
@@ -595,11 +459,13 @@ public class CommandLoader {
* @return true if it's a VotingPlugin command
*/
public boolean isVotingPluginCommand(Player player, String cmd) {
try {
org.bukkit.command.Command command = getCommandMap().getCommand(cmd);
return command instanceof PluginCommand owned && owned.getPlugin() == plugin;
} catch (ReflectiveOperationException failure) {
plugin.debug(failure);
if (plugin.getCommand(cmd) != null || cmd.startsWith("votingplugin")) {
return true;
}
for (String str : commands.keySet()) {
if (str.equalsIgnoreCase(cmd)) {
return true;
}
}
return false;
}
@@ -607,30 +473,9 @@ public class CommandLoader {
/**
* Load admin vote command.
*/
private void clearDiscordMessageId(CommandSender sender, TopVoter top) {
try {
plugin.getTimer().execute(() -> {
boolean confirmed;
try { confirmed = clearDiscordMessageId(top); }
catch (RuntimeException failure) { confirmed = false; }
String message = confirmed ? "&cCleared discord message ID for " + top.toString()
: "&cUnable to confirm the cleared Discord message ID; check storage before restarting.";
runForCommandSender(sender, () -> sender.sendMessage(MessageAPI.colorize(message)));
});
} catch (RuntimeException rejected) {
runForCommandSender(sender, () -> sender.sendMessage(MessageAPI.colorize(
"&cUnable to schedule clearing the Discord message ID; no changes made.")));
}
}
private boolean clearDiscordMessageId(TopVoter top) {
var discord = plugin.getDiscordHandler();
return discord != null ? discord.clearTopVoterMessageId(top)
: plugin.getServerData().setTopVoterMessageIdConfirmed(top, 0L);
}
private void loadAdminVoteCommand() {
plugin.setAdminVoteCommand(new ArrayList<>());
com.bencodez.votingplugin.npc.VotingNPCCommands.register(plugin);
plugin.getAdminVoteCommand().add(new CommandHandler(plugin, new String[] { "CurrentPluginTime" },
"VotingPlugin.Commands.AdminVote.CurrentPluginTime|" + adminPerm, "Current plugin time") {
@@ -865,7 +710,7 @@ public class CommandLoader {
@Override
public void executeSinglePlayer(CommandSender sender, String[] args) {
VotingPluginUser user = plugin.getVotingPluginUserManager().getVotingPluginUser(args[1]);
if (!UserStorage.MYSQL.equals(plugin.getStorageType())) user.cache();
user.cache();
user.removePoints(Integer.parseInt(args[3]), removed -> {
if (!removed) {
runForCommandSender(sender, () -> sender.sendMessage(MessageAPI.colorize(
@@ -2969,7 +2814,9 @@ public class CommandLoader {
public void execute(CommandSender sender, String[] args) {
String topVoter = args[1];
TopVoter top = TopVoter.getTopVoter(topVoter);
clearDiscordMessageId(sender, top);
plugin.getServerData().setTopVoterMessageId(top, 0);
plugin.getDiscordHandler().getTopVoterMessageIds().put(top, 0L);
sendMessage(sender, "&cCleared discord message ID for " + top.toString());
}
});
@@ -3123,10 +2970,9 @@ public class CommandLoader {
public void loadAliases() {
commands = new HashMap<>();
aliasCommandNames.clear();
configurePlayerCommand();
// Bukkit registers plugin.yml commands before this loader runs.
if (!startupLoadCommandAliases) {
if (!plugin.getConfigFile().isLoadCommandAliases()) {
unregisterOptionalPluginYMLCommands();
} else {
unregisterDisabledPluginYMLCommands();
@@ -3134,7 +2980,7 @@ public class CommandLoader {
// If false: still wire permissions, but don't wire alias executors/tab
// completers.
final boolean enableAliases = startupLoadCommandAliases;
final boolean enableAliases = plugin.getConfigFile().isLoadCommandAliases();
// ---------------------------
// /vote aliases
@@ -3166,18 +3012,16 @@ public class CommandLoader {
}
registerAdditionalPermissions(Bukkit.getPluginManager(), cmdHandle);
if (argLength > 0 && voteCommandEnabled) {
if (argLength > 0) {
String[] args = cmdHandle.getArgs()[0].split("&");
for (String arg : args) {
String commandName = "vote" + arg;
// A renamed root may equal a synthetic alias absent from plugin.yml.
if (ownedCommand(commandName) == playerRootCommand && playerRootCommand != null) continue;
commands.put(commandName, cmdHandle);
aliasCommandNames.add(commandName.toLowerCase(Locale.ROOT));
try {
PluginCommand command = ownedCommand(commandName);
PluginCommand command = plugin.getCommand(commandName);
if (command == null) {
plugin.devDebug("Command " + commandName + " not found in plugin.yml");
continue;
@@ -3251,13 +3095,11 @@ public class CommandLoader {
for (String arg : args) {
String commandName = "adminvote" + arg;
// A renamed root may equal a synthetic alias absent from plugin.yml.
if (ownedCommand(commandName) == playerRootCommand && playerRootCommand != null) continue;
commands.put(commandName, cmdHandle);
aliasCommandNames.add(commandName.toLowerCase(Locale.ROOT));
try {
PluginCommand command = ownedCommand(commandName);
PluginCommand command = plugin.getCommand(commandName);
if (command == null) {
plugin.devDebug("Command " + commandName + " not found in plugin.yml");
continue;
@@ -3323,8 +3165,8 @@ public class CommandLoader {
|| commandName.equalsIgnoreCase("av")) {
continue;
}
PluginCommand command = ownedCommand(commandName);
if (command != null && command != playerRootCommand) {
PluginCommand command = plugin.getCommand(commandName);
if (command != null) {
unregisterCommand(commandMap, command);
}
}
@@ -3338,8 +3180,8 @@ public class CommandLoader {
try {
CommandMap commandMap = getCommandMap();
for (String commandName : disabledAliasCommandNames) {
PluginCommand command = ownedCommand(commandName);
if (command != null && command != playerRootCommand) {
PluginCommand command = plugin.getCommand(commandName);
if (command != null) {
unregisterCommand(commandMap, command);
}
}
@@ -3351,7 +3193,22 @@ public class CommandLoader {
/** Removes the command and all labels that still point to it from Bukkit's map. */
private void unregisterCommand(CommandMap commandMap, PluginCommand command) throws ReflectiveOperationException {
command.unregister(commandMap);
Map<String, org.bukkit.command.Command> knownCommands = getKnownCommands(commandMap);
java.lang.reflect.Field field = null;
Class<?> commandMapClass = commandMap.getClass();
while (commandMapClass != null && field == null) {
try {
field = commandMapClass.getDeclaredField("knownCommands");
} catch (NoSuchFieldException ignored) {
commandMapClass = commandMapClass.getSuperclass();
}
}
if (field == null) {
throw new NoSuchFieldException("knownCommands");
}
field.setAccessible(true);
@SuppressWarnings("unchecked")
Map<String, org.bukkit.command.Command> knownCommands =
(Map<String, org.bukkit.command.Command>) field.get(commandMap);
Set<String> removedLabels = new HashSet<>();
for (Map.Entry<String, org.bukkit.command.Command> entry : knownCommands.entrySet()) {
if (entry.getValue() == command) {
@@ -3380,27 +3237,6 @@ public class CommandLoader {
}
}
/** Reads the same Bukkit-owned map used by exact-object unregister. */
private Map<String, org.bukkit.command.Command> getKnownCommands(CommandMap commandMap) throws ReflectiveOperationException {
java.lang.reflect.Field field = null;
Class<?> commandMapClass = commandMap.getClass();
while (commandMapClass != null && field == null) {
try {
field = commandMapClass.getDeclaredField("knownCommands");
} catch (NoSuchFieldException ignored) {
commandMapClass = commandMapClass.getSuperclass();
}
}
if (field == null) {
throw new NoSuchFieldException("knownCommands");
}
field.setAccessible(true);
@SuppressWarnings("unchecked")
Map<String, org.bukkit.command.Command> knownCommands =
(Map<String, org.bukkit.command.Command>) field.get(commandMap);
return knownCommands;
}
/** Gets Bukkit's command map without depending on a CraftBukkit package name. */
private CommandMap getCommandMap() throws ReflectiveOperationException {
java.lang.reflect.Method method = plugin.getServer().getClass().getMethod("getCommandMap");
@@ -3464,6 +3300,14 @@ public class CommandLoader {
* Load tab complete.
*/
public void loadTabComplete() {
TabCompleteHandler.getInstance().addTabCompleteOption(new TabCompleteHandle("(npcid)", new ArrayList<>()) {
@Override public void reload() { updateReplacements(); }
@Override public void updateReplacements() {
var manager = plugin.getVotingNPCManager();
setReplace(manager == null ? new ArrayList<>() : new ArrayList<>(manager.definitions().stream()
.map(com.bencodez.votingplugin.npc.VotingNPCDefinition::id).toList()));
}
});
ArrayList<String> sites = new ArrayList<>();
for (VoteSite site : plugin.getVoteSiteManager().getVoteSitesEnabled()) {
sites.add(site.getKey());
@@ -4234,9 +4078,6 @@ public class CommandLoader {
}
}
// Preserve administrator-defined matches ahead of this new fallback.
com.bencodez.votingplugin.streaks.VoteStreaksCommand.register(plugin);
ArrayList<CommandHandler> avCommands = com.bencodez.advancedcore.command.CommandLoader.getInstance()
.getBasicCommands("VotingPlugin");
for (CommandHandler cmd : avCommands) {
@@ -4303,7 +4144,7 @@ public class CommandLoader {
} else if (MessageAPI.startsWithIgnoreCase(slot, "today")) {
new VoteToday(plugin, player, user, 1).open();
} else if (MessageAPI.startsWithIgnoreCase(slot, "help")) {
performVoteCommand(player, "help");
player.performCommand("vote help");
} else if (MessageAPI.startsWithIgnoreCase(slot, "shop")) {
new VoteShop(plugin, player, user).open();
} else if (MessageAPI.startsWithIgnoreCase(slot, "lastmonth")) {
@@ -4312,8 +4153,6 @@ public class CommandLoader {
new VoteBest(plugin, player, user).open();
} else if (MessageAPI.startsWithIgnoreCase(slot, "streak")) {
new VoteStreak(plugin, player, user).open();
} else if (MessageAPI.startsWithIgnoreCase(slot, "streaks")) {
plugin.getVoteStreaksMenu().open(player);
}
}
@@ -74,7 +74,7 @@ public class CommandAliases implements CommandExecutor {
if (adminCommand) {
sender.sendMessage(MessageAPI.colorize(plugin.getConfigFile().getFormatInvalidCommandAdminVote()));
} else {
sender.sendMessage(MessageAPI.colorize(plugin.formatVoteCommandMessage(plugin.getConfigFile().getFormatInvalidCommandVote())));
sender.sendMessage(MessageAPI.colorize(plugin.getConfigFile().getFormatInvalidCommandVote()));
}
return true;
}
@@ -35,7 +35,7 @@ public class CommandVote implements CommandExecutor {
}
// invalid command
sender.sendMessage(MessageAPI.colorize(plugin.formatVoteCommandMessage(plugin.getConfigFile().getFormatInvalidCommandVote())));
sender.sendMessage(MessageAPI.colorize(plugin.getConfigFile().getFormatInvalidCommandVote()));
return true;
}
@@ -77,16 +77,16 @@ public class AdminVotePerms extends GUIHandler {
for (CommandHandler handle : plugin.getVoteCommand()) {
if (sender instanceof Player) {
if (handle.hasPerm(sender)) {
msg.add("&6" + handle.getHelpLineCommand(plugin.getVoteCommandPrefix()) + " : "
msg.add("&6" + handle.getHelpLineCommand("/vote") + " : "
+ handle.getPerm().split(Pattern.quote("|"))[0] + " : &atrue");
} else {
msg.add("&6" + handle.getHelpLineCommand(plugin.getVoteCommandPrefix()) + " : "
msg.add("&6" + handle.getHelpLineCommand("/vote") + " : "
+ handle.getPerm().split(Pattern.quote("|"))[0] + " : &cfalse");
}
} else {
msg.add(handle.getHelpLineCommand(plugin.getVoteCommandPrefix()) + " : " + handle.getPerm().split(Pattern.quote("|"))[0]);
msg.add(handle.getHelpLineCommand("/vote") + " : " + handle.getPerm().split(Pattern.quote("|"))[0]);
}
addAdditionalPermissions(msg, sender, handle, plugin.getVoteCommandPrefix());
addAdditionalPermissions(msg, sender, handle, "/vote");
}
@@ -164,13 +164,13 @@ public class AdminVotePerms extends GUIHandler {
for (CommandHandler handle : plugin.getVoteCommand()) {
if (handle.hasPerm(p)) {
msg.add("&6" + handle.getHelpLineCommand(plugin.getVoteCommandPrefix()) + " : "
msg.add("&6" + handle.getHelpLineCommand("/vote") + " : "
+ handle.getPerm().split(Pattern.quote("|"))[0] + " : &atrue");
} else {
msg.add("&6" + handle.getHelpLineCommand(plugin.getVoteCommandPrefix()) + " : "
msg.add("&6" + handle.getHelpLineCommand("/vote") + " : "
+ handle.getPerm().split(Pattern.quote("|"))[0] + " : &cfalse");
}
addAdditionalPermissions(msg, p, handle, plugin.getVoteCommandPrefix());
addAdditionalPermissions(msg, p, handle, "/vote");
}
@@ -237,7 +237,7 @@ public class AdminVotePerms extends GUIHandler {
msg.add(" ");
for (CommandHandler handle : plugin.getVoteCommand()) {
msg.add(handle.getHelpLineCommand(plugin.getVoteCommandPrefix()));
msg.add(handle.getHelpLineCommand("/vote"));
msg.add(" " + handle.getPerm());
msg.add(" " + handle.getHelpMessage());
for (String permission : additionalPermissions(handle)) {
@@ -80,7 +80,7 @@ public class AdminVoteTopPoints extends GUIHandler {
LinkedHashMap<TopVoterPlayer, Integer> raw = new LinkedHashMap<>();
for (String uuidString : plugin.getVotingPluginUserManager().getAllUUIDs()) {
UUID uuid = UUID.fromString(uuidString);
VotingPluginUser vpUser = plugin.getVotingPluginUserManager().getVotingPluginUser(uuid, true);
VotingPluginUser vpUser = plugin.getVotingPluginUserManager().getVotingPluginUser(uuid);
vpUser.userDataFetechMode(UserDataFetchMode.NO_CACHE);
int points = vpUser.getPoints();
if (points <= 0) continue;
@@ -55,7 +55,6 @@ public class VoteHelp extends GUIHandler {
*/
public ArrayList<TextComponent> helpText(CommandSender sender) {
ArrayList<TextComponent> msg = new ArrayList<>();
if (!plugin.isVoteCommandEnabled()) return msg;
HashMap<String, TextComponent> unsorted = new HashMap<>();
boolean requirePerms = plugin.getConfigFile().isFormatCommandsVoteHelpRequirePermission();
@@ -71,7 +70,7 @@ public class VoteHelp extends GUIHandler {
}
for (CommandHandler cmdHandle : plugin.getVoteCommand()) {
if (!requirePerms || cmdHandle.hasPerm(sender)) {
unsorted.put(cmdHandle.getHelpLineCommand(plugin.getVoteCommandPrefix()), cmdHandle.getHelpLine(plugin.getVoteCommandPrefix(),
unsorted.put(cmdHandle.getHelpLineCommand("/vote"), cmdHandle.getHelpLine("/vote",
plugin.getConfigFile().getFormatCommandsVoteHelpLine(), hoverColor));
}
}
@@ -93,15 +92,14 @@ public class VoteHelp extends GUIHandler {
*/
public ArrayList<TextComponent> helpTextLegacy(CommandSender sender) {
ArrayList<TextComponent> msg = new ArrayList<>();
if (!plugin.isVoteCommandEnabled()) return msg;
HashMap<String, TextComponent> unsorted = new HashMap<>();
boolean requirePerms = plugin.getConfigFile().isFormatCommandsVoteHelpRequirePermission();
for (CommandHandler cmdHandle : plugin.getVoteCommand()) {
if (!requirePerms || cmdHandle.hasPerm(sender)) {
unsorted.put(cmdHandle.getHelpLineCommand(plugin.getVoteCommandPrefix()),
cmdHandle.getHelpLine(plugin.getVoteCommandPrefix(), plugin.getConfigFile().getFormatCommandsVoteHelpLine()));
unsorted.put(cmdHandle.getHelpLineCommand("/vote"),
cmdHandle.getHelpLine("/vote", plugin.getConfigFile().getFormatCommandsVoteHelpLine()));
}
}
ArrayList<String> unsortedList = new ArrayList<>();
@@ -60,7 +60,7 @@ public class VoteToday extends GUIHandler {
Player clicked = player.getServer().getPlayer(payload.owner());
if (clicked != null) {
VotingPluginUser clickedUser = plugin.getVotingPluginUserManager()
.getVotingPluginUser(uuid, true);
.getVotingPluginUser(uuid);
new VoteGUI(plugin, clicked, clickedUser).open(
GUIMethod.valueOf(plugin.getGui().getGuiMethodGUI().toUpperCase()));
}
@@ -161,7 +161,7 @@ public class VoteToday extends GUIHandler {
inv.addButton(inv.getNextSlot(), new BInventoryButton(item) {
@Override
public void onClick(ClickEvent clickEvent) {
VotingPluginUser user = plugin.getVotingPluginUserManager().getVotingPluginUser(uuid, true);
VotingPluginUser user = plugin.getVotingPluginUserManager().getVotingPluginUser(uuid);
new VoteGUI(plugin, player, user)
.open(GUIMethod.valueOf(plugin.getGui().getGuiMethodGUI().toUpperCase()));
}
@@ -51,7 +51,7 @@ public class VoteTopVoter extends GUIHandler {
String topVoter = top.getName();
@SuppressWarnings("unchecked")
LinkedHashMap<TopVoterPlayer, Integer> topVotes = (LinkedHashMap<TopVoterPlayer, Integer>) plugin.getTopVoterDisplay(top)
LinkedHashMap<TopVoterPlayer, Integer> topVotes = (LinkedHashMap<TopVoterPlayer, Integer>) plugin.getTopVoter(top)
.clone();
com.bencodez.simpleapi.dialog.MultiActionDialogBuilder dialog = plugin.getDialogService().multiAction(player)
@@ -148,7 +148,7 @@ public class VoteTopVoter extends GUIHandler {
String topVoter = top.getName();
@SuppressWarnings("unchecked")
LinkedHashMap<TopVoterPlayer, Integer> topVotes = (LinkedHashMap<TopVoterPlayer, Integer>) plugin
.getTopVoterDisplay(top).clone();
.getTopVoter(top).clone();
users = topVotes.entrySet();
ConfigurationSection customization = plugin.getGui().getChestVoteTopCustomization();
@@ -31,7 +31,7 @@ public class VoteTopVoterLastMonth extends GUIHandler {
@Override
public void onDialog(Player player) {
Set<Entry<TopVoterPlayer, Integer>> users = plugin.getLastMonthTopVoterDisplay().entrySet();
Set<Entry<TopVoterPlayer, Integer>> users = plugin.getLastMonthTopVoter().entrySet();
com.bencodez.simpleapi.dialog.MultiActionDialogBuilder dialog = plugin.getDialogService().multiAction(player)
.placeholder("player", user.getPlayerName())
@@ -91,7 +91,7 @@ public class VoteTopVoterLastMonth extends GUIHandler {
public void onChest(Player player) {
Set<Entry<TopVoterPlayer, Integer>> users = null;
users = plugin.getLastMonthTopVoterDisplay().entrySet();
users = plugin.getLastMonthTopVoter().entrySet();
BInventory inv = new BInventory(plugin.getGui().getChestVoteTopName());
inv.addPlaceholder("topvoter", "Last Month");
@@ -60,7 +60,7 @@ public class VoteTopVoterPreviousMonths extends GUIHandler {
return;
}
Set<Entry<TopVoterPlayer, Integer>> users = plugin.getPreviousMonthTopVoterDisplay(yearMonth).entrySet();
Set<Entry<TopVoterPlayer, Integer>> users = plugin.getPreviousMonthsTopVoters().get(yearMonth).entrySet();
com.bencodez.simpleapi.dialog.MultiActionDialogBuilder dialog = plugin.getDialogService().multiAction(player)
.placeholder("player", user.getPlayerName())
@@ -160,7 +160,7 @@ public class VoteTopVoterPreviousMonths extends GUIHandler {
player.sendMessage(ChatColor.RED + "Can't open previous months, no data");
return;
}
users = plugin.getPreviousMonthTopVoterDisplay(yearMonth).entrySet();
users = plugin.getPreviousMonthsTopVoters().get(yearMonth).entrySet();
BInventory inv = new BInventory(plugin.getGui().getChestVoteTopName());
inv.addPlaceholder("topvoter", yearMonth.toString());
@@ -177,7 +177,7 @@ public class VoteURL extends GUIHandler {
}
if (plugin.getGui().isChestVoteURLBackButton()) {
dialog.button("&eBack", "&7Return to previous menu", payload -> plugin.getCommandLoader().performVoteCommand(player, "gui"));
dialog.button("&eBack", "&7Return to previous menu", payload -> player.performCommand("vote gui"));
}
dialog.open();
@@ -24,6 +24,9 @@ import com.bencodez.votingplugin.topvoter.TopVoter;
import lombok.Getter;
public class Config extends YMLFile {
/** Opt-in persistent vanilla voting NPCs; missing configuration preserves legacy behavior. */
public boolean isVotingNPCsEnabled() { return getData().getBoolean("VotingNPCs.Enabled", false); }
/** Explicit permission for executable deployment over private-network plaintext HTTP. */
public boolean getControlAllowInsecureHttpPluginDeployment() {
@@ -522,15 +525,6 @@ public class Config extends YMLFile {
@Getter
private boolean limitMonthlyVotes = false;
/** Restart-only player command registration. Missing keys preserve /vote. */
@ConfigDataBoolean(path = "VoteCommandEnabled", defaultValue = true)
@Getter
private boolean voteCommandEnabled = true;
@ConfigDataString(path = "VoteCommandName", defaultValue = "vote")
@Getter
private String voteCommandName = "vote";
@ConfigDataBoolean(path = "LoadCommandAliases")
@Getter
private boolean loadCommandAliases = true;
@@ -809,10 +803,6 @@ public class Config extends YMLFile {
@Getter
private boolean topVoterAwardsTies = true;
@ConfigDataBoolean(path = "HideTopVoterIfNotPlayedBefore")
@Getter
private boolean hideTopVoterIfNotPlayedBefore = false;
@ConfigDataBoolean(path = "TopVoterIgnorePermission")
@Getter
private boolean topVoterIgnorePermission = false;
@@ -26,10 +26,6 @@ import lombok.Getter;
*/
public class GUI extends YMLFile {
@ConfigDataString(path = "CHEST.VoteStreaks.Name")
@Getter
private String chestVoteStreaksName = "&6Vote streaks";
@ConfigDataString(path = "BOOK.VoteURLBookGUI.AlreadyVotedColor")
@Getter
private String bookVoteURLBookGUIAlreadyVotedColor = "RED";
@@ -11,13 +11,10 @@ import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import com.bencodez.advancedcore.api.rewards.Reward;
import com.bencodez.advancedcore.api.rewards.RewardOptions;
import com.bencodez.advancedcore.api.user.AdvancedCoreUser;
import com.bencodez.advancedcore.api.user.UserDataFetchMode;
@@ -39,14 +36,12 @@ public class CoolDownCheck implements Listener {
private final VotingPluginMain plugin;
private final Map<UUID, ScheduledFuture<?>> perSiteTasks = new ConcurrentHashMap<>();
private final Map<UUID, Object> perSiteGenerations = new ConcurrentHashMap<>();
private final Map<UUID, ScheduledFuture<?>> allSiteTasks = new ConcurrentHashMap<>();
@Getter
private final ScheduledExecutorService timer;
private volatile boolean cooldownCheckEnabled = false;
private volatile boolean stopped = false;
/**
* Constructs a new cooldown check manager.
@@ -79,8 +74,6 @@ public class CoolDownCheck implements Listener {
* Shuts down the cooldown check timer.
*/
public void shutdown() {
stopped = true;
perSiteGenerations.clear();
timer.shutdownNow();
for (ScheduledFuture<?> f : perSiteTasks.values()) {
@@ -154,7 +147,6 @@ public class CoolDownCheck implements Listener {
user.updateTempCacheWithColumns(cols);
cols.clear(); // help GC (only useful if reused)
}
capturePlayerName(user);
checkPerSite(site, user);
} finally {
@@ -227,20 +219,13 @@ public class CoolDownCheck implements Listener {
* Site-specific version used by batch checks / checkAllVoteSite.
*/
private void checkPerSite(VoteSite site, VotingPluginUser user) {
checkPerSite(site, user, null);
}
private HashMap<String, Boolean> checkPerSite(VoteSite site, VotingPluginUser user,
HashMap<String, Boolean> coolDownChecks) {
if (!plugin.getConfigFile().isPerSiteCoolDownEvents() || site == null) {
return coolDownChecks;
return;
}
if (coolDownChecks == null) {
coolDownChecks = user.getCoolDownCheckSiteList();
}
HashMap<String, Boolean> coolDownChecks = user.getCoolDownCheckSiteList();
if (Boolean.TRUE.equals(coolDownChecks.get(site.getKey()))) {
return coolDownChecks;
return;
}
if (user.canVoteSite(site)) {
@@ -252,7 +237,6 @@ public class CoolDownCheck implements Listener {
PlayerVoteSiteCoolDownEndEvent event = new PlayerVoteSiteCoolDownEndEvent(user, site);
plugin.getServer().getPluginManager().callEvent(event);
}
return coolDownChecks;
}
/**
@@ -283,8 +267,8 @@ public class CoolDownCheck implements Listener {
*/
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onCoolDownEnd(PlayerVoteCoolDownEndEvent event) {
dispatchCooldownReward(event.getPlayer(), plugin.getSpecialRewardsConfig().getData(),
"VoteCoolDownEndedReward", "all", new RewardOptions());
plugin.getRewardHandler().giveReward(event.getPlayer(), plugin.getSpecialRewardsConfig().getData(),
"VoteCoolDownEndedReward", new RewardOptions());
}
/**
@@ -294,73 +278,11 @@ public class CoolDownCheck implements Listener {
*/
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onCoolDownEnd(PlayerVoteSiteCoolDownEndEvent event) {
dispatchCooldownReward(event.getPlayer(), event.getSite().getSiteData(), "CoolDownEndRewards",
"site:" + event.getSite().getKey(), new RewardOptions()
.addPlaceholder("sitename", event.getSite().getDisplayName())
plugin.getRewardHandler().giveReward(event.getPlayer(), event.getSite().getSiteData(), "CoolDownEndRewards",
new RewardOptions().addPlaceholder("sitename", event.getSite().getDisplayName())
.addPlaceholder("url", event.getSite().getVoteURL(false)));
}
private void dispatchCooldownReward(VotingPluginUser user, ConfigurationSection data, String path,
String site, RewardOptions options) {
boolean configured = false;
try {
configured = hasConfiguredCooldownReward(data, path);
} catch (RuntimeException ignored) {
// Preserve legacy dispatch even when diagnostic configuration inspection fails.
}
if (!configured) {
plugin.getRewardHandler().giveReward(user, data, path, options);
return;
}
String occurrence = UUID.randomUUID().toString();
String player = user.getUUID();
String safeSite = String.valueOf(site).replaceAll("[\\r\\n\\p{Cntrl}]", "?");
long time = System.currentTimeMillis();
String context = " occurrence=" + occurrence + " player=" + player + " site=" + safeSite + " time=" + time;
logCooldownDiagnostic(false, "Cooldown reward status=attempted" + context);
options.setAsyncFailureObserver(failure -> logCooldownFailure(context, failure));
try {
plugin.getRewardHandler().giveReward(user, data, path, options);
} catch (RuntimeException | Error failure) {
logCooldownFailure(context, failure);
throw failure;
}
}
private boolean hasConfiguredCooldownReward(ConfigurationSection data, String path) {
if (data == null) return false;
if (data instanceof FileConfiguration) {
return plugin.getRewardHandler().hasRewards((FileConfiguration) data, path);
}
if (data.isList(path)) return !data.getList(path, new ArrayList<>()).isEmpty();
if (data.isConfigurationSection(path)) return !data.getConfigurationSection(path).getKeys(false).isEmpty();
return data.isString(path) && !data.getString(path, "").isEmpty();
}
private void logCooldownFailure(String context, Throwable failure) {
int completed = -1;
Throwable current = failure;
for (int depth = 0; current != null && depth < 32; depth++, current = current.getCause()) {
if (current instanceof Reward.RewardReplayFailure) {
completed = ((Reward.RewardReplayFailure) current).getCompletedInjectionCount();
break;
}
}
String error = failure == null ? "unknown" : failure.getClass().getSimpleName();
logCooldownDiagnostic(true, "Cooldown reward outcome=unknown/partial" + context + " error=" + error
+ " completedInjections=" + (completed < 0 ? "unknown" : completed)
+ "; inspect effects before reissuing");
}
private void logCooldownDiagnostic(boolean warning, String message) {
try {
if (warning) plugin.getLogger().warning(message);
else plugin.getLogger().info(message);
} catch (RuntimeException ignored) {
// A broken logger must not suppress or retry the reward.
}
}
/**
* Schedules a cooldown check for a user.
*
@@ -402,7 +324,7 @@ public class CoolDownCheck implements Listener {
* @param force whether to force the schedule
*/
public void schedulePerSite(VotingPluginUser user, boolean force) {
if (stopped || !plugin.getConfigFile().isPerSiteCoolDownEvents()) {
if (!plugin.getConfigFile().isPerSiteCoolDownEvents()) {
return;
}
@@ -411,7 +333,6 @@ public class CoolDownCheck implements Listener {
}
final UUID uuid = user.getJavaUUID();
final String scheduledName = user.getPlayerName();
final NextSite next = user.getNextSiteAvailable();
@@ -419,13 +340,8 @@ public class CoolDownCheck implements Listener {
if (existing != null) {
existing.cancel(false);
}
if (stopped) {
perSiteGenerations.remove(uuid);
return null;
}
if (next == null || next.getSite() == null || next.getSecondsUntilAvailable() <= 0) {
perSiteGenerations.remove(uuid);
plugin.extraDebug(user.getUUID() + "/" + user.getPlayerName() + " not scheduling per-site cooldown check");
return null; // remove entry
}
@@ -433,58 +349,19 @@ public class CoolDownCheck implements Listener {
plugin.devDebug("PerSiteCoolDownEvent schedule: site=" + next.getSite().getKey() + " time="
+ next.getSecondsUntilAvailable() + " seconds");
Object generation = new Object();
perSiteGenerations.put(uuid, generation);
try {
return timer.schedule(() -> runPerSiteTimer(uuid, scheduledName, next, generation, 0),
next.getSecondsUntilAvailable() + 2, TimeUnit.SECONDS);
} catch (RuntimeException | Error failure) {
perSiteGenerations.remove(uuid, generation);
throw failure;
}
});
}
private void runPerSiteTimer(UUID uuid, String scheduledName, NextSite next, Object generation, int retries) {
if (stopped || !plugin.isEnabled() || perSiteGenerations.get(uuid) != generation) return;
UUID occurrence = UUID.randomUUID();
boolean[] retried = { false };
try {
VotingPluginUser current;
try {
// The batch user's temporary row may have been cleared or replaced by a newer vote.
current = plugin.getVotingPluginUserManager().getVotingPluginUser(uuid, false);
if (!current.isCached()) current.userDataFetechMode(UserDataFetchMode.NO_CACHE);
String storedName = current.getData().getString("PlayerName", current.getUserDataFetchMode());
String name = storedName != null && !storedName.isBlank() ? storedName : scheduledName;
if (name != null && !name.isBlank()) current.setPlayerName(name);
} catch (RuntimeException refreshFailure) {
if (retries < 3) {
perSiteTasks.compute(uuid, (key, existing) -> {
if (stopped || !plugin.isEnabled() || perSiteGenerations.get(uuid) != generation) return existing;
ScheduledFuture<?> retry = timer.schedule(
() -> runPerSiteTimer(uuid, scheduledName, next, generation, retries + 1),
30, TimeUnit.SECONDS);
retried[0] = true;
return retry;
});
if (retried[0]) return;
return timer.schedule(() -> {
if (!plugin.isEnabled()) {
return;
}
throw refreshFailure;
}
if (perSiteGenerations.get(uuid) != generation) return;
checkPerSite(next.getSite(), current);
if (perSiteGenerations.get(uuid) == generation) schedulePerSite(current, false);
} catch (RuntimeException | Error failure) {
String siteKey = String.valueOf(next.getSite().getKey()).replaceAll("[\\r\\n\\p{Cntrl}]", "?");
logCooldownDiagnostic(true, "Cooldown timer failed: occurrence=" + occurrence + " player=" + uuid
+ " site=" + siteKey + " time=" + System.currentTimeMillis() + " error="
+ failure.getClass().getSimpleName() + "; reward outcome is uncertain; inspect effects before reissuing");
throw failure;
} finally {
if (!retried[0]) perSiteGenerations.remove(uuid, generation);
}
// Only check the next site; this will set the cooldown-end flag + fire event if ready
checkPerSite(next.getSite(), user);
// Schedule the following site (if any)
schedulePerSite(user, false);
}, next.getSecondsUntilAvailable() + 2, TimeUnit.SECONDS);
});
}
/**
@@ -504,14 +381,6 @@ public class CoolDownCheck implements Listener {
}
}
/** Preserve the name needed by asynchronous rewards after the temporary row is cleared. */
private static void capturePlayerName(VotingPluginUser user) {
String name = user.getPlayerName();
if (name != null && !name.isBlank()) {
user.setPlayerName(name);
}
}
/**
* Performance-optimized: scan users ONCE, process all daily-delay sites.
*/
@@ -552,11 +421,9 @@ public class CoolDownCheck implements Listener {
user.updateTempCacheWithColumns(cols);
cols.clear();
}
capturePlayerName(user);
HashMap<String, Boolean> coolDownChecks = null;
for (int i = 0; i < dailySites.size(); i++) {
coolDownChecks = checkPerSite(dailySites.get(i), user, coolDownChecks);
checkPerSite(dailySites.get(i), user);
}
check(user);
@@ -1,127 +0,0 @@
package com.bencodez.votingplugin.core.maintenance;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
/**
* Cumulative active-runtime clock for the owner-facing auto-create setup reminder.
* This class performs no persistence or notification. One owned worker must
* serialize the entire propose, persist, commit, then notify sequence, including
* reload and shutdown checkpoints. Method synchronization alone does not serialize
* the external persistence step. Only notify after a successful commit.
*
* <p>Reconstruct this state from its durable snapshot and a fresh monotonic clock
* reading on startup; never persist the process-local clock anchor. Samples must
* be less than {@link Long#MAX_VALUE} nanoseconds apart (the normal nanoTime elapsed
* time contract). Negative clock readings and signed clock wrap are supported.
*/
public final class AutoCreateVoteSitesReminderState {
public static final long NEVER_REMINDED = -1;
/** The first reminder is emitted on the first active checkpoint. */
public static final long DEFAULT_THRESHOLD_MILLIS = 0;
/** Subsequent reminders are bounded to one every 48 active hours. */
public static final long DEFAULT_REPEAT_MILLIS = TimeUnit.HOURS.toMillis(48);
public static final long MAX_INTERVAL_MILLIS = Long.MAX_VALUE / 1_000_000;
private static final long NANOS_PER_MILLI = 1_000_000;
/** Immutable durable data; a reminder marker must refer to accrued runtime. */
public record Snapshot(long totalRuntimeMillis, long lastReminderRuntimeMillis) {
public Snapshot {
if (totalRuntimeMillis < 0 || lastReminderRuntimeMillis < NEVER_REMINDED
|| lastReminderRuntimeMillis > totalRuntimeMillis) {
throw new IllegalArgumentException("Invalid reminder runtime snapshot");
}
}
}
/**
* A tentative checkpoint, valid only until this state commits any candidate.
* Persist {@link #snapshot()} before committing; discard on a failed write and
* propose again. Creating or discarding candidates changes no committed state.
*/
public static final class Candidate {
private final Object epoch;
private final Snapshot snapshot;
private final long checkpointNanos;
private final boolean reminderDue;
private Candidate(Object epoch, Snapshot snapshot, long checkpointNanos, boolean reminderDue) {
this.epoch = epoch;
this.snapshot = snapshot;
this.checkpointNanos = checkpointNanos;
this.reminderDue = reminderDue;
}
public Snapshot snapshot() {
return snapshot;
}
public boolean reminderDue() {
return reminderDue;
}
}
private Snapshot snapshot;
private long checkpointNanos;
private Object epoch = new Object();
public AutoCreateVoteSitesReminderState(Snapshot snapshot, long nowNanos) {
this.snapshot = Objects.requireNonNull(snapshot, "snapshot");
this.checkpointNanos = nowNanos;
}
public synchronized Snapshot snapshot() {
return snapshot;
}
/**
* Accrue runtime regardless of either flag. Both flags are required to propose a
* reminder, at the inclusive threshold or repeat boundary. Settings are sampled
* for each proposal; changing them does not reset accumulated runtime or markers.
* Backward samples accrue nothing and leave the clock anchor unchanged.
*/
public synchronized Candidate propose(long nowNanos, boolean reminderEnabled, boolean autoCreateEnabled,
long thresholdMillis, long repeatMillis) {
validateInterval(thresholdMillis);
validateInterval(repeatMillis);
if (repeatMillis == 0) {
throw new IllegalArgumentException("Reminder repeat interval must be positive");
}
long elapsedNanos = nowNanos - checkpointNanos;
long elapsedMillis = elapsedNanos > 0 ? elapsedNanos / NANOS_PER_MILLI : 0;
long total = saturatingAdd(snapshot.totalRuntimeMillis(), elapsedMillis);
long lastReminder = snapshot.lastReminderRuntimeMillis();
boolean due = reminderEnabled && autoCreateEnabled && total >= thresholdMillis
&& (lastReminder == NEVER_REMINDED || total - lastReminder >= repeatMillis);
Snapshot next = new Snapshot(total, due ? total : lastReminder);
// Consume only whole milliseconds so frequent checkpoints do not lose time.
long nextCheckpoint = checkpointNanos + elapsedMillis * NANOS_PER_MILLI;
return new Candidate(epoch, next, nextCheckpoint, due);
}
/**
* Publish a checkpoint only after its durable write succeeded. A successful
* commit invalidates every other candidate from that epoch, including this one.
* Foreign, stale, or duplicate candidates are rejected without changing state.
*/
public synchronized void commit(Candidate candidate) {
Objects.requireNonNull(candidate, "candidate");
if (candidate.epoch != epoch) {
throw new IllegalArgumentException("Candidate is not current for this reminder state");
}
snapshot = candidate.snapshot;
checkpointNanos = candidate.checkpointNanos;
epoch = new Object();
}
private static void validateInterval(long millis) {
if (millis < 0 || millis > MAX_INTERVAL_MILLIS) {
throw new IllegalArgumentException("Reminder interval is outside the supported range");
}
}
private static long saturatingAdd(long total, long elapsed) {
return elapsed > Long.MAX_VALUE - total ? Long.MAX_VALUE : total + elapsed;
}
}
@@ -1,247 +0,0 @@
package com.bencodez.votingplugin.data;
import java.io.File;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.function.Consumer;
import java.util.function.Supplier;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.plugin.Plugin;
import com.bencodez.advancedcore.api.time.TimeType;
import com.bencodez.votingplugin.VotingPluginMain;
import com.bencodez.votingplugin.util.ServerDataPublicationFence;
/**
* Routes SDK publications through this generation's ownership lease. The SDK's
* original file/configuration remains authoritative; no YAML snapshot is copied.
*/
public final class GenerationFencedServerDataFile extends com.bencodez.advancedcore.data.ServerData {
private final com.bencodez.advancedcore.data.ServerData delegate;
private final ServerDataPublicationFence fence;
private final VotingPluginMain ownerPlugin;
public GenerationFencedServerDataFile(VotingPluginMain plugin,
com.bencodez.advancedcore.data.ServerData delegate, ServerDataPublicationFence fence) {
super(plugin);
this.ownerPlugin = java.util.Objects.requireNonNull(plugin);
this.delegate = java.util.Objects.requireNonNull(delegate);
this.fence = java.util.Objects.requireNonNull(fence);
}
public boolean wraps(com.bencodez.advancedcore.data.ServerData file) { return delegate == file; }
public boolean belongsTo(ServerDataPublicationFence owner) { return fence == owner; }
/** Checkpoint callers use the same monitor as native final publication. */
@Override public Object publicationMonitor() {
return java.util.Objects.requireNonNull(delegate.publicationMonitor(), "Server-data publication monitor");
}
private void withOwner(Runnable operation) {
try (var lease = fence.acquire()) {
synchronized (publicationMonitor()) {
try { operation.run(); }
catch (RuntimeException | Error failure) {
try { refreshVotePartyDisplay(); }
catch (RuntimeException | Error observationFailure) {
if (observationFailure != failure) failure.addSuppressed(observationFailure);
}
throw failure;
}
refreshVotePartyDisplay();
}
}
}
private <T> T withOwnedValue(Supplier<T> operation) {
try (var lease = fence.acquire()) {
synchronized (publicationMonitor()) { return operation.get(); }
}
}
@Override public FileConfiguration getData() { return delegate.getData(); }
@Override public File getdFile() { return delegate.getdFile(); }
@Override public JavaPlugin getPlugin() { return delegate.getPlugin(); }
@Override public boolean isJustCreated() { return delegate.isJustCreated(); }
@Override public boolean isFailedToRead() { return delegate.isFailedToRead(); }
@Override public boolean isIgnoreCase() { return delegate.isIgnoreCase(); }
@Override public void setIgnoreCase(boolean value) {
withOwner(() -> delegate.setIgnoreCase(value));
}
@Override public void createSection(String path) {
mutateOrdinaryData(data -> data.createSection(path));
}
@Override public void setData(FileConfiguration data) {
withOwner(() -> delegate.setData(data));
}
@Override public void setValue(String path, Object value) {
mutateOrdinaryData(data -> data.set(path, value));
}
@Override public void onFileCreation() {
withOwner(delegate::onFileCreation);
}
@Override public void setup() {
withOwner(delegate::setup);
}
@Override public void loadValues() {
withOwner(delegate::loadValues);
}
@Override public void reloadData() {
withOwner(delegate::reloadData);
}
private void refreshVotePartyDisplay() {
var wrapper = ownerPlugin.getServerData();
if (wrapper != null) {
synchronized (publicationMonitor()) {
if (delegate.getData() != null) wrapper.refreshVotePartyDisplay();
}
}
}
@Override public void saveData() {
withOwner(() -> {
refreshVotePartyDisplay();
delegate.saveData();
});
}
@Override public void saveDataChecked() {
withOwner(() -> {
refreshVotePartyDisplay();
delegate.saveDataChecked();
});
}
@Override protected void saveTimeChangeTransitionData() { saveDataChecked(); }
@Override public void mutateOrdinaryData(Consumer<FileConfiguration> mutation) {
// Delegate admission, live mutation and saving to the actual SDK owner.
// The projection is published inside that owner's callback before I/O.
withOwner(() -> delegate.mutateOrdinaryData(data -> applyOwnedMutation(mutation, data)));
}
private void refreshIfLiveMutation(FileConfiguration data) {
var wrapper = ownerPlugin.getServerData();
if (wrapper == null) return;
synchronized (publicationMonitor()) {
// Native final publication mutates a staged candidate first. Legacy
// adapters may instead mutate the live owner before their save.
if (data == delegate.getData()) wrapper.refreshVotePartyDisplay();
}
}
private void applyOwnedMutation(Consumer<FileConfiguration> mutation, FileConfiguration data) {
try { mutation.accept(data); }
catch (RuntimeException | Error failure) {
try { refreshIfLiveMutation(data); }
catch (RuntimeException | Error observationFailure) {
if (observationFailure != failure) failure.addSuppressed(observationFailure);
}
throw failure;
}
refreshIfLiveMutation(data);
}
private void finishFinalPublication(ServerDataPublicationFence.Lease lease,
CompletableFuture<Void> result, Throwable failure) {
Throwable outcome = failure;
try {
// Partial startup may have no display wrapper. In that case, do not
// introduce a YAML-observation dependency into final-stage drain.
refreshVotePartyDisplay();
} catch (Throwable observationFailure) {
if (outcome == null) outcome = observationFailure;
else if (outcome != observationFailure) outcome.addSuppressed(observationFailure);
}
// Refresh observes only the actual live owner; it never acknowledges a
// failed/cancelled publication or releases its retained generation.
if (outcome != null) { result.completeExceptionally(outcome); return; }
try { lease.close(); result.complete(null); }
catch (Throwable releaseFailure) { result.completeExceptionally(releaseFailure); }
}
/** Retain this handle only for retries of the same accepted mutation. */
FinalPublication prepareFinalPublication(Consumer<FileConfiguration> mutation) {
return new FinalPublication(mutation);
}
final class FinalPublication {
private final Consumer<FileConfiguration> mutation;
private ServerDataPublicationFence.Lease lease;
private CompletableFuture<Void> attempt;
private boolean publicationConfirmed;
private FinalPublication(Consumer<FileConfiguration> mutation) { this.mutation = mutation; }
CompletionStage<Void> publish() {
CompletableFuture<Void> result;
ServerDataPublicationFence.Lease owner;
boolean refreshOnly;
synchronized (this) {
if (attempt != null && !attempt.isCompletedExceptionally())
return attempt.minimalCompletionStage();
if (lease == null) {
try { lease = fence.acquire(); }
catch (Throwable failure) { return CompletableFuture.failedFuture(failure); }
}
owner = lease;
result = new CompletableFuture<>();
attempt = result;
refreshOnly = publicationConfirmed;
}
// No operation lock is held across the actual owner's YAML or I/O.
if (refreshOnly) finish(owner, result, null);
else {
try {
java.util.Objects.requireNonNull(mutation, "mutation");
java.util.Objects.requireNonNull(delegate.mutateFinalData(data -> applyOwnedMutation(mutation, data)))
.whenComplete((ignored, failure) -> finish(owner, result, failure));
} catch (Throwable failure) { finish(owner, result, failure); }
}
return result.minimalCompletionStage();
}
private void finish(ServerDataPublicationFence.Lease owner,
CompletableFuture<Void> result, Throwable failure) {
if (failure == null) {
synchronized (this) { publicationConfirmed = true; }
}
// A retry after a display-observation failure must not repeat a
// confirmed mutation. Failed publication instead retains this one
// lease until this same operation has a confirmed successful retry.
finishFinalPublication(owner, result, failure);
}
}
@Override public CompletionStage<Void> mutateFinalData(Consumer<FileConfiguration> mutation) {
// Ordinary one-shot callers retain failed ownership conservatively.
// A caller with an explicit retry contract retains the operation handle.
return prepareFinalPublication(mutation).publish();
}
@Override public void setData(String path, Object value) { mutateOrdinaryData(data -> data.set(path, value)); }
@Override public void setIgnoreTime(boolean value) { withOwner(() -> delegate.setIgnoreTime(value)); }
@Override public void setLastUpdated() { withOwner(delegate::setLastUpdated); }
@Override public void setPluginVersion(Plugin plugin) { withOwner(() -> delegate.setPluginVersion(plugin)); }
@Override public void setPrevDay(int value) { withOwner(() -> delegate.setPrevDay(value)); }
@Override public void setPrevMonth(String value) { withOwner(() -> delegate.setPrevMonth(value)); }
@Override public void setPrevWeekDay(int value) { withOwner(() -> delegate.setPrevWeekDay(value)); }
@Override public TimeChangeTransitionState beginTimeChangeTransition(TimeType type, String period, String marker) {
return withOwnedValue(() -> delegate.beginTimeChangeTransition(type, period, marker));
}
@Override public TimeChangeTransitionState getPendingTimeChangeTransition(TimeType type) {
return withOwnedValue(() -> delegate.getPendingTimeChangeTransition(type));
}
@Override public void completeTimeChangeTransition(TimeChangeTransitionState transition) {
withOwner(() -> delegate.completeTimeChangeTransition(transition));
}
@Override public void failTimeChangeTransition(TimeChangeTransitionState transition) {
withOwner(() -> delegate.failTimeChangeTransition(transition));
}
@Override public boolean isPendingTimeChangeTransition(TimeChangeTransitionState transition) {
return withOwnedValue(() -> delegate.isPendingTimeChangeTransition(transition));
}
}
@@ -18,182 +18,9 @@ import com.bencodez.votingplugin.signs.SignHandler;
import com.bencodez.votingplugin.timequeue.VoteTimeQueue;
import com.bencodez.votingplugin.topvoter.TopVoter;
public class ServerData {
/** Immutable live display values, separate from durable publication acknowledgement. */
public record VotePartyDisplay(int total, int extraRequired) {
public int required(int configured) { return extraRequired > 0 ? configured + extraRequired : configured; }
public int needed(int configured) { return required(configured) - total; }
}
private volatile VotePartyDisplay votePartyDisplay = new VotePartyDisplay(0, 0);
/** Snapshot-only: never acquires a YAML owner or waits for filesystem publication. */
public VotePartyDisplay getVotePartyDisplay() { return votePartyDisplay; }
/** Called during startup before placeholders are registered. */
public void refreshVotePartyDisplay() { mutateData(this::captureVotePartyDisplay); }
private void captureVotePartyDisplay() {
var data = getFile().getData().getConfigurationSection("VotingPlugin");
votePartyDisplay = data == null ? new VotePartyDisplay(0, 0)
: new VotePartyDisplay(data.getInt("VoteParty.Total"), data.getInt("VotePartyExtraRequired"));
}
public class ServerData {
private VotingPluginMain plugin = VotingPluginMain.plugin;
private volatile com.bencodez.advancedcore.data.ServerData generationFile;
private final Object generationBinding = new Object();
private volatile com.bencodez.votingplugin.util.ServerDataPublicationFence generationFence;
private com.bencodez.advancedcore.data.ServerData getFile() {
var current = generationFile;
if (current != null) return current;
synchronized (generationBinding) {
if (generationFile == null) {
var owner = getPublicationFence();
// Reject an old lazy wrapper before exposing successor mutable state.
try (var lease = owner == null ? null : owner.acquire()) {
var file = plugin.getServerDataFile();
if (file instanceof GenerationFencedServerDataFile guarded && !guarded.belongsTo(owner))
throw new IllegalStateException("Server-data file belongs to another generation");
generationFile = file;
}
}
return generationFile;
}
}
private record SignCoordinates(String world, int x, int y, int z) {
static SignCoordinates capture(Location location) {
return new SignCoordinates(location.getWorld().getName(), (int) location.getX(),
(int) location.getY(), (int) location.getZ());
}
void store(ConfigurationSection data, String path) {
data.set(path + ".World", world);
data.set(path + ".X", x);
data.set(path + ".Y", y);
data.set(path + ".Z", z);
}
}
/** Detached shutdown payload: no platform object is accessed by its publisher. */
public static final class SignSnapshot {
private final String count;
private final SignCoordinates location;
private final SignCoordinates skull;
private final String data;
private final int position;
private SignSnapshot(String count, Location location, Location skull, String data, int position) {
this.count = count;
this.location = SignCoordinates.capture(location);
this.skull = skull == null ? null : SignCoordinates.capture(skull);
this.data = data;
this.position = position;
}
private void store(ConfigurationSection target) {
location.store(target, "Signs." + count);
target.set("Signs." + count + ".Data", data);
target.set("Signs." + count + ".Position", position);
if (skull != null) skull.store(target, "Signs." + count + ".Skull");
}
}
public static SignSnapshot captureSignSnapshot(String count, Location location, Location skull,
String data, int position) {
return new SignSnapshot(count, location, skull, data, position);
}
private record ShutdownSignPublication(List<SignSnapshot> snapshot,
java.util.function.Supplier<java.util.concurrent.CompletionStage<Void>> publisher) { }
private final Object shutdownSignBinding = new Object();
private ShutdownSignPublication shutdownSignPublication;
/** Worker-only: one accepted sign batch, with the same publication owner across retries. */
public java.util.concurrent.CompletionStage<Void> publishShutdownSigns(List<SignSnapshot> signs) {
var snapshot = List.copyOf(signs);
ShutdownSignPublication publication;
synchronized (shutdownSignBinding) {
if (shutdownSignPublication == null) {
var file = getFile();
java.util.function.Consumer<org.bukkit.configuration.file.FileConfiguration> mutation = candidate -> {
var target = candidate.getConfigurationSection("VotingPlugin");
if (target == null) target = candidate.createSection("VotingPlugin");
for (var sign : snapshot) sign.store(target);
};
java.util.function.Supplier<java.util.concurrent.CompletionStage<Void>> publisher;
if (file instanceof GenerationFencedServerDataFile guarded) {
var retained = guarded.prepareFinalPublication(mutation);
publisher = retained::publish;
} else publisher = () -> file.mutateFinalData(mutation);
shutdownSignPublication = new ShutdownSignPublication(snapshot, publisher);
} else if (!shutdownSignPublication.snapshot().equals(snapshot)) {
return java.util.concurrent.CompletableFuture.failedFuture(
new IllegalStateException("Shutdown sign publication already owns a different batch"));
}
publication = shutdownSignPublication;
}
return publication.publisher().get();
}
/** Only YAML work belongs here; platform callbacks run outside the file owner. */
private void mutateData(Runnable mutation) {
var fence = getPublicationFence();
try (var owner = fence == null ? null : fence.acquire()) {
synchronized (publicationMonitor()) {
mutation.run();
}
}
}
/** Admit the complete ordinary mutation before changing live YAML or its display. */
private void mutateSavedData(Runnable mutation) {
mutateData(() -> getFile().mutateOrdinaryData(ignored -> {
try { mutation.run(); }
catch (RuntimeException | Error failure) {
try { captureVotePartyDisplay(); }
catch (RuntimeException | Error observationFailure) {
if (observationFailure != failure) failure.addSuppressed(observationFailure);
}
throw failure;
}
captureVotePartyDisplay();
}));
}
/** Store a scalar and save under the same YAML ownership as final SDK snapshots. */
public void setInt(String path, int value) {
mutateSavedData(() -> {
getData().set(path, value);
});
}
/** Store a detached string list, preventing later caller mutation of live YAML. */
public void setStringList(String path, List<String> values) {
var snapshot = values == null ? null : new ArrayList<>(values);
mutateSavedData(() -> {
getData().set(path, snapshot);
});
}
/** All mutations serialize with the actual SDK YAML owner. */
private Object publicationMonitor() {
var file = getFile();
return java.util.Objects.requireNonNull(file.publicationMonitor(), "Server-data publication monitor");
}
private com.bencodez.votingplugin.util.ServerDataPublicationFence getPublicationFence() {
var current = generationFence;
if (current != null) return current;
synchronized (generationBinding) {
if (generationFence == null) generationFence = plugin.getServerDataPublicationFence();
return generationFence;
}
}
/**
* Constructs a new ServerData.
@@ -202,7 +29,6 @@ public class ServerData {
*/
public ServerData(VotingPluginMain plugin) {
this.plugin = plugin;
this.generationFence = plugin.getServerDataPublicationFence();
}
/**
@@ -210,15 +36,13 @@ public class ServerData {
*
* @param placeholder the placeholder to add
*/
public void addAutoCachedPlaceholder(String placeholder) {
mutateData(() -> {
List<String> p = getAutoCachedPlaceholder();
if (!ArrayUtils.containsIgnoreCase(p, placeholder)) {
p.add(placeholder);
setAutoCachedPlaceholder(p);
}
});
public void addAutoCachedPlaceholder(String placeholder) {
List<String> p = getAutoCachedPlaceholder();
if (!ArrayUtils.containsIgnoreCase(p, placeholder)) {
p.add(placeholder);
setAutoCachedPlaceholder(p);
}
}
/**
@@ -226,14 +50,12 @@ public class ServerData {
*
* @param site the service site to add
*/
public void addServiceSite(String site) {
mutateData(() -> {
ArrayList<String> l = getServiceSites();
if (!getServiceSites().contains(site)) {
l.add(site);
}
setServiceSites(ArrayUtils.removeDuplicates(l));
});
public synchronized void addServiceSite(String site) {
ArrayList<String> l = getServiceSites();
if (!getServiceSites().contains(site)) {
l.add(site);
}
setServiceSites(ArrayUtils.removeDuplicates(l));
}
/**
@@ -243,20 +65,19 @@ public class ServerData {
* @param data the data
* @param position the position
*/
public void addSign(Location location, String data, int position) {
var coordinates = new SignCoordinates(location.getWorld().getName(), location.getBlockX(),
location.getBlockY(), location.getBlockZ());
int[] selected = new int[1];
mutateSavedData(() -> {
int count = nextSignNumber();
selected[0] = count;
coordinates.store(getData(), "Signs." + count);
getData().set("Signs." + count + ".Data", data);
getData().set("Signs." + count + ".Position", position);
});
String count = Integer.toString(selected[0]);
plugin.getSigns().getSigns().add(new SignHandler(plugin, count, getSignLocation(count),
getSignSkullLocation(count), getSignData(count), getSignPosition(count)));
public void addSign(Location location, String data, int position) {
int count = nextSignNumber();
getData().set("Signs." + count + ".World", location.getWorld().getName());
getData().set("Signs." + count + ".X", location.getBlockX());
getData().set("Signs." + count + ".Y", location.getBlockY());
getData().set("Signs." + count + ".Z", location.getBlockZ());
getData().set("Signs." + count + ".Data", data);
getData().set("Signs." + count + ".Position", position);
saveData();
plugin.getSigns().getSigns().add(new SignHandler(plugin, "" + count, getSignLocation("" + count),
getSignSkullLocation("" + count), getSignData("" + count), getSignPosition("" + count)));
}
/**
@@ -265,13 +86,11 @@ public class ServerData {
* @param num the vote number
* @param vote the vote time queue entry
*/
public void addTimeVoted(int num, VoteTimeQueue vote) {
mutateData(() -> {
getData().set("TimedVoteCache." + num + ".Name", vote.getName());
getData().set("TimedVoteCache." + num + ".Service", vote.getService());
getData().set("TimedVoteCache." + num + ".Time", vote.getTime());
saveTimedVoteCache();
});
public void addTimeVoted(int num, VoteTimeQueue vote) {
getData().set("TimedVoteCache." + num + ".Name", vote.getName());
getData().set("TimedVoteCache." + num + ".Service", vote.getService());
getData().set("TimedVoteCache." + num + ".Time", vote.getTime());
saveData();
}
/**
@@ -279,20 +98,16 @@ public class ServerData {
*
* @param ident the vote shop identifier
*/
public void addVoteShopPurchase(String ident) {
mutateData(() -> {
setVoteShopPurchases(ident, (getVoteShopPurchases(ident) + 1));
});
public void addVoteShopPurchase(String ident) {
setVoteShopPurchases(ident, (getVoteShopPurchases(ident) + 1));
}
/**
* Clears the timed vote cache.
*/
public void clearTimedVoteCache() {
mutateData(() -> {
getData().set("TimedVoteCache", null);
saveTimedVoteCache();
});
public void clearTimedVoteCache() {
getData().set("TimedVoteCache", null);
saveData();
}
/**
@@ -327,15 +142,13 @@ public class ServerData {
*
* @return the data
*/
public ConfigurationSection getData() {
var fence = getPublicationFence();
try (var owner = fence == null ? null : fence.acquire()) {
synchronized (publicationMonitor()) {
ConfigurationSection data = getFile().getData().getConfigurationSection("VotingPlugin");
if (data == null) data = getFile().getData().createSection("VotingPlugin");
return data;
}
}
public ConfigurationSection getData() {
ConfigurationSection data = plugin.getServerDataFile().getData().getConfigurationSection("VotingPlugin");
if (data == null) {
plugin.getServerDataFile().getData().createSection("VotingPlugin");
data = plugin.getServerDataFile().getData().getConfigurationSection("VotingPlugin");
}
return data;
}
/**
@@ -352,10 +165,9 @@ public class ServerData {
*
* @return the service sites
*/
public ArrayList<String> getServiceSites() {
synchronized (publicationMonitor()) {
return new ArrayList<>(getData().getStringList("GottenServiceSites"));
}
@SuppressWarnings("unchecked")
public ArrayList<String> getServiceSites() {
return (ArrayList<String>) getData().getList("GottenServiceSites", new ArrayList<>());
}
/**
@@ -364,11 +176,9 @@ public class ServerData {
*
* @return persisted service-site observations
*/
public List<String> getServiceSitesReadOnly() {
synchronized (publicationMonitor()) {
ConfigurationSection root = getFile().getData().getConfigurationSection("VotingPlugin");
return root == null ? List.of() : List.copyOf(root.getStringList("GottenServiceSites"));
}
public synchronized List<String> getServiceSitesReadOnly() {
ConfigurationSection root = plugin.getServerDataFile().getData().getConfigurationSection("VotingPlugin");
return root == null ? List.of() : List.copyOf(root.getStringList("GottenServiceSites"));
}
/**
@@ -529,11 +339,8 @@ public class ServerData {
/**
* Reload data.
*/
public void reloadData() {
mutateData(() -> {
getFile().reloadData();
captureVotePartyDisplay();
});
public void reloadData() {
plugin.getServerDataFile().reloadData();
}
/**
@@ -552,164 +359,36 @@ public class ServerData {
* @param top the top voter type
* @param messageId the message ID
*/
public void setTopVoterMessageId(TopVoter top, long messageId) {
mutateSavedData(() -> {
getData().set("DiscordSRV.TopVoterMessageId." + top.toString(), messageId);
});
public void setTopVoterMessageId(TopVoter top, long messageId) {
getData().set("DiscordSRV.TopVoterMessageId." + top.toString(), messageId);
saveData();
}
/**
* Uses the existing writer and confirms this ID in the saved file. Legacy void saves may
* swallow I/O failure; queued/custom writers may also remain unconfirmed at this point.
* False is an uncertain outcome, never permission to delete a possibly recorded message.
* Call only on the existing worker, under this facade's normal save ordering.
*/
public synchronized boolean setTopVoterMessageIdConfirmed(TopVoter top, long messageId) {
setTopVoterMessageId(top, messageId);
try {
var saved = new org.bukkit.configuration.file.YamlConfiguration();
saved.load(plugin.getServerDataFile().getdFile());
return saved.getLong("VotingPlugin.DiscordSRV.TopVoterMessageId." + top.toString(), 0) == messageId;
} catch (java.io.IOException | org.bukkit.configuration.InvalidConfigurationException | RuntimeException failure) {
return false;
}
}
/**
/**
* Removes the sign.
*
* @param sign the sign
*/
public void removeSign(String sign) {
mutateSavedData(() -> {
getData().set("Signs." + sign + ".World", null);
getData().set("Signs." + sign + ".X", null);
getData().set("Signs." + sign + ".Y", null);
getData().set("Signs." + sign + ".Z", null);
getData().set("Signs." + sign + ".Data", null);
getData().set("Signs." + sign + ".Position", null);
getData().set("Signs." + sign, null);
getData().set("Signs." + sign + ".Skull.World", null);
getData().set("Signs." + sign + ".Skull.X", null);
getData().set("Signs." + sign + ".Skull.Y", null);
getData().set("Signs." + sign + ".Skull.Z", null);
});
public void removeSign(String sign) {
getData().set("Signs." + sign + ".World", null);
getData().set("Signs." + sign + ".X", null);
getData().set("Signs." + sign + ".Y", null);
getData().set("Signs." + sign + ".Z", null);
getData().set("Signs." + sign + ".Data", null);
getData().set("Signs." + sign + ".Position", null);
getData().set("Signs." + sign, null);
getData().set("Signs." + sign + ".Skull.World", null);
getData().set("Signs." + sign + ".Skull.X", null);
getData().set("Signs." + sign + ".Skull.Y", null);
getData().set("Signs." + sign + ".Skull.Z", null);
saveData();
}
/** Checkpoint the pending suffix without retiring its live queue entries. */
public void replaceTimedVoteCache(java.util.Collection<VoteTimeQueue> pending) {
mutateData(() -> {
Object previous = getData().get("TimedVoteCache");
try {
setTimedVoteCache(pending);
saveTimedVoteCache();
} catch (RuntimeException | Error failure) {
getData().set("TimedVoteCache", previous);
throw failure;
}
});
}
/** Publish the recovery suffix and conservative in-flight record in one file save. */
public void prepareTimedVoteDispatch(UUID id, VoteTimeQueue vote,
java.util.Collection<VoteTimeQueue> pending) {
mutateData(() -> {
String path = "UncertainTimedVotes." + id;
Object previousCache = getData().get("TimedVoteCache");
Object previousRecord = getData().get(path);
try {
setTimedVoteCache(pending);
getData().set(path, null);
getData().createSection(path, timedVoteFields(vote));
saveTimedVoteCache();
} catch (RuntimeException | Error failure) {
getData().set("TimedVoteCache", previousCache);
getData().set(path, previousRecord);
throw failure;
}
});
}
/** Restore an undispatched occurrence and its pending suffix for ordinary restart recovery. */
public void abortTimedVoteDispatch(UUID id, java.util.Collection<VoteTimeQueue> pending) {
mutateData(() -> {
String path = "UncertainTimedVotes." + id;
Object previousCache = getData().get("TimedVoteCache");
Object previousRecord = getData().get(path);
try {
setTimedVoteCache(pending);
getData().set(path, null);
saveTimedVoteCache();
} catch (RuntimeException | Error failure) {
getData().set("TimedVoteCache", previousCache);
getData().set(path, previousRecord);
throw failure;
}
});
}
/** Clear only a confirmed dispatch record; failed writes retain its live representation. */
public void completeTimedVoteDispatch(UUID id) {
mutateData(() -> {
String path = "UncertainTimedVotes." + id;
Object previous = getData().get(path);
try {
getData().set(path, null);
saveTimedVoteCache();
} catch (RuntimeException | Error failure) {
getData().set(path, previous);
throw failure;
}
});
}
private void setTimedVoteCache(java.util.Collection<VoteTimeQueue> pending) {
java.util.Map<String, Object> rows = new java.util.LinkedHashMap<>();
int index = 0;
for (VoteTimeQueue vote : pending) rows.put(Integer.toString(index++), timedVoteFields(vote));
getData().set("TimedVoteCache", null);
getData().createSection("TimedVoteCache", rows);
}
private static java.util.Map<String, Object> timedVoteFields(VoteTimeQueue vote) {
java.util.Map<String, Object> fields = new java.util.LinkedHashMap<>();
fields.put("Name", vote.getName());
fields.put("Service", vote.getService());
fields.put("Time", vote.getTime());
return fields;
}
/** Retain an ambiguous event delivery without making it eligible for automatic replay. */
public void addUncertainTimedVote(java.util.UUID id, VoteTimeQueue vote) {
mutateData(() -> {
String path = "UncertainTimedVotes." + id;
getData().set(path + ".Name", vote.getName());
getData().set(path + ".Service", vote.getService());
getData().set(path + ".Time", vote.getTime());
saveTimedVoteCache();
});
}
/** Timed votes must observe write failures before their in-memory queue is retired. */
private void saveTimedVoteCache() {
var fence = getPublicationFence();
try (var owner = fence == null ? null : fence.acquire()) {
var file = getFile();
if (file instanceof GenerationFencedServerDataFile guarded) guarded.saveDataChecked();
else file.getData().save(file.getdFile());
} catch (java.io.IOException failure) {
throw new java.io.UncheckedIOException("Failed to save timed vote cache", failure);
}
}
/** Saves server data through the existing general-purpose file helper. */
public void saveData() {
mutateData(() -> {
// Publish the complete live display projection before entering disk I/O.
// A failed save still does not acknowledge durable storage.
captureVotePartyDisplay();
getFile().saveData();
});
/**
* Save data.
*/
public synchronized void saveData() {
plugin.getServerDataFile().saveData();
}
/**
@@ -717,10 +396,13 @@ public class ServerData {
*
* @param disabledReminders the list of UUIDs with disabled reminders
*/
public void saveDisabledReminders(ArrayList<UUID> disabledReminders) {
ArrayList<String> uuids = new ArrayList<>();
for (UUID uuid : disabledReminders) uuids.add(uuid.toString());
setStringList("DisabledReminders", uuids);
public void saveDisabledReminders(ArrayList<UUID> disabledReminders) {
ArrayList<String> uuids = new ArrayList<>();
for (UUID uuid : disabledReminders) {
uuids.add(uuid.toString());
}
getData().set("DisabledReminders", uuids);
saveData();
}
/**
@@ -728,8 +410,9 @@ public class ServerData {
*
* @param placeholders the list of placeholders
*/
public void setAutoCachedPlaceholder(List<String> placeholders) {
setStringList("AutoCachePlaceholders", placeholders);
public void setAutoCachedPlaceholder(List<String> placeholders) {
getData().set("AutoCachePlaceholders", placeholders);
saveData();
}
/**
@@ -737,8 +420,9 @@ public class ServerData {
*
* @param current the current vote count
*/
public void setBungeeVotePartyCurrent(int current) {
setInt("BungeeVotePartyCurrent", current);
public void setBungeeVotePartyCurrent(int current) {
getData().set("BungeeVotePartyCurrent", current);
saveData();
}
/**
@@ -746,8 +430,9 @@ public class ServerData {
*
* @param required the required vote count
*/
public void setBungeeVotePartyRequired(int required) {
setInt("BungeeVotePartyRequired", required);
public void setBungeeVotePartyRequired(int required) {
getData().set("BungeeVotePartyRequired", required);
saveData();
}
/**
@@ -755,8 +440,9 @@ public class ServerData {
*
* @param list the service sites list
*/
public void setServiceSites(ArrayList<String> list) {
setStringList("GottenServiceSites", list);
public void setServiceSites(ArrayList<String> list) {
getData().set("GottenServiceSites", list);
saveData();
}
/**
@@ -764,10 +450,9 @@ public class ServerData {
*
* @param value the converted status
*/
public void setShopConverted(boolean value) {
mutateSavedData(() -> {
getData().set("VoteShopConverted", value);
});
public void setShopConverted(boolean value) {
getData().set("VoteShopConverted", value);
saveData();
}
/**
@@ -779,15 +464,21 @@ public class ServerData {
* @param data the sign data
* @param position the sign position
*/
public void setSign(String count, Location location, Location skullLocation, String data, int position) {
var coordinates = SignCoordinates.capture(location);
var skull = skullLocation == null ? null : SignCoordinates.capture(skullLocation);
mutateSavedData(() -> {
coordinates.store(getData(), "Signs." + count);
getData().set("Signs." + count + ".Data", data);
getData().set("Signs." + count + ".Position", position);
if (skull != null) skull.store(getData(), "Signs." + count + ".Skull");
});
public void setSign(String count, Location location, Location skullLocation, String data, int position) {
getData().set("Signs." + count + ".World", location.getWorld().getName());
getData().set("Signs." + count + ".X", (int) location.getX());
getData().set("Signs." + count + ".Y", (int) location.getY());
getData().set("Signs." + count + ".Z", (int) location.getZ());
getData().set("Signs." + count + ".Data", data);
getData().set("Signs." + count + ".Position", position);
if (skullLocation != null) {
getData().set("Signs." + count + ".Skull.World", skullLocation.getWorld().getName());
getData().set("Signs." + count + ".Skull.X", (int) skullLocation.getX());
getData().set("Signs." + count + ".Skull.Y", (int) skullLocation.getY());
getData().set("Signs." + count + ".Skull.Z", (int) skullLocation.getZ());
}
saveData();
}
/**
@@ -796,20 +487,21 @@ public class ServerData {
* @param count the sign count
* @param skullLocation the skull location
*/
public void setSkullLocation(String count, Location skullLocation) {
if (skullLocation == null) return;
var coordinates = SignCoordinates.capture(skullLocation);
mutateData(() -> coordinates.store(getData(), "Signs." + count + ".Skull"));
public void setSkullLocation(String count, Location skullLocation) {
if (skullLocation != null) {
getData().set("Signs." + count + ".Skull.World", skullLocation.getWorld().getName());
getData().set("Signs." + count + ".Skull.X", (int) skullLocation.getX());
getData().set("Signs." + count + ".Skull.Y", (int) skullLocation.getY());
getData().set("Signs." + count + ".Skull.Z", (int) skullLocation.getZ());
}
}
/**
* Sets the version.
*/
public void setVersion() {
String version = Bukkit.getVersion();
mutateSavedData(() -> {
getData().set("Version", version);
});
public void setVersion() {
getData().set("Version", Bukkit.getVersion());
saveData();
}
/**
@@ -817,10 +509,9 @@ public class ServerData {
*
* @param value the extra required votes
*/
public void setVotePartyExtraRequired(int value) {
mutateSavedData(() -> {
getData().set("VotePartyExtraRequired", value);
});
public void setVotePartyExtraRequired(int value) {
getData().set("VotePartyExtraRequired", value);
saveData();
}
/**
@@ -829,45 +520,42 @@ public class ServerData {
* @param ident the vote shop identifier
* @param amount the purchase amount
*/
public void setVoteShopPurchases(String ident, int amount) {
mutateSavedData(() -> {
getData().set("VoteShopPurchases." + ident, amount);
});
public void setVoteShopPurchases(String ident, int amount) {
getData().set("VoteShopPurchases." + ident, amount);
saveData();
}
/**
* Updates the last vote party timestamp to today.
*/
public void updateLastVoteParty() {
int day = plugin.getTimeChecker().getTime().getDayOfYear();
setInt("LastVoteParty", day);
public void updateLastVoteParty() {
getData().set("LastVoteParty", plugin.getTimeChecker().getTime().getDayOfYear());
saveData();
}
/**
* Updates the last vote party week timestamp to this week.
*/
public void updateLastVotePartyWeek() {
int week = plugin.getTimeChecker().getTime().get(WeekFields.of(Locale.getDefault()).weekOfYear());
setInt("LastVotePartyWeek", week);
public void updateLastVotePartyWeek() {
getData().set("LastVotePartyWeek",
plugin.getTimeChecker().getTime().get(WeekFields.of(Locale.getDefault()).weekOfYear()));
saveData();
}
/**
* Updates placeholders to lowercase format.
*/
public void updatePlaceholders() {
mutateData(() -> {
boolean data = getData().getBoolean("AutoCacheUpdated", false);
if (!data) {
mutateSavedData(() -> {
List<String> placeholders = getAutoCachedPlaceholder();
for (int i = 0; i < placeholders.size(); i++) {
placeholders.set(i, placeholders.get(i).toLowerCase());
}
getData().set("AutoCachePlaceholders", placeholders);
getData().set("AutoCacheUpdated", true);
});
}
});
public void updatePlaceholders() {
boolean data = getData().getBoolean("AutoCacheUpdated", false);
if (!data) {
List<String> placeholders = getAutoCachedPlaceholder();
for (int i = 0; i < placeholders.size(); i++) {
placeholders.set(i, placeholders.get(i).toLowerCase());
}
setAutoCachedPlaceholder(placeholders);
getData().set("AutoCacheUpdated", true);
saveData();
}
}
/**
@@ -3,8 +3,10 @@ package com.bencodez.votingplugin.discord;
import java.awt.Color;
import java.time.Instant;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
@@ -25,7 +27,6 @@ import github.scarsz.discordsrv.api.events.DiscordReadyEvent;
import github.scarsz.discordsrv.dependencies.jda.api.EmbedBuilder;
import github.scarsz.discordsrv.dependencies.jda.api.JDA;
import github.scarsz.discordsrv.dependencies.jda.api.entities.TextChannel;
import github.scarsz.discordsrv.dependencies.jda.api.entities.Message;
import github.scarsz.discordsrv.dependencies.jda.api.requests.ErrorResponse;
import github.scarsz.discordsrv.dependencies.jda.api.exceptions.ErrorResponseException;
import github.scarsz.discordsrv.util.DiscordUtil;
@@ -39,45 +40,8 @@ public class DiscordHandler {
private final VotingPluginMain plugin;
@Getter
private final HashMap<TopVoter, Long> topVoterMessageIds = new HashMap<TopVoter, Long>();
/** Identity, rather than generation alone, owns every request and its callbacks. */
private static final class Publication {
final long generation;
final boolean persistent;
boolean sending, editing, recovering, again, completing, retired;
long requestedGeneration;
final AtomicBoolean sendCompleted = new AtomicBoolean(false);
Publication(long generation, boolean persistent, boolean sending) {
this.generation = generation; this.requestedGeneration = generation;
this.persistent = persistent; this.sending = sending; this.editing = !sending;
}
}
private static final int PENDING = 0, WRITING = 1, RETAINED = 2, DISCARDED = 3, DETACHED = 4;
private static final int MAX_OWNED_RECEIPTS = 128;
/** External success is owned here before any cancellable worker handoff. */
private static final class SentReceipt {
final TopVoter top;
final Message message;
final long id;
final long generation;
final AtomicBoolean cleanupRequested = new AtomicBoolean(false);
int state = PENDING;
boolean confirmed;
SentReceipt(TopVoter top, Message message, long generation) {
this.top = top; this.message = message; this.id = message.getIdLong(); this.generation = generation;
}
}
private final java.util.EnumMap<TopVoter, Publication> publications = new java.util.EnumMap<>(TopVoter.class);
/** Guarded by publications; includes uncertain saves until confirmed replacement or explicit detachment. */
private final java.util.Set<SentReceipt> ownedReceipts = new java.util.HashSet<>();
private final AtomicBoolean closed = new AtomicBoolean(false);
private final Set<TopVoter> recoveringTopVoters = new HashSet<>();
private final AtomicBoolean discordReady = new AtomicBoolean(false);
private static final class DisplayUpdate {
private final long generation;
private long requestedGeneration;
private boolean again;
private DisplayUpdate(long generation) { this.generation = generation; this.requestedGeneration = generation; }
}
private final java.util.EnumMap<TopVoter, DisplayUpdate> preparing = new java.util.EnumMap<>(TopVoter.class);
/**
* Constructs a new Discord handler.
@@ -185,347 +149,14 @@ public class DiscordHandler {
* @param top the top voter
*/
public void updateTopVoterMessageId(TopVoter top) {
prepareTopVoterMessage(top, plugin.getTopVoterDisplayGeneration());
}
plugin.extraDebug("Updating Discord Top Voter message for: " + top);
private void prepareTopVoterMessage(TopVoter top, long generation) {
DisplayUpdate update;
synchronized (preparing) {
if (!currentGeneration(generation)) return;
DisplayUpdate pending = preparing.get(top);
if (pending != null) {
pending.again = true;
pending.requestedGeneration = generation;
return;
}
update = new DisplayUpdate(generation);
preparing.put(top, update);
}
try {
plugin.getTopVoterDisplayAsync(top).whenComplete((snapshot, failure) -> {
try {
plugin.getTimer().execute(() -> {
if (!releasePreparation(top, update)) return;
if (!currentGeneration(update.generation)) {
retryRequestedPreparation(top, update);
return;
}
// Joins and TTL/scope changes can revoke omissions while publication is queued.
// Recheck current evidence without opening another asynchronous deadline.
if (update.again || (failure == null && snapshot != null)) {
try { publishTopVoterMessage(top, plugin.getTopVoterDisplay(top), update.generation); }
catch (RuntimeException unavailable) { warnLeaderboardFailure("preparing a current display for " + top); }
} else plugin.getLogger().warning("Unable to prepare Discord Top Voters: " + top);
});
} catch (RuntimeException rejected) {
if (releasePreparation(top, update)) {
try { if (currentGeneration(update.generation)) warnLeaderboardFailure("preparation worker admission for " + top); }
finally { retryRequestedPreparation(top, update); }
}
}
});
} catch (RuntimeException unavailable) {
if (releasePreparation(top, update)) {
try { if (currentGeneration(update.generation)) warnLeaderboardFailure("preparing evidence for " + top); }
finally { retryRequestedPreparation(top, update); }
}
}
}
long channelId = plugin.getConfigFile().getDiscordSRVTopVoterChannel(top);
LinkedHashMap<TopVoterPlayer, Integer> topVoters = plugin.getTopVoter(top);
private boolean releasePreparation(TopVoter top, DisplayUpdate update) {
synchronized (preparing) { return preparing.remove(top, update); }
}
private void retryRequestedPreparation(TopVoter top, DisplayUpdate update) {
// The retired request's evidence never changes ownership to a replacement filter.
if (update.again && update.requestedGeneration != update.generation)
prepareTopVoterMessage(top, update.requestedGeneration);
}
void publishTopVoterMessage(TopVoter top, LinkedHashMap<TopVoterPlayer, Integer> prepared) {
publishTopVoterMessage(top, prepared, plugin.getTopVoterDisplayGeneration());
}
void publishTopVoterMessage(TopVoter top, LinkedHashMap<TopVoterPlayer, Integer> prepared, long generation) {
if (!currentGeneration(generation)) return;
String title = plugin.getConfigFile().getDiscordSRVTopVoterTitle(top);
boolean newMessage = plugin.getConfigFile().isDiscordSRVTopVoterNewMessageOnUpdate(top);
TextChannel channel;
try { channel = leaderboardChannel(plugin.getConfigFile().getDiscordSRVTopVoterChannel(top)); }
catch (RuntimeException unavailable) { warnLeaderboardFailure("channel lookup for " + top); return; }
if (channel == null) { warnLeaderboardFailure("missing channel for " + top); return; }
Publication publication;
long existingId;
synchronized (publications) {
if (!currentGeneration(generation)) return;
Publication pending = publications.get(top);
if (pending != null && (pending.editing || (!pending.retired && pending.generation == generation
&& (pending.sending || pending.completing)))) {
pending.again = true;
pending.requestedGeneration = generation;
return;
}
existingId = topVoterMessageIds.getOrDefault(top, 0L);
publication = new Publication(generation, !newMessage, existingId <= 0 || newMessage);
publications.put(top, publication);
}
try {
var embed = buildTopVoterEmbed(plugin.getConfigFile().getDiscordSRVTopVoterTitle(top), plugin.getTopVoterDisplay(top)).build();
if (!current(top, publication)) { finish(top, publication); return; }
if (publication.sending) send(top, channel, publication, embed);
else channel.editMessageEmbedsById(existingId, embed).queue(
message -> finishEdit(top, publication, existingId),
error -> handleMessageUpdateFailure(top, channel, publication, error));
} catch (RuntimeException unavailable) { failPublication(top, publication, "preparing or submitting a message"); }
}
private boolean current(TopVoter top, Publication publication) {
if (!currentGeneration(publication.generation)) return false;
synchronized (publications) { return publications.get(top) == publication && !publication.retired; }
}
/** Never hold the publication lock while waiting for the ServerData save monitor. */
private boolean persist(TopVoter top, Publication publication, long id) {
var data = plugin.getServerData();
synchronized (data) {
if (!current(top, publication)) return false;
data.setTopVoterMessageId(top, id);
}
return current(top, publication);
}
private void finish(TopVoter top, Publication publication) {
boolean again, prepareAgain;
long generation;
synchronized (publications) {
if (publications.get(top) != publication) return;
publications.remove(top);
again = publication.again;
generation = publication.requestedGeneration;
prepareAgain = publication.retired || generation != publication.generation;
}
// A queued request is independent of whether the previous network operation succeeded.
if (again) {
if (prepareAgain) prepareTopVoterMessage(top, generation);
else dispatchLeaderboard(generation,
() -> publishTopVoterMessage(top, plugin.getTopVoterDisplay(top), generation), () -> { });
}
}
private void warnLeaderboardFailure(String stage) {
// Provider exceptions can contain request URLs or message content. Report the phase only.
plugin.getLogger().warning("Unable to publish Discord Top Voters (" + stage
+ "). Check the Discord channel, permissions and configuration; a later update can retry.");
}
private void failPublication(TopVoter top, Publication publication, String stage) {
try { if (current(top, publication)) warnLeaderboardFailure(stage + " for " + top); }
finally { finish(top, publication); }
}
private void send(TopVoter top, TextChannel channel, Publication publication,
github.scarsz.discordsrv.dependencies.jda.api.entities.MessageEmbed embed) {
if (!current(top, publication)) { finish(top, publication); return; }
channel.sendMessageEmbeds(embed).queue(message -> {
if (!publication.sendCompleted.compareAndSet(false, true)) return;
SentReceipt receipt = new SentReceipt(top, message, publication.generation);
boolean admitted;
synchronized (publications) {
admitted = !closed.get() && (!publication.persistent || ownedReceipts.size() < MAX_OWNED_RECEIPTS);
if (admitted && publication.persistent) ownedReceipts.add(receipt);
publication.completing = true;
}
if (!admitted) {
discardCreatedMessage(publication, receipt); finish(top, publication); return;
}
dispatchLeaderboard(publication.generation, () -> {
try {
if (!current(top, publication)) return;
if (publication.persistent) { retainCreatedMessage(top, publication, receipt); return; }
if (!current(top, publication)) return;
synchronized (publications) {
if (publications.get(top) == publication) topVoterMessageIds.put(top, receipt.id);
}
} catch (RuntimeException failure) { warnLeaderboardFailure("storing a message ID for " + top); }
finally { discardCreatedMessage(publication, receipt); finish(top, publication); }
}, () -> { discardCreatedMessage(publication, receipt); finish(top, publication); });
}, failure -> failPublication(top, publication, "sending a message"));
}
/** Retry an uncertain ID save after a successful edit, without creating another external post. */
private void finishEdit(TopVoter top, Publication publication, long id) {
synchronized (publications) { publication.editing = false; publication.completing = true; }
if (!current(top, publication)) { finish(top, publication); return; }
SentReceipt retry;
synchronized (publications) {
retry = ownedReceipts.stream().filter(receipt -> receipt.top == top && receipt.id == id
&& receipt.state == RETAINED && !receipt.confirmed).findFirst().orElse(null);
}
if (retry == null) { finish(top, publication); return; }
dispatchLeaderboard(publication.generation, () -> {
try { retainCreatedMessage(top, publication, retry); }
finally { discardCreatedMessage(publication, retry); finish(top, publication); }
}, () -> finish(top, publication));
}
/** Never hold publication ownership while waiting for the existing save monitor or file I/O. */
private void retainCreatedMessage(TopVoter top, Publication publication, SentReceipt receipt) {
var obsolete = new java.util.ArrayList<SentReceipt>();
var data = plugin.getServerData();
boolean uncertain = false;
synchronized (data) {
if (!current(top, publication)) return;
synchronized (publications) {
if (!current(top, publication) || (receipt.state != PENDING && receipt.state != RETAINED)) return;
receipt.state = WRITING;
}
try {
boolean confirmed = data.setTopVoterMessageIdConfirmed(top, receipt.id);
long actual = data.getTopVoterMessageId(top);
synchronized (publications) {
if (receipt.state == DETACHED) return;
// A reentrant newer confirmed write already owns the file. Reconcile only this older post.
if (actual != receipt.id && ownedReceipts.stream().anyMatch(other -> other != receipt
&& other.top == top && other.id == actual && other.state == RETAINED && other.confirmed)) return;
receipt.state = RETAINED;
receipt.confirmed = confirmed && actual == receipt.id;
uncertain = !receipt.confirmed;
if (actual == receipt.id && (publications.get(top) == publication
|| topVoterMessageIds.getOrDefault(top, 0L) <= 0)) topVoterMessageIds.put(top, receipt.id);
if (receipt.confirmed) {
var iterator = ownedReceipts.iterator();
while (iterator.hasNext()) {
SentReceipt previous = iterator.next();
if (previous != receipt && previous.top == top && previous.state == RETAINED) {
previous.state = DISCARDED; iterator.remove(); obsolete.add(previous);
}
}
}
}
} catch (RuntimeException failure) {
// The legacy writer may have mutated or saved before throwing; do not delete a possibly recorded post.
synchronized (publications) {
if (receipt.state == DETACHED) return;
receipt.state = RETAINED; receipt.confirmed = false;
if (publications.get(top) == publication && topVoterMessageIds.getOrDefault(top, 0L) <= 0)
topVoterMessageIds.put(top, receipt.id);
}
uncertain = true;
}
}
obsolete.forEach(this::removeCreatedMessage);
if (uncertain) warnMessageStorage();
}
private void discardCreatedMessage(Publication publication, SentReceipt receipt) {
if (!publication.persistent) return; // Append mode deliberately keeps its posts.
synchronized (publications) {
if (receipt.state != PENDING && receipt.state != WRITING) return;
receipt.state = DISCARDED; ownedReceipts.remove(receipt);
}
removeCreatedMessage(receipt);
}
/** Detach the administrator's old posts; clearing an ID never authorizes deleting those posts. */
public boolean clearTopVoterMessageId(TopVoter top) {
var data = plugin.getServerData();
synchronized (data) {
synchronized (publications) {
publications.remove(top);
synchronized (preparing) { preparing.remove(top); }
topVoterMessageIds.put(top, 0L);
ownedReceipts.removeIf(receipt -> {
if (receipt.top != top || (receipt.state != PENDING && receipt.state != RETAINED
&& receipt.state != WRITING)) return false;
receipt.state = DETACHED; return true;
});
}
try { if (data.setTopVoterMessageIdConfirmed(top, 0L)) return true; }
catch (RuntimeException failure) { /* The outgoing diagnostic remains redacted. */ }
}
warnMessageStorage(); return false;
}
/** Retire invalidated generations before worker cancellation; close invalidates every generation. */
public void retireLeaderboardPublications() {
var abandoned = new java.util.ArrayList<SentReceipt>();
var restart = new java.util.EnumMap<TopVoter, Long>(TopVoter.class);
synchronized (publications) {
// An admitted edit can still write on Discord after retirement. Keep its
// bounded slot until its network callback rather than submitting overlapping edits.
publications.entrySet().removeIf(entry -> {
Publication publication = entry.getValue();
if (currentGeneration(publication.generation) && !publication.retired) return false;
boolean again = publication.again && currentGeneration(publication.requestedGeneration);
if (!publication.editing) {
if (again) restart.put(entry.getKey(), publication.requestedGeneration);
return true;
}
publication.retired = true;
publication.again = again;
return false;
});
synchronized (preparing) {
preparing.entrySet().removeIf(entry -> {
DisplayUpdate update = entry.getValue();
if (currentGeneration(update.generation)) return false;
if (update.again && currentGeneration(update.requestedGeneration))
restart.put(entry.getKey(), update.requestedGeneration);
return true;
});
}
var iterator = ownedReceipts.iterator();
while (iterator.hasNext()) {
SentReceipt receipt = iterator.next();
if (receipt.state == PENDING && !currentGeneration(receipt.generation)) {
receipt.state = DISCARDED; iterator.remove(); abandoned.add(receipt);
}
}
}
abandoned.forEach(this::removeCreatedMessage);
// Old worker completions can be cancelled; transfer explicit requests now,
// outside both ownership monitors and without waiting for those callbacks.
restart.forEach(this::prepareTopVoterMessage);
}
public void close() {
synchronized (publications) {
if (!closed.compareAndSet(false, true)) return;
}
retireLeaderboardPublications();
boolean uncertain;
synchronized (publications) {
uncertain = ownedReceipts.stream().anyMatch(receipt -> receipt.state == WRITING || !receipt.confirmed);
}
if (uncertain) warnMessageStorage();
}
private void warnMessageStorage() {
plugin.getLogger().warning("Unable to confirm Discord Top Voters message ID storage. "
+ "The post remains tracked in memory; check storage before restarting and reconcile posts manually.");
}
/** JDA owns asynchronous deletion; cleanup does not depend on the retiring plugin worker. */
private void removeCreatedMessage(SentReceipt receipt) {
if (!receipt.cleanupRequested.compareAndSet(false, true)) return;
try {
receipt.message.delete().queue(ignored -> { }, failure -> {
if (!(failure instanceof ErrorResponseException response)
|| response.getErrorResponse() != ErrorResponse.UNKNOWN_MESSAGE) warnMessageCleanup();
});
} catch (RuntimeException failure) { warnMessageCleanup(); }
}
private void warnMessageCleanup() {
plugin.getLogger().warning("Unable to remove an untracked Discord Top Voters message. "
+ "Check Discord permissions and remove the unwanted post manually.");
}
TextChannel leaderboardChannel(long channelId) {
return DiscordUtil.getJda().getTextChannelById(channelId);
}
/** Render an inspected display snapshot without accessing the Discord runtime. */
static EmbedBuilder buildTopVoterEmbed(String title, LinkedHashMap<TopVoterPlayer, Integer> topVoters) {
EmbedBuilder eb = new EmbedBuilder().setTitle(title).setColor(Color.CYAN).setTimestamp(Instant.now());
if (topVoters == null || topVoters.isEmpty()) {
@@ -556,7 +187,34 @@ public class DiscordHandler {
eb.setDescription(sb.toString()).setFooter("Top 10 • Updated");
}
return eb;
TextChannel channel = DiscordUtil.getJda().getTextChannelById(channelId);
if (channel == null) {
plugin.getLogger().warning("Discord channel ID " + channelId + " not found: " + top);
return;
}
long existingId;
synchronized (recoveringTopVoters) {
if (recoveringTopVoters.contains(top)) {
plugin.debug("Skipping Discord Top Voter update while recovery is in progress: " + top);
return;
}
existingId = topVoterMessageIds.getOrDefault(top, 0L);
}
if (existingId <= 0 || newMessage) {
channel.sendMessageEmbeds(eb.build()).queue(msg -> {
long newId = msg.getIdLong();
topVoterMessageIds.put(top, newId);
if (!newMessage)
plugin.getServerData().setTopVoterMessageId(top, newId);
plugin.debug("Posted new Top Voters " + top + " (ID: " + newId + ")");
}, err -> plugin.getLogger().warning("Error sending Top Voters " + top + ": " + err.getMessage()));
} else {
channel.editMessageEmbedsById(existingId, eb.build()).queue(
m -> plugin.debug("Edited Top Voters " + top + " (ID: " + existingId + ")"),
err -> handleMessageUpdateFailure(top, channel, eb, existingId, err));
}
}
/**
@@ -566,65 +224,41 @@ public class DiscordHandler {
* condition as recoverable so one deleted message cannot permanently stop
* leaderboard updates.
*/
private boolean currentGeneration(long generation) {
return !closed.get() && plugin.isEnabled() && plugin.getTopVoterDisplayGeneration() == generation;
}
private void dispatchLeaderboard(long generation, Runnable action, Runnable discarded) {
if (!currentGeneration(generation)) { discarded.run(); return; }
try {
plugin.getTimer().execute(() -> {
try {
if (currentGeneration(generation)) action.run(); else discarded.run();
} catch (RuntimeException failure) {
try { if (currentGeneration(generation)) warnLeaderboardFailure("asynchronous publication"); }
finally { discarded.run(); }
}
});
} catch (RuntimeException rejected) {
try { if (currentGeneration(generation)) warnLeaderboardFailure("worker admission"); }
finally { discarded.run(); }
}
}
private void handleMessageUpdateFailure(TopVoter top, TextChannel channel, Publication publication,
private void handleMessageUpdateFailure(TopVoter top, TextChannel channel, EmbedBuilder eb, long existingId,
Throwable error) {
synchronized (publications) { publication.editing = false; }
if (!current(top, publication)) { finish(top, publication); return; }
if (!plugin.getConfigFile().isDiscordSRVTopVoterAutoRecoverMessageOnFailure()
|| !(error instanceof ErrorResponseException response)
|| response.getErrorResponse() != ErrorResponse.UNKNOWN_MESSAGE) {
failPublication(top, publication, "editing a message");
return;
}
synchronized (publications) {
if (publications.get(top) != publication || publication.recovering) return;
publication.recovering = true;
publication.sending = true;
}
dispatchLeaderboard(publication.generation, () -> {
try {
if (!persist(top, publication, 0L)) { finish(top, publication); return; }
synchronized (publications) {
if (publications.get(top) != publication) return;
topVoterMessageIds.put(top, 0L);
}
// Persistence can block while a join, TTL, reload or disable revokes the earlier frame.
var replacement = buildTopVoterEmbed(plugin.getConfigFile().getDiscordSRVTopVoterTitle(top),
plugin.getTopVoterDisplay(top)).build();
send(top, channel, publication, replacement);
} catch (RuntimeException failure) { failPublication(top, publication, "recovering a deleted message"); }
}, () -> {
// Rejected admission has no effects; the same failed edit may be retried.
boolean again = false;
synchronized (publications) {
if (publications.get(top) == publication) {
publication.recovering = false; publication.sending = false;
again = publication.again;
if (plugin.getConfigFile().isDiscordSRVTopVoterAutoRecoverMessageOnFailure()
&& error instanceof ErrorResponseException
&& ((ErrorResponseException) error).getErrorResponse() == ErrorResponse.UNKNOWN_MESSAGE) {
synchronized (recoveringTopVoters) {
if (topVoterMessageIds.getOrDefault(top, 0L) != existingId || !recoveringTopVoters.add(top)) {
plugin.debug("Skipping stale Discord Top Voter recovery because another update handled: " + top);
return;
}
}
if (again) finish(top, publication);
});
plugin.getLogger().warning("Discord Top Voters " + top + " message " + existingId
+ " no longer exists; clearing the stored ID and posting a replacement.");
synchronized (recoveringTopVoters) {
topVoterMessageIds.put(top, 0L);
}
plugin.getServerData().setTopVoterMessageId(top, 0L);
channel.sendMessageEmbeds(eb.build()).queue(msg -> {
long newId = msg.getIdLong();
synchronized (recoveringTopVoters) {
topVoterMessageIds.put(top, newId);
plugin.getServerData().setTopVoterMessageId(top, newId);
recoveringTopVoters.remove(top);
}
plugin.debug("Recovered Top Voters " + top + " with replacement message (ID: " + newId + ")");
}, sendError -> {
synchronized (recoveringTopVoters) {
recoveringTopVoters.remove(top);
}
plugin.getLogger().warning("Error recovering Top Voters " + top + ": " + sendError.getMessage());
});
return;
}
plugin.getLogger().warning("Error editing Top Voters " + top + ": " + error.getMessage());
}
/**
@@ -35,7 +35,7 @@ public class PlayerJoinEvent implements Listener {
public void onPlayerJoin(org.bukkit.event.player.PlayerJoinEvent event) {
if (event == null || event.getPlayer() == null) return;
Player player = event.getPlayer();
plugin.getPlaceholderPlayerPresence().captureOnline(placeholderUuid(player), player);
plugin.getPlaceholderPlayerPresence().playerOnline(placeholderUuid(player), player);
}
private UUID placeholderUuid(Player player) {
@@ -83,7 +83,7 @@ public class PlayerJoinEvent implements Listener {
Player player = event.getPlayer();
if (player != null) {
if (!plugin.getPlaceholderPlayerPresence().updateStorageUuid(user.getJavaUUID(), player)) return;
plugin.getPlaceholderPlayerPresence().playerOnline(user.getJavaUUID(), player);
}
if (player != null && plugin.isYmlError()) {
@@ -160,19 +160,17 @@ public class PlayerJoinEvent implements Listener {
plugin.getBackendProxyHandler().playerOffline(player.getName());
}
final UUID serverUuid = player.getUniqueId();
final String playerName = player.getName();
plugin.getLoginTimer().execute(new Runnable() {
@Override
public void run() {
VotingPluginMain.plugin.getAdvancedTab().remove(serverUuid);
VotingPluginMain.plugin.getAdvancedTab().remove(player.getUniqueId());
// Use AdvancedCore UUIDLookup to derive the correct UUID (online/offline aware)
String uuid = UuidLookup.getInstance().getUUID(playerName);
String uuid = UuidLookup.getInstance().getUUID(player.getName());
if (isBlank(uuid)) {
// Fallback to online UUID if lookup fails
uuid = serverUuid.toString();
uuid = player.getUniqueId().toString();
}
VotingPluginUser user = plugin.getVotingPluginUserManager().getVotingPluginUser(uuid);
@@ -1,5 +1,6 @@
package com.bencodez.votingplugin.listeners;
import java.util.concurrent.RejectedExecutionException;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
@@ -134,8 +135,9 @@ public class VotiferEvent implements Listener {
plugin.debug("VoteSite: " + voteSite);
plugin.debug("IP: " + IP);
if (!com.bencodez.votingplugin.util.VoteTaskAdmission.trySubmit(plugin.getVoteTimer(),
() -> processVote(voteSite, voteUsername))) {
try {
plugin.getVoteTimer().submit(() -> processVote(voteSite, voteUsername));
} catch (RejectedExecutionException rejected) {
VotifierVoteOverflowQueue overflow = plugin.getVotifierVoteOverflowQueue();
if (overflow == null || !overflow.enqueue(voteUsername, voteSite)) {
plugin.getLogger().severe("Votifier vote queue is full; vote was not admitted for "
@@ -1,212 +0,0 @@
package com.bencodez.votingplugin.maintenance;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.LongSupplier;
import java.util.logging.Logger;
import com.bencodez.votingplugin.core.maintenance.AutoCreateVoteSitesReminderState;
import com.bencodez.votingplugin.core.maintenance.AutoCreateVoteSitesReminderState.Candidate;
import com.bencodez.votingplugin.core.maintenance.AutoCreateVoteSitesReminderState.Snapshot;
import com.bencodez.votingplugin.util.DurableFiles.PublishedException;
/** Owner-only console reminder; all file work runs on its bounded background worker. */
public final class AutoCreateVoteSitesReminderService {
public record Settings(boolean enabled, boolean autoCreateEnabled, long afterMillis, long repeatMillis) {
public Settings {
if (afterMillis < 0 || repeatMillis <= 0
|| afterMillis > AutoCreateVoteSitesReminderState.MAX_INTERVAL_MILLIS
|| repeatMillis > AutoCreateVoteSitesReminderState.MAX_INTERVAL_MILLIS) {
throw new IllegalArgumentException("Reminder intervals must be non-negative and bounded");
}
}
}
@FunctionalInterface
interface StoreFactory {
AutoCreateVoteSitesReminderStore create(Path directory) throws IOException;
}
private final Path directory;
private final ScheduledExecutorService executor;
private final Logger logger;
private final LongSupplier clock;
private final StoreFactory storeFactory;
private final long startedNanos;
private final AtomicBoolean started = new AtomicBoolean();
private final AtomicBoolean recoveryRequested = new AtomicBoolean();
private record CloseRequest(CompletableFuture<Void> result, long stoppedNanos) { }
private final AtomicReference<CloseRequest> closing = new AtomicReference<>();
private final Object clockGate = new Object();
private volatile Settings settings;
private volatile ScheduledFuture<?> task;
// Accessed only inside the serialized worker checkpoint, never by gameplay callers.
private AutoCreateVoteSitesReminderStore store;
private AutoCreateVoteSitesReminderState state;
private boolean failed;
private boolean checkpointRequired;
private boolean waitingReported;
public AutoCreateVoteSitesReminderService(Path directory, ScheduledExecutorService executor,
Logger logger, Settings settings) {
this(directory, executor, logger, settings, System::nanoTime, AutoCreateVoteSitesReminderStore::new);
}
AutoCreateVoteSitesReminderService(Path directory, ScheduledExecutorService executor,
Logger logger, Settings settings, LongSupplier clock, StoreFactory storeFactory) {
this.directory = Objects.requireNonNull(directory);
this.executor = Objects.requireNonNull(executor);
this.logger = Objects.requireNonNull(logger);
this.settings = Objects.requireNonNull(settings);
this.clock = Objects.requireNonNull(clock);
this.storeFactory = Objects.requireNonNull(storeFactory);
startedNanos = clock.getAsLong();
}
public void start() {
if (closing.get() != null || !started.compareAndSet(false, true)) return;
try {
task = executor.scheduleWithFixedDelay(this::tick, 0, 60, TimeUnit.SECONDS);
if (closing.get() != null) task.cancel(false);
} catch (RuntimeException rejected) {
logger.warning("AutoCreateVoteSites setup reminder could not start; voting is unaffected.");
}
}
/** Reload is a snapshot update, never synchronous file I/O or another periodic task. */
public void reload(Settings next) {
settings = Objects.requireNonNull(next);
recoveryRequested.set(true);
}
private void tick() {
long nowNanos;
synchronized (clockGate) {
if (closing.get() != null) return;
nowNanos = clock.getAsLong();
}
try {
checkpoint(nowNanos, false);
} catch (IOException | RuntimeException failure) {
logger.warning("AutoCreateVoteSites setup reminder paused after a checkpoint failure; "
+ "repair its checkpoint if necessary and reload or restart. Voting is unaffected.");
}
}
private synchronized void checkpoint(long nowNanos, boolean finalCheckpoint) throws IOException {
CloseRequest stopped = closing.get();
if (stopped != null) {
if (!finalCheckpoint) return;
nowNanos = stopped.stoppedNanos();
}
if (failed && !recoveryRequested.getAndSet(false)) {
if (finalCheckpoint) throw new IOException("Reminder checkpoint remains unavailable");
return;
}
try {
if (store == null) store = storeFactory.create(directory);
if (!store.tryAcquireLease()) {
if (finalCheckpoint) throw new IOException("Final reminder checkpoint has no storage ownership");
if (!waitingReported) {
logger.warning("AutoCreateVoteSites setup reminder is waiting for a retiring reminder worker; "
+ "voting is unaffected.");
waitingReported = true;
}
return;
}
waitingReported = false;
if (state == null || failed) {
Snapshot saved;
try {
saved = store.load();
} catch (IOException | RuntimeException unverified) {
checkpointRequired = true;
throw unverified;
}
if (saved == null && checkpointRequired) {
throw new IOException("Reminder checkpoint was removed while running");
}
if (saved != null) checkpointRequired = true;
state = new AutoCreateVoteSitesReminderState(saved == null ? new Snapshot(0, -1) : saved,
state == null && !failed ? startedNanos : nowNanos);
failed = false;
} else if (checkpointRequired && store.load() == null) {
throw new IOException("Reminder checkpoint was removed while running");
}
recoveryRequested.set(false);
Settings current = settings;
Candidate candidate = state.propose(nowNanos, !finalCheckpoint && current.enabled(),
current.autoCreateEnabled(), current.afterMillis(), current.repeatMillis());
try {
store.save(candidate.snapshot());
} catch (PublishedException uncertain) {
checkpointRequired = true;
throw uncertain;
}
checkpointRequired = true;
state.commit(candidate);
// Do not publish a stale warning if shutdown or configuration changed during I/O.
if (candidate.reminderDue() && closing.get() == null && current.equals(settings)) {
logger.warning("After voting-site setup, set AutoCreateVoteSites: false in Config.yml.");
}
} catch (IOException | RuntimeException failure) {
failed = true;
throw failure;
}
}
/** Cancel promptly; enqueue the final checkpoint without blocking the server thread. */
public CompletableFuture<Void> closeAsync() {
CloseRequest request;
synchronized (clockGate) {
CloseRequest existing = closing.get();
if (existing != null) return existing.result();
request = new CloseRequest(new CompletableFuture<>(), clock.getAsLong());
closing.set(request);
}
CompletableFuture<Void> result = request.result();
long stoppedNanos = request.stoppedNanos();
ScheduledFuture<?> current = task;
if (current != null) current.cancel(false);
if (!started.get()) {
result.complete(null);
return result;
}
try {
executor.execute(() -> {
Exception failure = null;
try {
checkpoint(stoppedNanos, true);
} catch (IOException | RuntimeException checkpointFailure) {
failure = checkpointFailure;
} finally {
if (store != null) {
try {
store.releaseLease();
} catch (IOException | RuntimeException cleanupFailure) {
if (failure == null) failure = cleanupFailure;
else failure.addSuppressed(cleanupFailure);
}
}
}
if (failure == null) result.complete(null);
else {
logger.warning("AutoCreateVoteSites reminder checkpoint or cleanup did not complete; "
+ "inspect its storage before reloading.");
result.completeExceptionally(failure);
}
});
} catch (RuntimeException rejected) {
result.completeExceptionally(rejected);
}
return result;
}
}
@@ -1,240 +0,0 @@
package com.bencodez.votingplugin.maintenance;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.channels.OverlappingFileLockException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.OpenOption;
import java.nio.file.StandardOpenOption;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.PosixFileAttributeView;
import java.nio.file.attribute.PosixFilePermissions;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Objects;
import java.util.Set;
import com.bencodez.votingplugin.core.maintenance.AutoCreateVoteSitesReminderState.Snapshot;
import com.bencodez.votingplugin.util.DurableFiles;
/**
* A fixed, checksummed active-runtime checkpoint in the plugin's existing data
* directory. One reminder worker owns all load/save operations. This store never
* creates the directory, repairs corrupt records, or follows a record symlink.
*/
public final class AutoCreateVoteSitesReminderStore {
private static final String FILE_NAME = ".auto-create-sites-reminder.dat";
private static final byte[] MAGIC = "VPACR001".getBytes(StandardCharsets.US_ASCII);
private static final int HEADER_BYTES = 24;
private static final int RECORD_BYTES = 56;
private final Path directory;
private final Path target;
private final Publisher publisher;
private FileChannel leaseChannel;
private FileLock lease;
@FunctionalInterface
interface Publisher {
void publish(Path staged, Path target) throws IOException;
}
public AutoCreateVoteSitesReminderStore(Path dataDirectory) throws IOException {
this(dataDirectory, DurableFiles::publishStagedFile);
}
AutoCreateVoteSitesReminderStore(Path dataDirectory, Publisher publisher) throws IOException {
this.directory = Objects.requireNonNull(dataDirectory, "dataDirectory").toAbsolutePath().normalize();
this.target = directory.resolve(FILE_NAME);
this.publisher = Objects.requireNonNull(publisher, "publisher");
validateDirectory();
}
/**
* Nonblocking admission across plugin instances/class loaders in one JVM, held
* through final publication. Multiple JVMs sharing the directory are unsupported:
* closing another channel may release native locks on some platforms.
*/
public boolean tryAcquireLease() throws IOException {
if (lease != null && lease.isValid()) return true;
validateDirectory();
Path lockPath = directory.resolve(".auto-create-sites-reminder.lock");
try {
BasicFileAttributes attributes = Files.readAttributes(lockPath, BasicFileAttributes.class,
LinkOption.NOFOLLOW_LINKS);
if (!attributes.isRegularFile() || attributes.isSymbolicLink() || attributes.size() != 0) {
throw new IOException("Invalid reminder ownership file");
}
} catch (NoSuchFileException absent) {
// Create only this fixed empty metadata file inside the checked data directory.
}
Set<OpenOption> options = Set.of(StandardOpenOption.CREATE, StandardOpenOption.WRITE,
LinkOption.NOFOLLOW_LINKS);
FileChannel channel = Files.getFileAttributeView(directory, PosixFileAttributeView.class,
LinkOption.NOFOLLOW_LINKS) == null ? FileChannel.open(lockPath, options)
: FileChannel.open(lockPath, options,
PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rw-------")));
boolean acquired = false;
try {
if (channel.size() != 0) throw new IOException("Invalid reminder ownership file");
FileLock candidate;
try {
candidate = channel.tryLock();
} catch (OverlappingFileLockException busy) {
return false;
}
if (candidate == null) return false;
leaseChannel = channel;
lease = candidate;
acquired = true;
return true;
} finally {
if (!acquired) channel.close();
}
}
/** Closing the channel releases its lock; keep the fixed lock file for successors. */
public void releaseLease() throws IOException {
FileChannel channel = leaseChannel;
leaseChannel = null;
lease = null;
if (channel != null) channel.close();
}
/** Returns null only when the record is absent from a valid existing directory. */
public Snapshot load() throws IOException {
validateDirectory();
try {
return readRecord(target);
} catch (NoSuchFileException absent) {
// A missing/replaced data directory is a failure, not an absent checkpoint.
validateDirectory();
if (Files.notExists(target, LinkOption.NOFOLLOW_LINKS)) {
return null;
}
throw absent;
}
}
/**
* Publish a checked same-directory staged record using DurableFiles. Existing
* invalid or unreadable records block replacement. PublishedException propagates
* unchanged: the new record may already be visible, so no rollback is attempted.
*/
public void save(Snapshot snapshot) throws IOException {
Objects.requireNonNull(snapshot, "snapshot");
load();
Path staged = createStagedFile();
Throwable failure = null;
try {
ByteBuffer record = ByteBuffer.wrap(encode(snapshot));
try (FileChannel channel = FileChannel.open(staged, StandardOpenOption.WRITE,
StandardOpenOption.TRUNCATE_EXISTING, LinkOption.NOFOLLOW_LINKS)) {
while (record.hasRemaining()) {
if (channel.write(record) <= 0) {
throw new IOException("Could not write reminder checkpoint");
}
}
}
if (!snapshot.equals(readRecord(staged))) {
throw new IOException("Staged reminder checkpoint did not match");
}
// Recheck after staging, before replacing any existing destination.
load();
publisher.publish(staged, target);
} catch (IOException | RuntimeException | Error primary) {
failure = primary;
throw primary;
} finally {
try {
Files.deleteIfExists(staged);
} catch (IOException | RuntimeException cleanup) {
if (failure != null) {
failure.addSuppressed(cleanup);
} else {
throw new DurableFiles.PublishedException(cleanup instanceof IOException io ? io
: new IOException("Reminder staging cleanup failed after publication", cleanup));
}
}
}
}
private void validateDirectory() throws IOException {
BasicFileAttributes attributes = Files.readAttributes(directory, BasicFileAttributes.class,
LinkOption.NOFOLLOW_LINKS);
if (!attributes.isDirectory() || attributes.isSymbolicLink()) {
throw new IOException("Reminder data directory must be an existing directory");
}
}
private Path createStagedFile() throws IOException {
if (Files.getFileAttributeView(directory, PosixFileAttributeView.class, LinkOption.NOFOLLOW_LINKS) != null) {
return Files.createTempFile(directory, ".auto-create-sites-reminder-", ".tmp",
PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rw-------")));
}
return Files.createTempFile(directory, ".auto-create-sites-reminder-", ".tmp");
}
private static Snapshot readRecord(Path recordPath) throws IOException {
BasicFileAttributes attributes = Files.readAttributes(recordPath, BasicFileAttributes.class,
LinkOption.NOFOLLOW_LINKS);
if (!attributes.isRegularFile() || attributes.isSymbolicLink() || attributes.size() != RECORD_BYTES) {
throw new IOException("Invalid reminder checkpoint file");
}
ByteBuffer record = ByteBuffer.allocate(RECORD_BYTES);
try (FileChannel channel = FileChannel.open(recordPath, StandardOpenOption.READ, LinkOption.NOFOLLOW_LINKS)) {
if (channel.size() != RECORD_BYTES) {
throw new IOException("Invalid reminder checkpoint length");
}
while (record.hasRemaining()) {
if (channel.read(record) <= 0) {
throw new IOException("Incomplete reminder checkpoint");
}
}
if (channel.size() != RECORD_BYTES || channel.read(ByteBuffer.allocate(1)) != -1) {
throw new IOException("Trailing reminder checkpoint data");
}
}
return decode(record.array());
}
private static byte[] encode(Snapshot snapshot) {
ByteBuffer record = ByteBuffer.allocate(RECORD_BYTES).order(ByteOrder.BIG_ENDIAN);
record.put(MAGIC).putLong(snapshot.totalRuntimeMillis()).putLong(snapshot.lastReminderRuntimeMillis());
record.put(digest(Arrays.copyOf(record.array(), HEADER_BYTES)));
return record.array();
}
private static Snapshot decode(byte[] record) throws IOException {
if (!Arrays.equals(MAGIC, Arrays.copyOf(record, MAGIC.length))) {
throw new IOException("Invalid reminder checkpoint schema");
}
byte[] expected = digest(Arrays.copyOf(record, HEADER_BYTES));
if (!MessageDigest.isEqual(expected, Arrays.copyOfRange(record, HEADER_BYTES, RECORD_BYTES))) {
throw new IOException("Invalid reminder checkpoint checksum");
}
ByteBuffer header = ByteBuffer.wrap(record).order(ByteOrder.BIG_ENDIAN);
header.position(MAGIC.length);
try {
return new Snapshot(header.getLong(), header.getLong());
} catch (IllegalArgumentException invalid) {
throw new IOException("Invalid reminder checkpoint counters", invalid);
}
}
private static byte[] digest(byte[] header) {
try {
return MessageDigest.getInstance("SHA-256").digest(header);
} catch (NoSuchAlgorithmException unavailable) {
throw new IllegalStateException("SHA-256 is unavailable", unavailable);
}
}
}
@@ -0,0 +1,119 @@
package com.bencodez.votingplugin.npc;
import java.util.Arrays;
import java.util.UUID;
import java.util.concurrent.CompletionStage;
import org.bukkit.Location;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.bencodez.advancedcore.api.command.CommandHandler;
import com.bencodez.votingplugin.VotingPluginMain;
import com.bencodez.votingplugin.util.BukkitCompletionScheduler;
/** Normal /av command handlers; no separate command map or player GUI registry. */
public final class VotingNPCCommands {
private static final String PERMISSION = "VotingPlugin.Commands.AdminVote.NPC";
private VotingNPCCommands() { }
public static void register(VotingPluginMain plugin) {
add(plugin, new String[] { "NPC", "Create", "(string)" }, false);
add(plugin, new String[] { "NPC", "Create", "(string)", "(list)" }, false);
add(plugin, new String[] { "NPC", "List" }, true);
add(plugin, new String[] { "NPC", "Inspect", "(npcid)" }, true);
add(plugin, new String[] { "NPC", "Remove", "(npcid)" }, true);
}
private static void add(VotingPluginMain plugin, String[] pattern, boolean console) {
plugin.getAdminVoteCommand().add(new CommandHandler(plugin, pattern, PERMISSION + "|VotingPlugin.Admin",
"Manage saved vanilla voting NPCs", console) {
@Override public void execute(CommandSender sender, String[] args) {
// CommandHandler invokes execute asynchronously. Capture location,
// permission and messages only after reaching the sender's owner.
String[] captured = args.clone();
onSender(plugin, sender, () -> executeOwned(plugin, sender, captured));
}
});
}
private static boolean allowed(CommandSender sender) {
return (!(sender instanceof Player player) || player.isOnline())
&& (sender.hasPermission(PERMISSION) || sender.hasPermission("VotingPlugin.Admin"));
}
private static void onSender(VotingPluginMain plugin, CommandSender sender, Runnable action) {
Player player = sender instanceof Player candidate ? candidate : null;
BukkitCompletionScheduler.run(plugin, player, action, player == null ? action : () -> { }, () -> { });
}
private static void executeOwned(VotingPluginMain plugin, CommandSender sender, String[] args) {
if (!allowed(sender)) return;
VotingNPCManager manager = plugin.getVotingNPCManager();
if (manager == null || !manager.available()) {
sender.sendMessage("Voting NPCs are disabled, unsupported, or waiting for valid storage. Check VotingNPCs.Enabled in Config.yml and reload.");
return;
}
switch (args[1].toLowerCase(java.util.Locale.ROOT)) {
case "create":
if (!(sender instanceof Player player)) { sender.sendMessage("Create a voting NPC from in game."); return; }
try {
Location at = player.getLocation();
String name = args.length > 3 ? String.join(" ", Arrays.copyOfRange(args, 3, args.length)) : "&aVote";
VotingNPCDefinition definition = new VotingNPCDefinition(args[2], UUID.randomUUID(), at.getWorld().getUID(),
at.getX(), at.getY(), at.getZ(), at.getYaw(), at.getPitch(), name);
confirm(plugin, sender, manager, manager.create(definition),
ignored -> "Saved voting NPC '" + definition.id() + "'. Its villager appears when the area is loaded and available.");
} catch (IllegalArgumentException invalid) {
sender.sendMessage("Use a lowercase ID of 1-40 letters, digits, underscores or hyphens, and a name of 1-128 characters without controls.");
}
break;
case "remove":
confirm(plugin, sender, manager, manager.remove(args[2]), removed -> removed
? "Removed saved voting NPC '" + args[2] + "'; exact entity cleanup has been requested."
: "No voting NPC has that ID.");
break;
case "inspect":
manager.definitions().stream().filter(value -> value.id().equals(args[2])).findFirst().ifPresentOrElse(value ->
sender.sendMessage("Voting NPC " + value.id() + ": world " + value.world() + ", "
+ value.x() + ", " + value.y() + ", " + value.z() + "; " + manager.runtimeState(value.id())),
() -> sender.sendMessage("No voting NPC has that ID."));
break;
case "list":
sender.sendMessage("Saved voting NPCs: " + manager.definitions().size() + "/64; tracked runtime slots: " + manager.runtimeCount());
for (var value : manager.definitions()) sender.sendMessage(value.id() + ": " + manager.runtimeState(value.id()));
break;
default:
sender.sendMessage("Use /av npc create <id> [name], list, inspect <id>, or remove <id>.");
}
}
private static String failureMessage(VotingNPCManager manager, Throwable failure) {
while ((failure instanceof java.util.concurrent.CompletionException
|| failure instanceof java.util.concurrent.ExecutionException) && failure.getCause() != null) {
failure = failure.getCause();
}
if (manager.available()) {
if (failure instanceof VotingNPCRegistry.ValidationFailure validation) {
return switch (validation.reason) {
case DUPLICATE_ID -> "That voting NPC ID already exists. Use a different ID or remove it first.";
case DUPLICATE_IDENTITY -> "That voting NPC identity already exists. No definition was changed.";
case LIMIT -> "The 64 voting NPC limit has been reached. Remove an NPC before creating another.";
};
}
if (failure instanceof java.util.concurrent.RejectedExecutionException) {
return "Voting NPC storage is busy. Wait for pending changes to finish before retrying.";
}
}
return "Voting NPC change was not confirmed. Check storage and reload before retrying; no success is assumed.";
}
private static <T> void confirm(VotingPluginMain plugin, CommandSender sender, VotingNPCManager manager, CompletionStage<T> completion,
java.util.function.Function<T, String> message) {
completion.whenComplete((value, failure) -> onSender(plugin, sender, () -> {
if (!allowed(sender)) return;
sender.sendMessage(failure == null ? message.apply(value)
: failureMessage(manager, failure));
}));
}
}
@@ -0,0 +1,29 @@
package com.bencodez.votingplugin.npc;
import java.util.Objects;
import java.util.UUID;
import java.util.regex.Pattern;
/** Durable definition; it contains no live world, player, entity or reward state. */
public record VotingNPCDefinition(String id, UUID identity, UUID world, double x, double y, double z,
float yaw, float pitch, String name) {
private static final Pattern ID = Pattern.compile("[a-z0-9][a-z0-9_-]{0,39}");
public VotingNPCDefinition {
if (id == null || !ID.matcher(id).matches()) throw new IllegalArgumentException("Invalid voting NPC ID");
Objects.requireNonNull(identity, "identity");
Objects.requireNonNull(world, "world");
if (!Double.isFinite(x) || !Double.isFinite(y) || !Double.isFinite(z)
|| Math.abs(x) > 30_000_000 || Math.abs(z) > 30_000_000
|| !Float.isFinite(yaw) || !Float.isFinite(pitch)) {
throw new IllegalArgumentException("Invalid voting NPC position");
}
if (name == null || name.isEmpty() || name.length() > 128
|| name.codePoints().anyMatch(Character::isISOControl)) {
throw new IllegalArgumentException("Invalid voting NPC name");
}
}
public int chunkX() { return Math.floorDiv((int) Math.floor(x), 16); }
public int chunkZ() { return Math.floorDiv((int) Math.floor(z), 16); }
}
@@ -0,0 +1,450 @@
package com.bencodez.votingplugin.npc;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Consumer;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.entity.Villager;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityCombustEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityInteractEvent;
import org.bukkit.event.entity.EntityTargetEvent;
import org.bukkit.event.entity.EntityTeleportEvent;
import org.bukkit.event.entity.EntityTransformEvent;
import org.bukkit.event.player.PlayerInteractAtEntityEvent;
import org.bukkit.event.player.PlayerInteractEntityEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.vehicle.VehicleEnterEvent;
import org.bukkit.event.world.ChunkLoadEvent;
import org.bukkit.event.world.ChunkUnloadEvent;
import org.bukkit.event.world.WorldLoadEvent;
import org.bukkit.event.world.WorldUnloadEvent;
import org.bukkit.inventory.EquipmentSlot;
import com.bencodez.votingplugin.VotingPluginMain;
import com.bencodez.votingplugin.util.BukkitCompletionScheduler;
/** Persistent definitions, transient public villagers, and no vote/reward accounting. */
public final class VotingNPCManager implements Listener, AutoCloseable {
private final VotingPluginMain plugin;
private final VotingNPCScheduler scheduler;
private final Consumer<Player> open;
private final Map<String, RuntimeNPC> resources = new ConcurrentHashMap<>();
private final Set<String> capacityDemand = ConcurrentHashMap.newKeySet();
private final AtomicBoolean capacityWakeQueued = new AtomicBoolean();
private final Map<UUID, RuntimeNPC> entities = new ConcurrentHashMap<>();
private final Set<ChunkKey> unloadingChunks = ConcurrentHashMap.newKeySet();
private final Set<UUID> unloadingWorlds = ConcurrentHashMap.newKeySet();
private final Map<UUID, Long> recentClicks = new LinkedHashMap<>();
private volatile VotingNPCRegistry registry;
private volatile boolean enabled;
private volatile boolean closed;
private volatile long configuration;
private final AtomicBoolean warned = new AtomicBoolean();
private record ChunkKey(UUID world, int x, int z) { }
private static final class RuntimeNPC {
final VotingNPCDefinition definition;
final Location anchor;
final long configuration;
boolean closed, cleanupQueued, reconstructRequested;
Villager entity;
UUID entityId;
RuntimeNPC(VotingNPCDefinition definition, World world, long configuration) {
this.definition = definition;
this.configuration = configuration;
anchor = new Location(world, definition.x(), definition.y(), definition.z(), definition.yaw(), definition.pitch());
}
}
public VotingNPCManager(VotingPluginMain plugin) {
this(plugin, new VotingNPCScheduler(plugin), null, player -> openVotingSites(plugin, player));
}
static void openVotingSites(VotingPluginMain plugin, Player player) {
// Reuse the normal command's permissions, asynchronous user loading,
// configured GUI, cooldown display, and URL handling; no root alias.
for (var handler : plugin.getVoteCommand()) {
if (handler.runCommand(player, new String[] { "URL" })) return;
}
player.sendMessage("Voting-site selection is unavailable.");
}
VotingNPCManager(VotingPluginMain plugin, VotingNPCScheduler scheduler, VotingNPCRegistry registry, Consumer<Player> open) {
this.plugin = plugin;
this.scheduler = scheduler;
this.registry = registry;
this.open = open;
}
public static boolean supported() {
try {
Entity.class.getMethod("setPersistent", boolean.class);
Entity.class.getMethod("setGravity", boolean.class);
Entity.class.getMethod("setInvulnerable", boolean.class);
LivingEntity.class.getMethod("setAI", boolean.class);
LivingEntity.class.getMethod("setCollidable", boolean.class);
World.class.getMethod("spawn", Location.class, Class.class, Consumer.class);
return true;
} catch (ReflectiveOperationException | LinkageError unavailable) { return false; }
}
/** Configuration callers do no file I/O and do not wait for storage. */
public void configure(boolean requested) {
VotingNPCRegistry owner;
CompletionStage<List<VotingNPCDefinition>> loading;
long generation;
boolean activate;
synchronized (this) {
if (closed) return;
generation = ++configuration;
activate = requested && supported();
enabled = activate;
if (!activate) { owner = null; loading = null; }
else {
if (registry == null) {
registry = new VotingNPCRegistry(plugin.getDataFolder().toPath().resolve("VotingNPCs.json"));
loading = registry.initialLoad();
} else loading = registry.reload();
owner = registry;
}
}
if (!activate) {
for (RuntimeNPC npc : resources.values()) retire(npc);
if (requested) report(new IllegalStateException("Vanilla voting NPC API is unavailable"));
return;
}
loading.whenComplete((definitions, failure) -> {
synchronized (VotingNPCManager.this) {
if (closed || !enabled || generation != configuration || registry != owner) return;
}
if (failure != null) {
for (RuntimeNPC npc : resources.values()) retire(npc);
report(failure);
} else {
warned.set(false);
reconcile();
}
});
}
public boolean available() {
VotingNPCRegistry owner = registry;
return !closed && enabled && owner != null && owner.available();
}
public List<VotingNPCDefinition> definitions() {
VotingNPCRegistry owner = registry;
return owner == null ? List.of() : owner.snapshot();
}
/** Returns durable definition completion; runtime creation can still await a loaded chunk. */
public CompletionStage<VotingNPCDefinition> create(VotingNPCDefinition definition) {
VotingNPCRegistry owner = registry;
if (!available()) return CompletableFuture.failedFuture(new IllegalStateException("Enable VotingNPCs and load valid storage first"));
CompletionStage<VotingNPCDefinition> completion = owner.create(definition);
completion.whenComplete((value, failure) -> mutationFinished(owner, failure));
return completion;
}
public CompletionStage<Boolean> remove(String id) {
VotingNPCRegistry owner = registry;
if (!available()) return CompletableFuture.failedFuture(new IllegalStateException("Enable VotingNPCs and load valid storage first"));
CompletionStage<Boolean> completion = owner.remove(id);
completion.whenComplete((value, failure) -> mutationFinished(owner, failure));
return completion;
}
private void mutationFinished(VotingNPCRegistry owner, Throwable failure) {
if (owner != registry || closed) return;
if (failure == null) reconcile();
else if (!owner.available()) {
for (RuntimeNPC npc : resources.values()) retire(npc);
report(failure);
}
}
private boolean current(RuntimeNPC npc) {
return available() && definitions().contains(npc.definition);
}
private void reconcile() {
retryPendingCleanup();
capacityDemand.retainAll(definitions().stream().map(VotingNPCDefinition::id).toList());
List<VotingNPCDefinition> snapshot = definitions();
Set<ChunkKey> chunks = new HashSet<>();
Set<UUID> worlds = new HashSet<>();
for (var value : snapshot) { chunks.addAll(occupiedChunks(value)); worlds.add(value.world()); }
unloadingChunks.retainAll(chunks);
unloadingWorlds.retainAll(worlds);
for (RuntimeNPC npc : resources.values()) if (!current(npc)) retire(npc);
if (!available()) return;
scheduler.global(() -> {
if (!available()) return;
for (var value : definitions()) ensure(value);
}, this::report);
}
/** Same conservative half-block bounds used for creation ownership and chunk availability. */
private static Set<ChunkKey> occupiedChunks(VotingNPCDefinition value) {
Set<ChunkKey> chunks = new HashSet<>();
for (double dx : new double[] { -.5, .5 }) for (double dz : new double[] { -.5, .5 }) {
chunks.add(new ChunkKey(value.world(), (int) Math.floor(value.x() + dx) >> 4,
(int) Math.floor(value.z() + dz) >> 4));
}
return chunks;
}
private boolean unloading(VotingNPCDefinition value) {
return occupiedChunks(value).stream().anyMatch(unloadingChunks::contains);
}
private void ensure(VotingNPCDefinition value) {
if (!available() || !definitions().contains(value) || unloadingWorlds.contains(value.world()) || unloading(value)) return;
World world = Bukkit.getWorld(value.world());
if (world == null) return;
RuntimeNPC npc = new RuntimeNPC(value, world, configuration);
RuntimeNPC previous;
synchronized (resources) {
previous = resources.get(value.id());
if (previous == null) {
if (resources.size() >= VotingNPCStore.MAX_NPCS) {
if (capacityDemand.size() < VotingNPCStore.MAX_NPCS) capacityDemand.add(value.id());
return;
}
resources.put(value.id(), npc);
capacityDemand.remove(value.id());
}
}
if (previous != null) {
synchronized (previous) { if (previous.closed) previous.reconstructRequested = true; }
return;
}
scheduler.region(npc.anchor, () -> spawn(npc), failure -> { retire(npc); report(failure); });
}
private boolean loadedArea(RuntimeNPC npc) {
World world = npc.anchor.getWorld();
if (Bukkit.getWorld(npc.definition.world()) != world || unloadingWorlds.contains(npc.definition.world())
|| unloading(npc.definition)) return false;
for (double dx : new double[] { -.5, .5 }) for (double dz : new double[] { -.5, .5 }) {
Location edge = npc.anchor.clone().add(dx, 0, dz);
if (!scheduler.owns(edge) || !world.isChunkLoaded(edge.getBlockX() >> 4, edge.getBlockZ() >> 4)) return false;
}
return true;
}
private void spawn(RuntimeNPC npc) {
try {
synchronized (npc) {
if (npc.closed || !current(npc) || !loadedArea(npc)) {
boolean capacityReleased = !npc.closed && !current(npc);
forget(npc, capacityReleased);
return;
}
if (npc.entity != null) return;
Villager spawned = npc.anchor.getWorld().spawn(npc.anchor, Villager.class, villager -> {
npc.entity = villager;
npc.entityId = villager.getUniqueId();
entities.put(npc.entityId, npc);
villager.setPersistent(false);
villager.setAI(false);
villager.setGravity(false);
villager.setInvulnerable(true);
villager.setSilent(true);
villager.setCollidable(false);
villager.setCanPickupItems(false);
villager.setRemoveWhenFarAway(false);
villager.setCustomName(ChatColor.translateAlternateColorCodes('&', npc.definition.name()));
villager.setCustomNameVisible(true);
});
if (spawned != npc.entity || !spawned.isValid() || !current(npc) || npc.closed) {
throw new IllegalStateException("Voting NPC spawn was cancelled or superseded");
}
}
} catch (RuntimeException | LinkageError failure) { retire(npc); report(failure); }
}
private void retire(RuntimeNPC npc) {
Villager entity;
synchronized (npc) {
npc.closed = true;
entity = npc.entity;
if (entity == null) { forget(npc, false); return; }
if (npc.cleanupQueued) return;
npc.cleanupQueued = true;
}
scheduler.entity(entity, () -> {
try { entity.remove(); forget(npc); }
catch (RuntimeException | LinkageError failure) { cleanupFailed(npc, failure); }
}, () -> forget(npc), failure -> cleanupFailed(npc, failure));
}
private void cleanupFailed(RuntimeNPC npc, Throwable failure) {
synchronized (npc) {
npc.cleanupQueued = false;
npc.reconstructRequested = true;
}
// Keep the exact identity and capacity reservation. Rejected scheduling
// is not successful removal and must not permit duplicate reconstruction.
report(failure);
}
private void retryPendingCleanup() {
for (RuntimeNPC npc : resources.values()) {
synchronized (npc) {
if (!npc.closed || !npc.reconstructRequested || npc.cleanupQueued || npc.entity == null) continue;
}
retire(npc);
}
}
private void forget(RuntimeNPC npc) { forget(npc, false); }
private void forget(RuntimeNPC npc, boolean capacityReleased) {
boolean reconstruct, removed;
synchronized (npc) {
reconstruct = npc.entity != null && (npc.reconstructRequested || npc.configuration != configuration
|| definitions().stream().anyMatch(value -> value.id().equals(npc.definition.id()) && !value.equals(npc.definition)));
if (npc.entityId != null) entities.remove(npc.entityId, npc);
npc.entity = null;
removed = resources.remove(npc.definition.id(), npc);
}
// A successor sharing this configured ID must wait for exact predecessor
// cleanup. Missing/unloaded spawn attempts do not recursively retry.
if (reconstruct && available()) scheduler.global(() -> {
for (var value : definitions()) if (value.id().equals(npc.definition.id())) ensure(value);
}, this::report);
if (removed && !capacityDemand.isEmpty() && available()
&& capacityWakeQueued.compareAndSet(false, true)) {
scheduler.global(() -> {
capacityWakeQueued.set(false);
for (var value : definitions()) if (capacityDemand.contains(value.id())) ensure(value);
}, failure -> {
capacityWakeQueued.set(false);
report(failure);
});
}
}
private void report(Throwable failure) {
if (warned.compareAndSet(false, true)) {
try {
plugin.getLogger().warning("Voting NPCs could not complete an operation; definitions are retained. Check API support and VotingNPCs.json, then reload. Cause: "
+ failure.getClass().getSimpleName());
} catch (RuntimeException ignored) { /* Reporting must not prevent independent cleanup. */ }
}
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = false)
public void interact(PlayerInteractEntityEvent event) {
RuntimeNPC npc = entities.get(event.getRightClicked().getUniqueId());
if (npc == null) return;
boolean cancelled = event.isCancelled();
event.setCancelled(true); // Only this exact owned entity; never trading.
if (cancelled || event.getHand() != EquipmentSlot.HAND || !current(npc)) return;
synchronized (npc) { if (npc.closed) { retire(npc); return; } }
Player player = event.getPlayer();
long now = System.nanoTime();
synchronized (recentClicks) {
recentClicks.entrySet().removeIf(entry -> now - entry.getValue() >= 300_000_000L);
if (recentClicks.containsKey(player.getUniqueId()) || recentClicks.size() >= 256) return;
recentClicks.put(player.getUniqueId(), now);
}
BukkitCompletionScheduler.run(plugin, player, () -> {
if (!player.isOnline() || !current(npc) || !player.getWorld().getUID().equals(npc.definition.world())
|| player.getLocation().distanceSquared(npc.anchor) > 36) return;
synchronized (npc) { if (npc.closed) return; }
open.accept(player);
}, () -> { }, () -> { });
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = false)
public void interactAt(PlayerInteractAtEntityEvent event) { interact(event); }
private boolean owned(Entity entity) { return entity != null && entities.containsKey(entity.getUniqueId()); }
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = false)
public void damage(EntityDamageEvent event) { if (owned(event.getEntity())) event.setCancelled(true); }
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = false)
public void combust(EntityCombustEvent event) { if (owned(event.getEntity())) event.setCancelled(true); }
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = false)
public void teleport(EntityTeleportEvent event) { if (owned(event.getEntity())) event.setCancelled(true); }
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = false)
public void transform(EntityTransformEvent event) { if (owned(event.getEntity())) event.setCancelled(true); }
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = false)
public void target(EntityTargetEvent event) { if (owned(event.getEntity()) || owned(event.getTarget())) event.setCancelled(true); }
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = false)
public void blockInteract(EntityInteractEvent event) { if (owned(event.getEntity())) event.setCancelled(true); }
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = false)
public void vehicle(VehicleEnterEvent event) { if (owned(event.getEntered())) event.setCancelled(true); }
@EventHandler public void quit(PlayerQuitEvent event) { synchronized (recentClicks) { recentClicks.remove(event.getPlayer().getUniqueId()); } }
@EventHandler(priority = EventPriority.MONITOR)
public void chunkLoad(ChunkLoadEvent event) {
UUID world = event.getWorld().getUID();
unloadingChunks.remove(new ChunkKey(world, event.getChunk().getX(), event.getChunk().getZ()));
retryPendingCleanup();
ChunkKey chunk = new ChunkKey(world, event.getChunk().getX(), event.getChunk().getZ());
for (var value : definitions()) if (occupiedChunks(value).contains(chunk)) ensure(value);
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void chunkUnload(ChunkUnloadEvent event) {
ChunkKey chunk = new ChunkKey(event.getWorld().getUID(), event.getChunk().getX(), event.getChunk().getZ());
if (definitions().stream().noneMatch(value -> occupiedChunks(value).contains(chunk))) return;
unloadingChunks.add(chunk);
for (RuntimeNPC npc : resources.values()) if (occupiedChunks(npc.definition).contains(chunk)) retire(npc);
}
@EventHandler(priority = EventPriority.MONITOR)
public void worldLoad(WorldLoadEvent event) {
UUID world = event.getWorld().getUID();
if (definitions().stream().noneMatch(value -> value.world().equals(world))) return;
unloadingWorlds.remove(world);
reconcile();
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void worldUnload(WorldUnloadEvent event) {
UUID world = event.getWorld().getUID();
if (definitions().stream().noneMatch(value -> value.world().equals(world))) return;
unloadingWorlds.add(world);
for (RuntimeNPC npc : resources.values()) if (npc.definition.world().equals(world)) retire(npc);
}
public int runtimeCount() { return resources.size(); }
public String runtimeState(String id) {
RuntimeNPC npc = resources.get(id);
if (npc == null) return "waiting for a loaded, available area";
synchronized (npc) {
if (npc.closed) return "cleanup pending";
return npc.entity == null ? "creation scheduled" : "villager created";
}
}
@Override public void close() {
synchronized (this) { if (closed) return; closed = true; enabled = false; ++configuration; }
VotingNPCRegistry owner = registry;
if (owner != null) owner.close();
for (RuntimeNPC npc : new ArrayList<>(resources.values())) retire(npc);
synchronized (recentClicks) { recentClicks.clear(); }
}
}
@@ -0,0 +1,206 @@
package com.bencodez.votingplugin.npc;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.channels.OverlappingFileLockException;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit;
/**
* One bounded, daemon file owner. Completion means the definition was persisted,
* not that a world entity has spawned. Callbacks have no player/region ownership.
*/
final class VotingNPCRegistry implements AutoCloseable {
enum Rejection { DUPLICATE_ID, DUPLICATE_IDENTITY, LIMIT }
static final class ValidationFailure extends IllegalArgumentException {
private static final long serialVersionUID = 1L;
final Rejection reason;
ValidationFailure(Rejection reason) { super("Voting NPC request rejected"); this.reason = reason; }
}
private final Object admission = new Object();
private final ArrayBlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(128);
private final CountDownLatch stopped = new CountDownLatch(1);
private final VotingNPCStore store;
private final Path lockPath;
private final CompletableFuture<List<VotingNPCDefinition>> initial;
private volatile Map<String, VotingNPCDefinition> definitions = Map.of();
private volatile boolean available;
private volatile boolean closed;
// Only the file worker accesses these resources.
private FileChannel lockChannel;
private FileLock lease;
private boolean storageReady;
VotingNPCRegistry(Path file) {
this(file, new VotingNPCStore(file));
}
VotingNPCRegistry(Path file, VotingNPCStore store) {
this.store = store;
lockPath = file.toAbsolutePath().normalize().resolveSibling(file.getFileName() + ".lock");
initial = submit(false, this::readDefinitions);
Thread thread = new Thread(this::work, "VotingPlugin-NPC-storage");
thread.setDaemon(true);
try { thread.start(); }
catch (RuntimeException | Error failure) {
closed = true;
initial.completeExceptionally(failure);
stopped.countDown();
throw failure;
}
}
CompletionStage<List<VotingNPCDefinition>> initialLoad() { return initial; }
boolean available() { return !closed && available; }
List<VotingNPCDefinition> snapshot() { return List.copyOf(definitions.values()); }
CompletionStage<List<VotingNPCDefinition>> reload() {
synchronized (admission) {
if (closed) return rejected("Voting NPC registry is closed");
var completion = submit(false, this::readDefinitions);
// A rejected reload changes nothing. The worker publishes readiness
// under this same short lock, after admission has finished.
if (!completion.isCompletedExceptionally()) available = false;
return completion;
}
}
CompletionStage<VotingNPCDefinition> create(VotingNPCDefinition definition) {
return submit(true, () -> {
if (definition == null) throw new IllegalArgumentException("Voting NPC definition is required");
if (definitions.containsKey(definition.id())) throw new ValidationFailure(Rejection.DUPLICATE_ID);
if (definitions.values().stream().anyMatch(value -> value.identity().equals(definition.identity()))) {
throw new ValidationFailure(Rejection.DUPLICATE_IDENTITY);
}
if (definitions.size() >= VotingNPCStore.MAX_NPCS) throw new ValidationFailure(Rejection.LIMIT);
var next = new LinkedHashMap<>(definitions);
next.put(definition.id(), definition);
publish(next);
return definition;
});
}
CompletionStage<Boolean> remove(String id) {
return submit(true, () -> {
if (!definitions.containsKey(id)) return false;
var next = new LinkedHashMap<>(definitions);
next.remove(id);
publish(next);
return true;
});
}
private List<VotingNPCDefinition> readDefinitions() throws IOException {
try {
ownFile();
List<VotingNPCDefinition> loaded = store.load();
var next = new LinkedHashMap<String, VotingNPCDefinition>();
for (VotingNPCDefinition value : loaded) next.put(value.id(), value);
definitions = java.util.Collections.unmodifiableMap(next);
storageReady = true;
synchronized (admission) { available = true; }
return loaded;
} catch (IOException | RuntimeException failure) {
storageReady = false;
synchronized (admission) { available = false; }
throw failure;
}
}
private void publish(LinkedHashMap<String, VotingNPCDefinition> next) throws IOException {
// The worker holds the process-independent lease through shutdown drain.
try { store.save(List.copyOf(next.values())); }
catch (IOException | RuntimeException | Error failure) {
// A failed write may already be visible. Neither later admitted
// mutations nor a new request may overwrite it from the old map.
storageReady = false;
synchronized (admission) { available = false; }
throw failure;
}
definitions = java.util.Collections.unmodifiableMap(next);
}
private <T> CompletableFuture<T> submit(boolean needsReady, Callable<T> action) {
synchronized (admission) {
if (closed || (needsReady && !available)) return rejected("Voting NPC storage is not available");
var completion = new CompletableFuture<T>();
Runnable task = () -> {
try {
if (needsReady && !storageReady) throw new RejectedExecutionException("Reload valid voting NPC storage before editing");
completion.complete(action.call());
}
catch (Throwable failure) { completion.completeExceptionally(failure); }
};
if (!queue.offer(task)) completion.completeExceptionally(new RejectedExecutionException("Voting NPC storage queue is full"));
return completion;
}
}
private static <T> CompletableFuture<T> rejected(String message) {
return CompletableFuture.failedFuture(new RejectedExecutionException(message));
}
private void ownFile() throws IOException {
if (lease != null && lease.isValid()) return;
if (!Files.isDirectory(lockPath.getParent().toRealPath(), LinkOption.NOFOLLOW_LINKS)) {
throw new IOException("Voting NPC data directory is unavailable");
}
FileChannel candidate = FileChannel.open(lockPath, StandardOpenOption.CREATE,
StandardOpenOption.WRITE, LinkOption.NOFOLLOW_LINKS);
try {
FileLock acquired;
try { acquired = candidate.tryLock(); }
catch (OverlappingFileLockException overlap) { throw new IOException("Voting NPC file still has an active owner", overlap); }
if (acquired == null) throw new IOException("Voting NPC file still has an active owner");
lockChannel = candidate;
lease = acquired;
} finally {
if (lockChannel != candidate) candidate.close();
}
}
private void work() {
try {
while (!closed || !queue.isEmpty()) {
Runnable task;
try { task = queue.take(); }
catch (InterruptedException interrupted) { continue; }
task.run();
}
} finally {
available = false;
try {
if (lockChannel != null) lockChannel.close();
} catch (IOException ignored) {
// Closing this channel releases its OS lease; never do this I/O
// under an admission or executor lock on a gameplay caller.
} finally { stopped.countDown(); }
}
}
/** Stops admission without blocking or interrupting an accepted file write. */
@Override public void close() {
synchronized (admission) {
if (closed) return;
closed = true;
queue.offer(() -> { }); // Wake an idle worker; a full queue already wakes it.
}
}
/** Test/owner-worker observation only; gameplay callers must never wait here. */
boolean awaitClosed(long time, TimeUnit unit) throws InterruptedException { return stopped.await(time, unit); }
}
@@ -0,0 +1,77 @@
package com.bencodez.votingplugin.npc;
import java.lang.reflect.Method;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Consumer;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.entity.Entity;
import com.bencodez.votingplugin.VotingPluginMain;
import com.bencodez.votingplugin.util.BukkitCompletionScheduler;
/** World creation uses a region; subsequent cleanup follows the actual entity. */
class VotingNPCScheduler {
private final VotingPluginMain plugin;
private final Method locationOwner;
private final Method entityOwner;
VotingNPCScheduler(VotingPluginMain plugin) {
this.plugin = plugin;
Method location = null, entity = null;
try {
Class.forName("io.papermc.paper.threadedregions.RegionizedServer");
location = Bukkit.class.getMethod("isOwnedByCurrentRegion", Location.class);
entity = Bukkit.class.getMethod("isOwnedByCurrentRegion", Entity.class);
} catch (ClassNotFoundException ordinaryServer) {
// Spigot/Paper have a single world-owner thread.
} catch (ReflectiveOperationException unavailable) {
throw new IllegalStateException("Voting NPC region ownership API is unavailable", unavailable);
}
locationOwner = location;
entityOwner = entity;
}
boolean owns(Location location) { return owns(locationOwner, location); }
boolean owns(Entity entity) { return owns(entityOwner, entity); }
private boolean owns(Method method, Object value) {
if (method == null) return Bukkit.isPrimaryThread();
try { return Boolean.TRUE.equals(method.invoke(null, value)); }
catch (ReflectiveOperationException failure) { throw new IllegalStateException("Cannot verify voting NPC ownership", failure); }
}
void global(Runnable action, Consumer<Throwable> failure) {
try {
plugin.getBukkitScheduler().getFoliaLib().getImpl().runNextTick(ignored -> action.run())
.whenComplete((ignored, failed) -> { if (failed != null) failure.accept(failed); });
} catch (RuntimeException | LinkageError rejected) { failure.accept(rejected); }
}
void region(Location anchor, Runnable action, Consumer<Throwable> failure) {
try {
if (owns(anchor)) action.run();
else plugin.getBukkitScheduler().getFoliaLib().getImpl().runAtLocation(anchor, ignored -> action.run())
.whenComplete((ignored, failed) -> { if (failed != null) failure.accept(failed); });
} catch (RuntimeException | LinkageError rejected) { failure.accept(rejected); }
}
void entity(Entity entity, Runnable action, Runnable retired, Consumer<Throwable> failure) {
AtomicBoolean executed = new AtomicBoolean();
Runnable run = () -> { if (executed.compareAndSet(false, true)) action.run(); };
Runnable gone = () -> { if (executed.compareAndSet(false, true)) retired.run(); };
try {
if (owns(entity)) { run.run(); return; }
plugin.getBukkitScheduler().getFoliaLib().getImpl().runAtEntityWithFallback(entity,
ignored -> run.run(), gone).whenComplete((status, failed) -> {
if (failed != null) failure.accept(failed);
else if (status instanceof Enum<?> result && "ENTITY_RETIRED".equals(result.name())) gone.run();
else if (!BukkitCompletionScheduler.isSuccessfulEntityTaskResult(status)) {
// Scheduler retirement does not prove the entity was removed.
failure.accept(new IllegalStateException("Voting NPC entity scheduler is unavailable"));
}
});
} catch (RuntimeException | LinkageError rejected) { failure.accept(rejected); }
}
}
@@ -0,0 +1,199 @@
package com.bencodez.votingplugin.npc;
import java.io.IOException;
import java.io.StringReader;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.CodingErrorAction;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
import com.bencodez.votingplugin.util.DurableFiles;
/** Single storage-worker owner. Never call this file boundary on a gameplay thread. */
class VotingNPCStore {
static final int MAX_NPCS = 64;
private static final int MAX_BYTES = 128 * 1024;
private static final Set<String> FIELDS = Set.of("id", "identity", "world", "x", "y", "z", "yaw", "pitch", "name");
private final Path file;
private boolean initialized;
private boolean uncertain;
VotingNPCStore(Path file) { this.file = file.toAbsolutePath().normalize(); }
synchronized List<VotingNPCDefinition> load() throws IOException {
initialized = false;
checkParent();
BasicFileAttributes attributes;
try { attributes = Files.readAttributes(file, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); }
catch (NoSuchFileException missing) {
if (uncertain) throw new IOException("Uncertain voting NPC definitions are missing", missing);
initialized = true;
return List.of();
}
if (!attributes.isRegularFile() || attributes.isSymbolicLink() || attributes.size() > MAX_BYTES) {
throw new IOException("Voting NPC definitions are not a bounded regular file");
}
byte[] bytes;
try (var input = Files.newInputStream(file, LinkOption.NOFOLLOW_LINKS)) {
bytes = input.readNBytes(MAX_BYTES + 1);
}
if (bytes.length > MAX_BYTES) throw new IOException("Voting NPC definitions exceed limit");
String text;
try { text = StandardCharsets.UTF_8.newDecoder().onMalformedInput(CodingErrorAction.REPORT)
.onUnmappableCharacter(CodingErrorAction.REPORT).decode(ByteBuffer.wrap(bytes)).toString(); }
catch (CharacterCodingException invalid) { throw new IOException("Invalid voting NPC encoding", invalid); }
List<VotingNPCDefinition> result = decode(text);
uncertain = false;
initialized = true;
return result;
}
synchronized void save(List<VotingNPCDefinition> definitions) throws IOException {
if (!initialized || uncertain) throw new IOException("Load valid voting NPC definitions before editing");
validate(definitions);
byte[] bytes = encode(definitions).getBytes(StandardCharsets.UTF_8);
if (bytes.length > MAX_BYTES) throw new IOException("Voting NPC definitions exceed limit");
checkParent();
if (Files.isSymbolicLink(file)) throw new IOException("Voting NPC definitions cannot be a symbolic link");
Path staged = Files.createTempFile(file.getParent(), ".voting-npcs-", ".tmp");
boolean published = false;
Throwable primary = null;
try {
try (FileChannel output = FileChannel.open(staged, StandardOpenOption.WRITE)) {
ByteBuffer buffer = ByteBuffer.wrap(bytes);
while (buffer.hasRemaining()) output.write(buffer);
output.force(true);
}
Files.move(staged, file, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
published = true;
forceDirectory(file.getParent());
} catch (IOException | RuntimeException | Error failure) {
// A visible replacement followed by a failed directory sync is not a
// rollback. Fence later mutations rather than overwrite it from old state.
if (published) uncertain = true;
primary = failure;
throw failure;
} finally {
try { Files.deleteIfExists(staged); }
catch (IOException cleanupFailure) {
if (primary != null) primary.addSuppressed(cleanupFailure);
else {
if (published) uncertain = true;
throw cleanupFailure;
}
}
}
}
private void checkParent() throws IOException {
// Operators may place the data directory below a directory alias. Only
// the definitions and lease files themselves must remain non-links.
if (!Files.isDirectory(file.getParent().toRealPath(), LinkOption.NOFOLLOW_LINKS)) {
throw new IOException("Voting NPC data directory is unavailable");
}
}
/** Kept as a narrow I/O seam so failure-after-publication can be tested. */
void forceDirectory(Path directory) throws IOException {
DurableFiles.forceDirectory(directory);
}
private static void validate(List<VotingNPCDefinition> values) throws IOException {
if (values == null || values.size() > MAX_NPCS) throw new IOException("Voting NPC definition limit exceeded");
Set<String> ids = new HashSet<>();
Set<UUID> identities = new HashSet<>();
for (VotingNPCDefinition value : values) {
if (value == null || !ids.add(value.id()) || !identities.add(value.identity())) {
throw new IOException("Duplicate or missing voting NPC identity");
}
}
}
private static String encode(List<VotingNPCDefinition> values) throws IOException {
var text = new java.io.StringWriter();
try (JsonWriter writer = new JsonWriter(text)) {
writer.setIndent(" ");
writer.beginObject().name("version").value(1).name("npcs").beginArray();
for (VotingNPCDefinition value : values) {
writer.beginObject().name("id").value(value.id()).name("identity").value(value.identity().toString())
.name("world").value(value.world().toString()).name("x").value(value.x()).name("y").value(value.y())
.name("z").value(value.z()).name("yaw").value(value.yaw()).name("pitch").value(value.pitch())
.name("name").value(value.name()).endObject();
}
writer.endArray().endObject();
}
return text.toString() + "\n";
}
private static List<VotingNPCDefinition> decode(String text) throws IOException {
try (JsonReader reader = new JsonReader(new StringReader(text))) {
Set<String> keys = new HashSet<>();
List<VotingNPCDefinition> values = null;
reader.beginObject();
while (reader.hasNext()) {
String key = reader.nextName();
if (!keys.add(key)) throw new IOException("Duplicate voting NPC document field");
if (key.equals("version")) {
if (reader.peek() != JsonToken.NUMBER || !reader.nextString().equals("1")) {
throw new IOException("Unsupported voting NPC document version");
}
} else if (key.equals("npcs")) {
values = new ArrayList<>();
reader.beginArray();
while (reader.hasNext()) {
if (values.size() >= MAX_NPCS) throw new IOException("Voting NPC definition limit exceeded");
values.add(readDefinition(reader));
}
reader.endArray();
} else throw new IOException("Unknown voting NPC document field");
}
reader.endObject();
if (!keys.equals(Set.of("version", "npcs")) || reader.peek() != JsonToken.END_DOCUMENT) {
throw new IOException("Incomplete or trailing voting NPC document");
}
validate(values);
return List.copyOf(values);
} catch (IllegalArgumentException | IllegalStateException invalid) {
throw new IOException("Invalid voting NPC definitions", invalid);
}
}
private static VotingNPCDefinition readDefinition(JsonReader reader) throws IOException {
var fields = new java.util.HashMap<String, String>();
reader.beginObject();
while (reader.hasNext()) {
String field = reader.nextName();
if (!FIELDS.contains(field) || fields.containsKey(field)) throw new IOException("Unknown or duplicate voting NPC field");
boolean numeric = Set.of("x", "y", "z", "yaw", "pitch").contains(field);
if (reader.peek() != (numeric ? JsonToken.NUMBER : JsonToken.STRING)) throw new IOException("Invalid voting NPC field type");
fields.put(field, reader.nextString());
}
reader.endObject();
if (!fields.keySet().equals(FIELDS)) throw new IOException("Missing voting NPC field");
return new VotingNPCDefinition(fields.get("id"), uuid(fields.get("identity")), uuid(fields.get("world")),
Double.parseDouble(fields.get("x")), Double.parseDouble(fields.get("y")), Double.parseDouble(fields.get("z")),
Float.parseFloat(fields.get("yaw")), Float.parseFloat(fields.get("pitch")), fields.get("name"));
}
private static UUID uuid(String text) {
UUID value = UUID.fromString(text);
if (!value.toString().equals(text)) throw new IllegalArgumentException("Noncanonical voting NPC identity");
return value;
}
}
@@ -67,8 +67,6 @@ public class PlaceHolders {
private record PlatformUpdateKey(UUID uuid, PlaceHolder<VotingPluginUser> placeholder) { }
private final ConcurrentHashMap<PlatformUpdateKey, Long> platformUpdateGenerations = new ConcurrentHashMap<>();
private boolean userDataChangeListenerRegistered;
private final PointPlaceholderFence pointFence = new PointPlaceholderFence();
private final ConcurrentHashMap<UUID, Object> pointRecoveryWorkers = new ConcurrentHashMap<>();
@Getter
private PlaceholderCacheLevel cacheLevel;
@@ -187,103 +185,6 @@ public class PlaceHolders {
* @return the placeholder value
*/
public String getPlaceholderValue(OfflinePlayer p, String identifier, boolean javascript, boolean forceProcess,
boolean useCache) {
if (p == null || !isPointIdentifier(identifier)) {
return getPlaceholderValueUnfenced(p, identifier, javascript, forceProcess, useCache);
}
VotingPluginUser pointUser = resolvePlaceholderUser(p);
UUID uuid = pointUser.getJavaUUID();
var generation = pointFence.generation(uuid);
try {
if (!pointFence.readable(uuid, generation)) {
if (pointFence.recoverable(uuid)) schedulePointRecovery(pointUser);
return "...";
}
if (com.bencodez.advancedcore.api.user.UserStorage.MYSQL.equals(plugin.getStorageType())) {
var snapshot = publishedPointSnapshot(pointUser);
if (snapshot == null) {
schedulePointRecovery(pointUser);
return "...";
}
// A complete row with invalid data is unavailable, not a missing snapshot to reload.
if (pointBalance(snapshot, pointUser.getPointsPath()) == null) return "...";
}
String value = getPlaceholderValueUnfenced(p, identifier, javascript, forceProcess, useCache);
return pointFence.readable(uuid, generation) ? value : "...";
} finally {
pointFence.release(uuid);
}
}
/**
* Snapshot-only point balance for direct API users on Bukkit/Folia threads.
* A pending/uncertain debit or incomplete publication is unavailable, not
* a genuine zero. This shares the same mutation fence as point placeholders.
*
* @param user the requested user
* @return a published point balance, or empty until it is safe to read
*/
public java.util.OptionalInt getPointBalanceIfReady(VotingPluginUser user) {
if (user == null || !plugin.isEnabled() || plugin.getPlaceholders() != this) {
return java.util.OptionalInt.empty();
}
UUID uuid = user.getJavaUUID();
var generation = pointFence.generation(uuid);
try {
if (!pointFence.readable(uuid, generation)) {
if (pointFence.recoverable(uuid)) schedulePointRecovery(user);
return java.util.OptionalInt.empty();
}
var snapshot = publishedPointSnapshot(user);
if (snapshot == null) {
schedulePointRecovery(user);
return java.util.OptionalInt.empty();
}
Integer amount = pointBalance(snapshot, user.getPointsPath());
if (amount == null || !pointFence.readable(uuid, generation)) {
return java.util.OptionalInt.empty();
}
return java.util.OptionalInt.of(amount);
} finally {
pointFence.release(uuid);
}
}
private java.util.Map<String, com.bencodez.simpleapi.sql.data.DataValue> publishedPointSnapshot(VotingPluginUser user) {
var cache = plugin.getUserManager().getDataManager().getUserDataCache().get(user.getJavaUUID());
return cache == null ? null : cache.snapshotIfPublished();
}
private Integer pointBalance(VotingPluginUser user) {
if (!com.bencodez.advancedcore.api.user.UserStorage.MYSQL.equals(plugin.getStorageType())) return user.getPoints();
return pointBalance(publishedPointSnapshot(user), user.getPointsPath());
}
private Integer pointBalance(java.util.Map<String, com.bencodez.simpleapi.sql.data.DataValue> snapshot, String column) {
if (snapshot == null) return null;
// AC publishes a complete row; absence has the historical integer default.
if (!snapshot.containsKey(column)) return 0;
var value = snapshot.get(column);
if (value == null) return null;
try {
if (value.isInt()) return value.getInt();
if (value.isString()) return Integer.valueOf(value.getString());
} catch (NumberFormatException malformed) {
return null;
}
return null;
}
private void schedulePointRecovery(VotingPluginUser user) {
schedulePlaceholderCheck(user);
}
private static boolean isPointIdentifier(String identifier) {
String key = identifier.toLowerCase(Locale.ROOT);
return key.equals("points") || key.equals("points_format") || key.startsWith("enoughpoints_");
}
private String getPlaceholderValueUnfenced(OfflinePlayer p, String identifier, boolean javascript, boolean forceProcess,
boolean useCache) {
if (plugin.getConfigFile().isUseJavascriptPlaceholders() && javascript && p != null) {
identifier = PlaceholderUtils.replaceJavascript(p, identifier);
@@ -304,12 +205,6 @@ public class PlaceHolders {
return "no player";
}
// These ranks use bounded snapshot projections; persistent result caches outlive presence evidence.
if (plugin.getConfigFile().isHideTopVoterIfNotPlayedBefore() && switch (identifier.toLowerCase(Locale.ROOT)) {
case "top_all_position", "top_month_position", "top_lastmonth_position", "top_week_position",
"top_daily_position" -> true;
default -> false;
}) useCache = false;
VotingPluginUser user = resolvePlaceholderUser(p);
if (useCache) {
if (!cachedPlaceholders.contains(identifier)) {
@@ -597,8 +492,7 @@ public class PlaceHolders {
@Override
public String placeholderRequest(VotingPluginUser user, String identifier) {
Integer points = pointBalance(user);
return points == null ? "..." : Integer.toString(points);
return Integer.toString(user.getPoints());
}
}.withDescription("User points").updateDataKey("Points"));
@@ -607,8 +501,7 @@ public class PlaceHolders {
@Override
public String placeholderRequest(VotingPluginUser user, String identifier) {
NumberFormat numberFormat = NumberFormat.getNumberInstance(Locale.US);
Integer points = pointBalance(user);
return points == null ? "..." : numberFormat.format(points);
return numberFormat.format(user.getPoints());
}
}.withDescription("User points").updateDataKey("Points"));
@@ -716,7 +609,7 @@ public class PlaceHolders {
public String placeholderRequest(VotingPluginUser user, String identifier) {
int num = 1;
UUID toMatch = UUID.fromString(user.getUUID());
for (Entry<TopVoterPlayer, Integer> entry : plugin.getTopVoterDisplay(TopVoter.AllTime).entrySet()) {
for (Entry<TopVoterPlayer, Integer> entry : plugin.getTopVoter(TopVoter.AllTime).entrySet()) {
if (entry.getKey().getUuid().equals(toMatch)) {
return "" + num;
}
@@ -734,9 +627,7 @@ public class PlaceHolders {
return "invalid";
}
int number = Integer.parseInt(identifier.split("_")[1]);
Integer points = pointBalance(user);
if (points == null) return "...";
if (points >= number) {
if (user.getPoints() >= number) {
return "true";
}
return "false";
@@ -814,7 +705,7 @@ public class PlaceHolders {
public String placeholderRequest(String identifier) {
int num = 1;
int number = Integer.parseInt(identifier.split("_")[2]);
for (Entry<TopVoterPlayer, Integer> entry : plugin.getTopVoterDisplay(TopVoter.AllTime).entrySet()) {
for (Entry<TopVoterPlayer, Integer> entry : plugin.getTopVoter(TopVoter.AllTime).entrySet()) {
if (num == number) {
return "" + entry.getValue().intValue();
}
@@ -833,7 +724,7 @@ public class PlaceHolders {
}
int num = 1;
int number = Integer.parseInt(identifier.split("_")[2]);
for (Entry<TopVoterPlayer, Integer> entry : plugin.getTopVoterDisplay(TopVoter.AllTime).entrySet()) {
for (Entry<TopVoterPlayer, Integer> entry : plugin.getTopVoter(TopVoter.AllTime).entrySet()) {
if (num == number) {
return entry.getKey().getPlayerName();
}
@@ -849,7 +740,7 @@ public class PlaceHolders {
public String placeholderRequest(VotingPluginUser user, String identifier) {
int num = 1;
UUID toMatch = UUID.fromString(user.getUUID());
for (Entry<TopVoterPlayer, Integer> entry : plugin.getTopVoterDisplay(TopVoter.Monthly).entrySet()) {
for (Entry<TopVoterPlayer, Integer> entry : plugin.getTopVoter(TopVoter.Monthly).entrySet()) {
if (entry.getKey().getUuid().equals(toMatch)) {
return "" + num;
}
@@ -866,7 +757,7 @@ public class PlaceHolders {
public String placeholderRequest(VotingPluginUser user, String identifier) {
int num = 1;
UUID toMatch = UUID.fromString(user.getUUID());
for (Entry<TopVoterPlayer, Integer> entry : plugin.getLastMonthTopVoterDisplay().entrySet()) {
for (Entry<TopVoterPlayer, Integer> entry : plugin.getLastMonthTopVoter().entrySet()) {
if (entry.getKey().getUuid().equals(toMatch)) {
return "" + num;
}
@@ -884,7 +775,7 @@ public class PlaceHolders {
}
int num = 1;
int number = Integer.parseInt(identifier.split("_")[2]);
for (Entry<TopVoterPlayer, Integer> entry : plugin.getLastMonthTopVoterDisplay().entrySet()) {
for (Entry<TopVoterPlayer, Integer> entry : plugin.getLastMonthTopVoter().entrySet()) {
if (num == number) {
return entry.getKey().getPlayerName();
}
@@ -900,7 +791,7 @@ public class PlaceHolders {
public String placeholderRequest(String identifier) {
int num = 1;
int number = Integer.parseInt(identifier.split("_")[2]);
for (Entry<TopVoterPlayer, Integer> entry : plugin.getLastMonthTopVoterDisplay().entrySet()) {
for (Entry<TopVoterPlayer, Integer> entry : plugin.getLastMonthTopVoter().entrySet()) {
if (num == number) {
return "" + entry.getValue().intValue();
}
@@ -921,7 +812,7 @@ public class PlaceHolders {
}
int num = 1;
int number = Integer.parseInt(identifier.split("_")[2]);
for (Entry<TopVoterPlayer, Integer> entry : plugin.getTopVoterDisplay(TopVoter.Monthly).entrySet()) {
for (Entry<TopVoterPlayer, Integer> entry : plugin.getTopVoter(TopVoter.Monthly).entrySet()) {
if (num == number) {
return entry.getKey().getPlayerName();
}
@@ -937,7 +828,7 @@ public class PlaceHolders {
public String placeholderRequest(String identifier) {
int num = 1;
int number = Integer.parseInt(identifier.split("_")[2]);
for (Entry<TopVoterPlayer, Integer> entry : plugin.getTopVoterDisplay(TopVoter.Monthly).entrySet()) {
for (Entry<TopVoterPlayer, Integer> entry : plugin.getTopVoter(TopVoter.Monthly).entrySet()) {
if (num == number) {
return "" + entry.getValue().intValue();
}
@@ -953,7 +844,7 @@ public class PlaceHolders {
public String placeholderRequest(VotingPluginUser user, String identifier) {
int num = 1;
UUID toMatch = UUID.fromString(user.getUUID());
for (Entry<TopVoterPlayer, Integer> entry : plugin.getTopVoterDisplay(TopVoter.Weekly).entrySet()) {
for (Entry<TopVoterPlayer, Integer> entry : plugin.getTopVoter(TopVoter.Weekly).entrySet()) {
if (entry.getKey().getUuid().equals(toMatch)) {
return "" + num;
}
@@ -972,7 +863,7 @@ public class PlaceHolders {
}
int num = 1;
int number = Integer.parseInt(identifier.split("_")[2]);
for (Entry<TopVoterPlayer, Integer> entry : plugin.getTopVoterDisplay(TopVoter.Weekly).entrySet()) {
for (Entry<TopVoterPlayer, Integer> entry : plugin.getTopVoter(TopVoter.Weekly).entrySet()) {
if (num == number) {
return entry.getKey().getPlayerName();
}
@@ -988,7 +879,7 @@ public class PlaceHolders {
public String placeholderRequest(String identifier) {
int num = 1;
int number = Integer.parseInt(identifier.split("_")[2]);
for (Entry<TopVoterPlayer, Integer> entry : plugin.getTopVoterDisplay(TopVoter.Weekly).entrySet()) {
for (Entry<TopVoterPlayer, Integer> entry : plugin.getTopVoter(TopVoter.Weekly).entrySet()) {
if (num == number) {
return "" + entry.getValue().intValue();
}
@@ -1004,7 +895,7 @@ public class PlaceHolders {
public String placeholderRequest(VotingPluginUser user, String identifier) {
int num = 1;
UUID toMatch = UUID.fromString(user.getUUID());
for (Entry<TopVoterPlayer, Integer> entry : plugin.getTopVoterDisplay(TopVoter.Daily).entrySet()) {
for (Entry<TopVoterPlayer, Integer> entry : plugin.getTopVoter(TopVoter.Daily).entrySet()) {
if (entry.getKey().getUuid().equals(toMatch)) {
return "" + num;
}
@@ -1023,7 +914,7 @@ public class PlaceHolders {
}
int num = 1;
int number = Integer.parseInt(identifier.split("_")[2]);
for (Entry<TopVoterPlayer, Integer> entry : plugin.getTopVoterDisplay(TopVoter.Daily).entrySet()) {
for (Entry<TopVoterPlayer, Integer> entry : plugin.getTopVoter(TopVoter.Daily).entrySet()) {
if (num == number) {
return entry.getKey().getPlayerName();
}
@@ -1047,7 +938,7 @@ public class PlaceHolders {
public String placeholderRequest(String identifier) {
int num = 1;
int number = Integer.parseInt(identifier.split("_")[2]);
for (Entry<TopVoterPlayer, Integer> entry : plugin.getTopVoterDisplay(TopVoter.Daily).entrySet()) {
for (Entry<TopVoterPlayer, Integer> entry : plugin.getTopVoter(TopVoter.Daily).entrySet()) {
if (num == number) {
return "" + entry.getValue().intValue();
}
@@ -1063,7 +954,7 @@ public class PlaceHolders {
@Override
public String placeholderRequest(String identifier) {
return Integer.toString(plugin.getServerData().getVotePartyDisplay().total());
return Integer.toString(plugin.getVoteParty().getTotalVotes());
}
}.withDescription("Current amount of voteparty votes"));
@@ -1071,8 +962,7 @@ public class PlaceHolders {
@Override
public String placeholderRequest(String identifier) {
return Integer.toString(plugin.getServerData().getVotePartyDisplay()
.needed(plugin.getSpecialRewardsConfig().getVotePartyVotesRequired()));
return Integer.toString(plugin.getVoteParty().getNeededVotes());
}
}.withDescription("Voteparty votes needed"));
@@ -1080,8 +970,7 @@ public class PlaceHolders {
@Override
public String placeholderRequest(String identifier) {
return Integer.toString(plugin.getServerData().getVotePartyDisplay()
.required(plugin.getSpecialRewardsConfig().getVotePartyVotesRequired()));
return Integer.toString(plugin.getVoteParty().getVotesRequired());
}
}.withDescription("Amount of votes needed for voteparty"));
@@ -1518,13 +1407,6 @@ public class PlaceHolders {
@SuppressWarnings("unchecked")
private void updateCachedPlaceholder(PlaceHolder<VotingPluginUser> placeholder, VotingPluginUser user,
UUID uuid, String... keys) {
var pointGeneration = pointFence.generation(uuid);
try {
if ("Points".equalsIgnoreCase(placeholder.getUpdateDataKey())
&& !pointFence.readable(uuid, pointGeneration)) {
if (pointFence.recoverable(uuid)) schedulePointRecovery(user);
return;
}
for (String ident : Set.copyOf(placeholder.getCache().keySet())) {
ConcurrentHashMap<UUID, String> values = placeholder.getCache().get(ident);
if (values == null) continue;
@@ -1545,11 +1427,7 @@ public class PlaceHolders {
}
} else {
String value = placeholder.placeholderRequest(user, ident);
if ("Points".equalsIgnoreCase(placeholder.getUpdateDataKey())) {
pointFence.publish(uuid, pointGeneration, () -> {
if (plugin.isEnabled()) values.put(uuid, value);
});
} else values.put(uuid, value);
values.put(uuid, value);
if (getCacheLevel().onlineOnly() && !plugin.getPlaceholderPlayerPresence().isOnline(uuid)) {
values.remove(uuid);
continue;
@@ -1558,9 +1436,6 @@ public class PlaceHolders {
+ matchingKey(placeholder, keys) + " with " + value);
}
}
} finally {
pointFence.release(uuid);
}
}
private void publishCachedValue(PlaceHolder<VotingPluginUser> placeholder, VotingPluginUser user, UUID uuid,
@@ -1585,52 +1460,6 @@ public class PlaceHolders {
return placeholder.getUpdateDataKey();
}
/** Blocks stale point results before a shared debit enters its worker. */
public void beginSharedPointDebit(UUID uuid) {
pointFence.begin(uuid, () -> clearPointResults(uuid));
}
/** Owns a queued batch without replacing its worker's mutation outcome. */
public java.util.function.Consumer<Boolean> sharedPointAdmissionCompletion(UUID uuid) {
beginSharedPointDebit(uuid);
var completed = new java.util.concurrent.atomic.AtomicBoolean();
return settled -> {
if (completed.compareAndSet(false, true)) pointFence.finishAdmission(uuid,
settled && plugin.isEnabled() && plugin.getPlaceholders() == this);
};
}
private void clearPointResults(UUID uuid) {
for (PlaceHolder<VotingPluginUser> placeholder : userDataChangeClassification.all()) {
if ("Points".equalsIgnoreCase(placeholder.getUpdateDataKey()) && placeholder.isUsesCache()) {
placeholder.clearCachePlayer(uuid);
}
}
}
/** Completes the fence only after the storage worker has reconciled its snapshot. */
public void finishSharedPointDebit(UUID uuid, boolean trustworthySnapshot) {
finishSharedPointDebit(uuid, trustworthySnapshot, trustworthySnapshot);
}
public void finishSharedPointDebit(UUID uuid, boolean knownOutcome, boolean trustworthySnapshot) {
pointFence.finish(uuid, knownOutcome, trustworthySnapshot);
}
/** Captures a worker refill generation without granting permission to retry a mutation. */
public java.util.function.Consumer<Boolean> sharedPointRefillCompletion(UUID uuid) {
var stamp = pointFence.beginRefill(uuid, () -> clearPointResults(uuid));
var completed = new java.util.concurrent.atomic.AtomicBoolean();
return verified -> {
if (!completed.compareAndSet(false, true)) return;
try {
pointFence.finishRefill(uuid, stamp, verified && plugin.isEnabled() && plugin.getPlaceholders() == this);
} finally {
pointFence.release(uuid);
}
};
}
/**
* Handle player logout.
* @param user the voting plugin user
@@ -1676,12 +1505,11 @@ public class PlaceHolders {
/**
* Update placeholders for specific user.
* @param user the voting plugin user
* @param login whether to include uncached entries, such as a login or worker warmup
* @param login whether this is a login update
*/
public void onUpdate(VotingPluginUser user, boolean login) {
if (user == null) return;
UUID uuid = user.getJavaUUID();
if (pointFence.recoverable(uuid)) schedulePointRecovery(user);
Player owner = plugin.getPlaceholderPlayerPresence().schedulerOwner(uuid);
PlaceholderClassification classification = userDataChangeClassification;
List<PlaceHolder<VotingPluginUser>> platformUpdates = new ArrayList<>();
@@ -1723,8 +1551,6 @@ public class PlaceHolders {
* Reload placeholders.
*/
public void reload() {
pointFence.invalidateLifecycle();
pointRecoveryWorkers.clear();
platformUpdateGenerations.clear();
plugin.refreshPlaceholderPlayerPresence();
cacheLevel = plugin.getConfigFile().getPlaceholderCacheLevel();
@@ -1758,47 +1584,14 @@ public class PlaceHolders {
* Schedule placeholder check for user.
* @param user the voting plugin user
*/
public void schedulePlaceholderCheck(VotingPluginUser user) {
if (!plugin.isEnabled() || plugin.getPlaceholders() != this) return;
UUID uuid = user.getJavaUUID();
Object token = new Object();
long lifecycle = pointFence.lifecycle();
// Common warming and direct point recovery share queued and executing admission.
if (pointRecoveryWorkers.putIfAbsent(uuid, token) != null) return;
try {
plugin.getTimer().execute(() -> {
boolean warmed = false;
try {
if (!plugin.isEnabled() || plugin.getPlaceholders() != this || lifecycle != pointFence.lifecycle()) return;
var observed = pointFence.generation(uuid);
try {
// Invalid data in a complete published row is not a missing snapshot.
// Pending/unknown writes cannot authorize a competing point refill.
if (pointFence.recoverable(uuid)
|| (pointFence.readable(uuid, observed)
&& com.bencodez.advancedcore.api.user.UserStorage.MYSQL.equals(plugin.getStorageType())
&& publishedPointSnapshot(user) == null)) {
com.bencodez.votingplugin.user.SharedMysqlCacheReconciler.invalidateAndRefreshOnWorker(
plugin, user.getUUID(), user.getPointsPath());
}
} finally { pointFence.release(uuid); }
if (!plugin.isEnabled() || plugin.getPlaceholders() != this || lifecycle != pointFence.lifecycle()) return;
checkNonCachedPlaceholders();
// Preserve each cache level's existing offline-entry admission policy.
onUpdate(user, !getCacheLevel().onlineOnly() || plugin.getPlaceholderPlayerPresence().isOnline(uuid));
warmed = true;
} finally {
boolean retired = pointRecoveryWorkers.remove(uuid, token);
// A new identifier may have arrived after this worker's discovery pass.
if (retired && warmed && !placeholdersToSetCacheOn.isEmpty() && plugin.isEnabled()
&& plugin.getPlaceholders() == this && lifecycle == pointFence.lifecycle()) {
schedulePlaceholderCheck(user);
}
}
});
} catch (RuntimeException rejected) {
pointRecoveryWorkers.remove(uuid, token);
plugin.debug(rejected);
}
}
public void schedulePlaceholderCheck(VotingPluginUser user) {
plugin.getTimer().execute(new Runnable() {
@Override
public void run() {
checkNonCachedPlaceholders();
onUpdate(user, plugin.getPlaceholderPlayerPresence().isOnline(user.getJavaUUID()));
}
});
}
}
@@ -7,8 +7,6 @@ import java.util.Map;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Supplier;
import org.bukkit.entity.Player;
@@ -21,97 +19,6 @@ import org.bukkit.entity.Player;
public final class PlaceholderPlayerPresence {
private final AtomicReference<Map<UUID, Player>> onlinePlayers = new AtomicReference<>(Map.of());
private final Object lifecycleLock = new Object();
private final Map<Player, LiveIdentity> identities = new IdentityHashMap<>();
private final Map<Player, Object> refreshReservations = new IdentityHashMap<>();
/** Immutable identity; lookup callers never need to access its Bukkit owner. */
public record LiveIdentity(UUID serverUuid, String playerName, UUID storageUuid) { }
/** Capture only on this player's owning thread (join or entity scheduler). */
public void captureOnline(UUID storageUuid, Player player) {
if (storageUuid == null || player == null) return;
LiveIdentity identity = new LiveIdentity(player.getUniqueId(), player.getName(), storageUuid);
synchronized (lifecycleLock) {
playerOnline(storageUuid, player);
identities.put(player, identity);
}
}
/** Rekey only the current owner. Delayed login cannot resurrect a retired session. */
public boolean updateStorageUuid(UUID uuid, Player player) {
if (uuid == null || player == null) return false;
synchronized (lifecycleLock) {
if (storageUuid(player) == null) return false;
Player currentOwner = onlinePlayers.get().get(uuid);
if (currentOwner != null && currentOwner != player) return false;
LiveIdentity identity = identities.get(player);
playerOnline(uuid, player);
if (identity != null) identities.put(player,
new LiveIdentity(identity.serverUuid(), identity.playerName(), uuid));
return true;
}
}
/** Snapshot-only lookup, with exact storage identities taking precedence over aliases. */
public LiveIdentity liveIdentity(UUID uuid) {
if (uuid == null) return null;
synchronized (lifecycleLock) {
Player exact = onlinePlayers.get().get(uuid);
if (exact != null) return identities.get(exact);
LiveIdentity found = null;
for (LiveIdentity identity : identities.values()) {
if (!uuid.equals(identity.serverUuid())) continue;
if (found != null) return null; // Uncertain or ambiguous: preserve the supplied UUID.
found = identity;
}
return found;
}
}
/**
* Refresh membership without reading another region's players. Each scheduled
* capture is fenced by its reservation; quit, join, another refresh and clear
* invalidate it before it can publish stale identity data. The capture consumer
* must run on that player's owning thread.
*/
public void refresh(Supplier<? extends Collection<? extends Player>> playersSupplier,
BiConsumer<Player, Consumer<UUID>> scheduleCapture) {
Map<Player, Object> reservations = new IdentityHashMap<>();
synchronized (lifecycleLock) {
Collection<? extends Player> players = playersSupplier.get();
Map<Player, Boolean> members = new IdentityHashMap<>();
if (players != null) for (Player player : players) {
if (player != null) members.put(player, Boolean.TRUE);
}
Map<UUID, Player> retained = new HashMap<>(onlinePlayers.get());
retained.entrySet().removeIf(entry -> !members.containsKey(entry.getValue()));
onlinePlayers.set(Map.copyOf(retained));
retainCurrentIdentities();
refreshReservations.clear();
members.keySet().forEach(player -> {
Object reservation = new Object();
refreshReservations.put(player, reservation);
reservations.put(player, reservation);
});
}
reservations.forEach((player, reservation) -> scheduleCapture.accept(player, storageUuid -> {
synchronized (lifecycleLock) {
if (refreshReservations.get(player) != reservation) return;
refreshReservations.remove(player);
if (storageUuid == null || !player.isOnline()) return;
Player currentOwner = onlinePlayers.get().get(storageUuid);
if (currentOwner != null && currentOwner != player) return;
UUID serverUuid = player.getUniqueId();
if (identities.entrySet().stream().anyMatch(entry -> entry.getKey() != player
&& serverUuid.equals(entry.getValue().serverUuid()))) return;
captureOnline(storageUuid, player);
}
}));
}
private void retainCurrentIdentities() {
identities.entrySet().removeIf(entry -> onlinePlayers.get().get(entry.getValue().storageUuid()) != entry.getKey());
}
public boolean isOnline(UUID uuid) {
return uuid != null && onlinePlayers.get().containsKey(uuid);
@@ -139,31 +46,24 @@ public final class PlaceholderPlayerPresence {
public void playerOnline(UUID uuid, Player player) {
if (uuid == null || player == null) return;
synchronized (lifecycleLock) {
refreshReservations.remove(player);
Player displacedOwner = onlinePlayers.get().get(uuid);
if (displacedOwner != null && displacedOwner != player) refreshReservations.remove(displacedOwner);
update(current -> {
Map<UUID, Player> next = new HashMap<>(current);
next.entrySet().removeIf(entry -> entry.getValue() == player && !entry.getKey().equals(uuid));
next.put(uuid, player);
return Map.copyOf(next);
});
retainCurrentIdentities();
}
}
public void playerOffline(UUID uuid) {
if (uuid == null) return;
synchronized (lifecycleLock) {
Player owner = onlinePlayers.get().get(uuid);
if (owner != null) refreshReservations.remove(owner);
update(current -> {
if (!current.containsKey(uuid)) return current;
Map<UUID, Player> next = new HashMap<>(current);
next.remove(uuid);
return Map.copyOf(next);
});
retainCurrentIdentities();
}
}
@@ -171,13 +71,11 @@ public final class PlaceholderPlayerPresence {
public boolean playerOffline(UUID uuid, Player expectedOwner) {
if (uuid == null || expectedOwner == null) return false;
synchronized (lifecycleLock) {
refreshReservations.remove(expectedOwner);
Map<UUID, Player> current = onlinePlayers.get();
if (current.get(uuid) != expectedOwner) return false;
Map<UUID, Player> next = new HashMap<>(current);
next.remove(uuid);
onlinePlayers.set(Map.copyOf(next));
retainCurrentIdentities();
return true;
}
}
@@ -215,8 +113,6 @@ public final class PlaceholderPlayerPresence {
}
}
onlinePlayers.set(Map.copyOf(next));
refreshReservations.clear();
retainCurrentIdentities();
}
}
@@ -226,11 +122,11 @@ public final class PlaceholderPlayerPresence {
if (players != null) players.forEach((uuid, player) -> {
if (uuid != null && player != null) next.put(uuid, player);
});
synchronized (lifecycleLock) { onlinePlayers.set(Map.copyOf(next)); refreshReservations.clear(); retainCurrentIdentities(); }
synchronized (lifecycleLock) { onlinePlayers.set(Map.copyOf(next)); }
}
public void clear() {
synchronized (lifecycleLock) { onlinePlayers.set(Map.of()); identities.clear(); refreshReservations.clear(); }
synchronized (lifecycleLock) { onlinePlayers.set(Map.of()); }
}
/** Publish an offline-only result atomically with player lifecycle capture. */
@@ -1,107 +0,0 @@
package com.bencodez.votingplugin.placeholders;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
/** Coordinates point rendering with in-flight shared-storage mutations. */
final class PointPlaceholderFence {
private static final class State {
long generation;
int pending;
int readers;
int refills;
boolean uncertain;
boolean snapshotUnavailable;
}
private final Map<UUID, State> states = new HashMap<>();
private long generation;
private long lifecycle;
record Stamp(long lifecycle, long generation) { }
synchronized Stamp generation(UUID uuid) {
State state = states.computeIfAbsent(uuid, ignored -> {
State created = new State();
created.generation = ++generation;
return created;
});
state.readers++;
return new Stamp(lifecycle, state.generation);
}
synchronized boolean readable(UUID uuid, Stamp observed) {
if (lifecycle != observed.lifecycle()) return false;
State state = states.get(uuid);
return state != null && state.generation == observed.generation()
&& state.pending == 0 && state.refills == 0 && !state.uncertain && !state.snapshotUnavailable;
}
synchronized void release(UUID uuid) {
State state = states.get(uuid);
if (state == null || state.readers == 0) throw new IllegalStateException("Unbalanced point reader");
state.readers--;
retireIfSafe(uuid, state);
}
private void retireIfSafe(UUID uuid, State state) {
if (state.readers == 0 && state.pending == 0 && state.refills == 0 && !state.uncertain && !state.snapshotUnavailable) states.remove(uuid);
}
synchronized void invalidateLifecycle() { lifecycle++; }
synchronized long lifecycle() { return lifecycle; }
synchronized boolean recoverable(UUID uuid) {
State state = states.get(uuid);
return state != null && state.snapshotUnavailable && !state.uncertain && state.pending == 0 && state.refills == 0;
}
synchronized Stamp beginRefill(UUID uuid, Runnable invalidate) {
State state = states.computeIfAbsent(uuid, ignored -> new State());
state.generation = ++generation;
state.snapshotUnavailable = true;
state.refills++;
state.readers++;
invalidate.run();
return new Stamp(lifecycle, state.generation);
}
synchronized void begin(UUID uuid, Runnable invalidate) {
State state = states.computeIfAbsent(uuid, ignored -> new State());
state.generation = ++generation;
state.pending++;
invalidate.run();
}
synchronized void finish(UUID uuid, boolean knownOutcome, boolean trustworthy) {
State state = states.get(uuid);
if (state == null || state.pending == 0) throw new IllegalStateException("Unbalanced point mutation");
state.uncertain |= !knownOutcome;
state.snapshotUnavailable = !trustworthy || state.refills != 0;
state.pending--;
state.generation = ++generation;
retireIfSafe(uuid, state);
}
synchronized void finishAdmission(UUID uuid, boolean workerSettled) {
State state = states.get(uuid);
if (state == null || state.pending == 0) throw new IllegalStateException("Unbalanced point admission");
state.pending--;
state.snapshotUnavailable |= !workerSettled;
state.generation = ++generation;
retireIfSafe(uuid, state);
}
synchronized void finishRefill(UUID uuid, Stamp observed, boolean verified) {
State state = states.get(uuid);
if (state == null || state.refills == 0) throw new IllegalStateException("Unbalanced point refill");
boolean current = lifecycle == observed.lifecycle() && state.generation == observed.generation();
state.refills--;
state.snapshotUnavailable = !(verified && current && state.pending == 0 && state.refills == 0 && !state.uncertain);
// Even an obsolete read completion can replace storage data: retire every older render.
state.generation = ++generation;
}
synchronized void publish(UUID uuid, Stamp observed, Runnable publication) {
if (readable(uuid, observed)) publication.run();
}
}
@@ -123,7 +123,8 @@ public class ServiceSiteHandler {
public void saveToServerData() {
List<String> out = toListFormat(sitesRef.get());
plugin.getServerData().setStringList(SERVERDATA_PATH, out);
plugin.getServerData().getData().set(SERVERDATA_PATH, out);
plugin.getServerData().saveData();
}
public void refreshFromWebOnce(boolean logMore) {
@@ -12,6 +12,7 @@ import org.bukkit.block.Skull;
import org.bukkit.block.data.Directional;
import org.bukkit.inventory.meta.SkullMeta;
import com.bencodez.advancedcore.api.misc.MiscUtils;
import com.bencodez.simpleapi.array.ArrayUtils;
import com.bencodez.votingplugin.VotingPluginMain;
import com.bencodez.votingplugin.topvoter.TopVoter;
@@ -24,14 +25,14 @@ public class SignHandler {
@Getter
@Setter
private volatile String data;
private String data;
/** The lines. */
private ArrayList<String> lines;
@Getter
@Setter
private volatile Location location;
private Location location;
private String playerName;
@@ -47,7 +48,7 @@ public class SignHandler {
@Getter
@Setter
private volatile Location skullLocation;
private Location skullLocation;
@Getter
@Setter
@@ -55,88 +56,6 @@ public class SignHandler {
private int votes;
private record Render(ArrayList<String> lines, String name, UUID identity, int votes) { }
private record DisplayUpdate(long generation, Location location, String data) { }
private DisplayUpdate preparing;
private long skullSequence;
private static final int MAX_DISCOVERED_SKULLS = 28;
private final java.util.Set<Location> displayedSkulls = new java.util.LinkedHashSet<>();
private SkullFrame lastSkullFrame;
private record SkullFrame(long sequence, long generation, Location origin, Location selected, String data,
String name, UUID identity) { }
private synchronized SkullFrame skullFrame(String name, UUID identity) {
var frame = new SkullFrame(++skullSequence, plugin.getTopVoterDisplayGeneration(), location.clone(),
skullLocation == null ? null : skullLocation.clone(), data, name, identity);
if (lastSkullFrame == null || lastSkullFrame.generation() != frame.generation()
|| !java.util.Objects.equals(lastSkullFrame.origin(), frame.origin())
|| !java.util.Objects.equals(lastSkullFrame.selected(), frame.selected())
|| !java.util.Objects.equals(lastSkullFrame.data(), frame.data())) displayedSkulls.clear();
lastSkullFrame = frame;
return frame;
}
/** Remember successful automatic publications, never arbitrary neighboring skulls. */
private synchronized void rememberSkull(SkullFrame frame, Location target) {
if (lastSkullFrame == frame && frame.selected() == null && displayedSkulls.size() < MAX_DISCOVERED_SKULLS)
displayedSkulls.add(target.clone());
}
private synchronized void forgetSkull(SkullFrame frame, Location target) {
if (lastSkullFrame == frame) displayedSkulls.remove(target);
}
private synchronized boolean assignedSkull(SkullFrame frame, Location target) {
return lastSkullFrame == frame && (java.util.Objects.equals(frame.selected(), target)
|| displayedSkulls.contains(target));
}
private synchronized ArrayList<Location> assignedSkulls(SkullFrame frame) {
if (lastSkullFrame != frame) return new ArrayList<>();
return new ArrayList<>(frame.selected() == null ? displayedSkulls : java.util.List.of(frame.selected()));
}
private boolean current(SkullFrame frame) {
if (!plugin.isEnabled() || plugin.getTopVoterDisplayGeneration() != frame.generation()) return false;
synchronized (this) {
return skullSequence == frame.sequence() && java.util.Objects.equals(location, frame.origin())
&& java.util.Objects.equals(skullLocation, frame.selected())
&& java.util.Objects.equals(data, frame.data());
}
}
/** Only coordinates cross regions; every block access occurs inside its own location task. */
private void onOwner(SkullFrame frame, Location target, Runnable action) {
try {
plugin.getBukkitScheduler().runTask(plugin, () -> {
if (current(frame)) action.run();
}, target);
} catch (RuntimeException rejected) { plugin.debug("Unable to schedule skull display"); }
}
private void updateSkull(SkullFrame frame, Location target, Runnable absent) {
onOwner(frame, target, () -> {
Block block = target.getBlock();
if (!(block.getState() instanceof Skull)) {
forgetSkull(frame, target);
if (absent != null) absent.run();
return;
}
String name = frame.name(); UUID identity = frame.identity();
// Queued region work may outlive the evidence used by the sign render.
TopVoter period = displayPeriod();
if (period != null && position > 0 && plugin.getConfigFile().isHideTopVoterIfNotPlayedBefore()) {
var rows = new ArrayList<>(plugin.getTopVoterDisplay(period).keySet());
if (rows.size() >= position) {
name = rows.get(position - 1).getPlayerName(); identity = rows.get(position - 1).getUuid();
} else { name = "No Player"; identity = null; }
}
if (!current(frame)) return;
if (!checkSkull(block, target, name, identity, frame) && absent != null) absent.run();
});
}
/**
* Constructs a new SignHandler.
*
@@ -162,28 +81,19 @@ public class SignHandler {
}
@SuppressWarnings("deprecation")
private boolean checkSkull(Block block, Location target, String name, UUID identity, SkullFrame frame) {
if (block.getState() instanceof Skull skull) {
if (name.isEmpty() || name.equalsIgnoreCase("No Player")) {
if (plugin.getConfigFile().isHideTopVoterIfNotPlayedBefore()) {
if (!current(frame) || !assignedSkull(frame, target)) return true;
skull.setOwnerProfile(null);
if (current(frame) && skull.update(true, false)) forgetSkull(frame, target);
}
return true;
}
if (!name.equals("No Player")) {
private boolean checkSkull(Block block) {
if (block.getState() instanceof Skull) {
if (!playerName.equals("No Player")) {
Skull skull = (Skull) block.getState();
try {
SkullMeta meta = (SkullMeta) plugin.getSkullCacheHandler().getSkull(identity, name).getItemMeta();
var profile = java.util.Objects.requireNonNull(meta.getOwnerProfile(), "Skull profile unavailable");
if (!current(frame)) return true;
skull.setOwnerProfile(profile);
if (current(frame) && skull.update(true, false)) rememberSkull(frame, target);
SkullMeta meta = (SkullMeta) plugin.getSkullCacheHandler().getSkull(uuid, playerName).getItemMeta();
skull.setOwnerProfile(meta.getOwnerProfile());
skull.update(true, false);
} catch (Exception e) {
plugin.debug("Failed to set skull for " + name);
plugin.debug("Failed to set skull for " + playerName);
plugin.debug(e);
if (!current(frame)) return true;
if (skull.setOwner(name) && current(frame) && skull.update(true, false)) rememberSkull(frame, target);
skull.setOwner(playerName);
skull.update(true, false);
}
}
@@ -196,24 +106,18 @@ public class SignHandler {
* Check skulls.
*/
public void checkSkulls() {
Render rendered = currentRender();
checkSkulls(rendered.name(), rendered.identity());
}
if (noNameAvailable()) {
return;
}
if (skullLocation != null) {
checkSkull(skullLocation.getBlock());
return;
}
private void checkSkulls(String name, UUID identity) {
if ((name.equalsIgnoreCase("No Player") || name.isEmpty())
&& !plugin.getConfigFile().isHideTopVoterIfNotPlayedBefore()) {
return;
}
SkullFrame frame = skullFrame(name, identity);
if (frame.selected() != null) {
updateSkull(frame, frame.selected(), null);
return;
}
Location loc = frame.origin();
Location loc = location;
Location loc1 = new Location(loc.getWorld(), loc.getBlockX() - 1, loc.getBlockY() - 1, loc.getBlockZ() - 1);
Location loc2 = new Location(loc.getWorld(), loc.getBlockX() + 1, loc.getBlockY() + 1, loc.getBlockZ() + 1);
updateSkulls(loc1, loc2, frame);
updateSkulls(loc1, loc2);
}
/**
@@ -286,12 +190,6 @@ public class SignHandler {
/**
* Store sign.
*/
/** Capture platform state on the caller before shutdown transfers publication ownership. */
public com.bencodez.votingplugin.data.ServerData.SignSnapshot captureShutdownSnapshot() {
return com.bencodez.votingplugin.data.ServerData.captureSignSnapshot(
sign, location, skullLocation, data, position);
}
public void storeSign() {
plugin.getServerData().setSign(sign, location, skullLocation, data, position);
}
@@ -300,131 +198,95 @@ public class SignHandler {
* Update lines.
*/
public void updateLines() {
Render rendered = renderLines();
synchronized (this) { applyRender(rendered); }
}
private TopVoter displayPeriod() {
if ("all".equalsIgnoreCase(data)) return TopVoter.AllTime;
if ("monthly".equalsIgnoreCase(data)) return TopVoter.Monthly;
if ("weekly".equalsIgnoreCase(data)) return TopVoter.Weekly;
if ("daily".equalsIgnoreCase(data)) return TopVoter.Daily;
return null;
}
private Render renderLines() {
var rendered = new ArrayList<String>();
lines = new ArrayList<>();
checkValidSign();
if (position == 0) {
synchronized (this) { return new Render(rendered, playerName, uuid, votes); }
}
rendered.add(plugin.getConfigFile().getFormatSignTopVoterSignLine1());
rendered.add(plugin.getConfigFile().getFormatSignTopVoterSignLine2());
rendered.add(plugin.getConfigFile().getFormatSignTopVoterSignLine3());
rendered.add(plugin.getConfigFile().getFormatSignTopVoterSignLine4());
TopVoter period = displayPeriod();
java.util.Map<TopVoterPlayer, Integer> board = period == null ? java.util.Map.of()
: plugin.getTopVoterDisplay(period);
var users = new ArrayList<>(board.keySet());
String name = "No Player";
UUID identity = null;
int amount = 0;
if (users.size() >= position) {
TopVoterPlayer row = users.get(position - 1);
name = row.getPlayerName(); identity = row.getUuid(); amount = board.get(row);
}
for (int index = 0; index < rendered.size(); index++) {
rendered.set(index, rendered.get(index).replace("%votes%", Integer.toString(amount))
.replace("%player%", name).replace("%SiteName%", data)
.replace("%position%", Integer.toString(position)));
}
return new Render(ArrayUtils.colorize(rendered), name, identity, amount);
}
if (position != 0) {
String line1 = plugin.getConfigFile().getFormatSignTopVoterSignLine1();
String line2 = plugin.getConfigFile().getFormatSignTopVoterSignLine2();
String line3 = plugin.getConfigFile().getFormatSignTopVoterSignLine3();
String line4 = plugin.getConfigFile().getFormatSignTopVoterSignLine4();
lines.add(line1);
lines.add(line2);
lines.add(line3);
lines.add(line4);
/** Called under this monitor; never call storage/provider APIs from this scope. */
private void applyRender(Render rendered) {
lines = rendered.lines(); playerName = rendered.name(); uuid = rendered.identity(); votes = rendered.votes();
}
private Render currentRender() {
synchronized (this) { return new Render(new ArrayList<>(lines), playerName, uuid, votes); }
}
/** Update the sign on its owning scheduler, waiting once for admitted presence evidence when enabled. */
public void updateSign(int delay) {
TopVoter period = displayPeriod();
if (position != 0 && period != null && plugin.getConfigFile() != null
&& plugin.getConfigFile().isHideTopVoterIfNotPlayedBefore()) {
prepareDisplay(period, delay);
return;
}
plugin.getBukkitScheduler().runTaskLater(plugin, () -> writeSign(currentRender(), getLocation()),
delay, getLocation());
}
private void prepareDisplay(TopVoter period, int delay) {
long generation = plugin.getTopVoterDisplayGeneration();
Location target = getLocation().clone();
DisplayUpdate update;
synchronized (this) {
if (preparing != null && preparing.generation() == generation
&& preparing.location().equals(target) && java.util.Objects.equals(preparing.data(), data)) return;
update = new DisplayUpdate(generation, target, data);
preparing = update;
}
try {
var ready = plugin.getTopVoterDisplayAsync(period);
if (ready == null) schedulePreparedDisplay(update, delay);
else ready.whenComplete((ignored, failure) -> schedulePreparedDisplay(update, delay));
} catch (RuntimeException unavailable) {
schedulePreparedDisplay(update, delay);
}
}
private boolean current(DisplayUpdate update) {
return plugin.isEnabled() && plugin.getTopVoterDisplayGeneration() == update.generation()
&& java.util.Objects.equals(update.location(), getLocation())
&& java.util.Objects.equals(update.data(), data);
}
private void schedulePreparedDisplay(DisplayUpdate update, int delay) {
synchronized (this) { if (preparing != update) return; }
try {
plugin.getBukkitScheduler().runTaskLater(plugin, () -> {
try {
synchronized (SignHandler.this) { if (preparing != update) return; }
if (!current(update)) return;
// Resolve current evidence outside the sign monitor. Completion may reenter from the SDK worker.
Render rendered = renderLines();
if (!current(update)) return;
synchronized (SignHandler.this) {
if (preparing != update) return;
applyRender(rendered);
}
writeSign(rendered, update.location());
} finally {
synchronized (SignHandler.this) { if (preparing == update) preparing = null; }
}
}, delay, update.location());
} catch (RuntimeException rejected) {
synchronized (this) { if (preparing == update) preparing = null; }
}
}
@SuppressWarnings("deprecation")
private void writeSign(Render rendered, Location target) {
try {
BlockState state = target.getBlock().getState();
if (state instanceof Sign signState) {
for (int index = 0; index < rendered.lines().size() && index < 4; index++)
signState.setLine(index, rendered.lines().get(index));
signState.update();
checkSkulls(rendered.name(), rendered.identity());
ArrayList<TopVoterPlayer> users = null;
if (data.equalsIgnoreCase("all")) {
users = new ArrayList<>(plugin.getTopVoter(TopVoter.AllTime).keySet());
} else if (data.equalsIgnoreCase("monthly")) {
users = new ArrayList<>(plugin.getTopVoter(TopVoter.Monthly).keySet());
} else if (data.equalsIgnoreCase("weekly")) {
users = new ArrayList<>(plugin.getTopVoter(TopVoter.Weekly).keySet());
} else if (data.equalsIgnoreCase("daily")) {
users = new ArrayList<>(plugin.getTopVoter(TopVoter.Daily).keySet());
}
} catch (Exception failure) {
plugin.debug("Failed to update sign display");
plugin.debug(failure);
if (users != null && users.size() >= position) {
TopVoterPlayer user = users.get(position - 1);
playerName = user.getPlayerName();
uuid = user.getUuid();
votes = 0;
if (data.equalsIgnoreCase("all")) {
votes = plugin.getTopVoter(TopVoter.AllTime).get(user);
} else if (data.equalsIgnoreCase("monthly")) {
votes = plugin.getTopVoter(TopVoter.Monthly).get(user);
} else if (data.equalsIgnoreCase("weekly")) {
votes = plugin.getTopVoter(TopVoter.Weekly).get(user);
} else if (data.equalsIgnoreCase("daily")) {
votes = plugin.getTopVoter(TopVoter.Daily).get(user);
}
for (int j = 0; j < lines.size(); j++) {
lines.set(j, lines.get(j).replace("%votes%", "" + votes).replace("%player%", playerName));
}
} else {
playerName = "No Player";
votes = 0;
for (int j = 0; j < lines.size(); j++) {
lines.set(j, lines.get(j).replace("%votes%", "" + votes).replace("%player%", playerName));
}
}
for (int j = 0; j < lines.size(); j++) {
lines.set(j, lines.get(j).replace("%SiteName%", data).replace("%position%", "" + position));
}
lines = ArrayUtils.colorize(lines);
}
}
/**
* Update sign.
*
* @param delay the delay
*/
public void updateSign(int delay) {
plugin.getBukkitScheduler().runTaskLater(plugin, new Runnable() {
@SuppressWarnings("deprecation")
@Override
public void run() {
try {
BlockState state = getLocation().getBlock().getState();
if (state instanceof Sign) {
Sign s = (Sign) state;
for (int j = 0; j < lines.size() && j < 4; j++) {
s.setLine(j, lines.get(j));
}
s.update();
checkSkulls();
}
} catch (Exception ex) {
plugin.debug("Failed to update sign at " + getLocation().toString());
VotingPluginMain.plugin.debug(ex);
}
}
}, delay, getLocation());
}
/**
@@ -434,38 +296,19 @@ public class SignHandler {
* @param loc2 the second location
*/
public void updateSkulls(Location loc1, Location loc2) {
Render rendered = currentRender();
updateSkulls(loc1, loc2, rendered.name(), rendered.identity());
}
BlockState state = getLocation().getBlock().getState();
if (state instanceof Sign && state.getBlockData() instanceof Directional) {
Directional s = (Directional) state.getBlockData();
Block b = location.getBlock().getRelative(s.getFacing());
Block above = b.getRelative(BlockFace.UP);
if (checkSkull(above)) {
return;
}
private void updateSkulls(Location loc1, Location loc2, String name, UUID identity) {
updateSkulls(loc1, loc2, skullFrame(name, identity));
}
private void updateSkulls(Location loc1, Location loc2, SkullFrame frame) {
if (frame.name().isEmpty() || frame.name().equalsIgnoreCase("No Player")) {
if (plugin.getConfigFile().isHideTopVoterIfNotPlayedBefore())
for (Location target : assignedSkulls(frame)) updateSkull(frame, target, null);
return;
}
Runnable nearby = () -> {
for (int x = Math.min(loc1.getBlockX(), loc2.getBlockX()); x <= Math.max(loc1.getBlockX(), loc2.getBlockX()); x++)
for (int y = Math.min(loc1.getBlockY(), loc2.getBlockY()); y <= Math.max(loc1.getBlockY(), loc2.getBlockY()); y++)
for (int z = Math.min(loc1.getBlockZ(), loc2.getBlockZ()); z <= Math.max(loc1.getBlockZ(), loc2.getBlockZ()); z++) {
if (!current(frame)) return;
updateSkull(frame, new Location(frame.origin().getWorld(), x, y, z), null);
}
};
onOwner(frame, frame.origin(), () -> {
BlockState state = frame.origin().getBlock().getState();
if (state instanceof Sign && state.getBlockData() instanceof Directional direction) {
BlockFace facing = direction.getFacing();
Location preferred = new Location(frame.origin().getWorld(),
frame.origin().getBlockX() + facing.getModX(),
frame.origin().getBlockY() + facing.getModY() + 1,
frame.origin().getBlockZ() + facing.getModZ());
updateSkull(frame, preferred, nearby);
} else nearby.run();
});
for (Block block : MiscUtils.getInstance().getRegionBlocks(location.getWorld(), loc1, loc2)) {
checkSkull(block);
}
}
}
@@ -64,69 +64,6 @@ public class Signs {
}
}
private final Object shutdownLock = new Object();
private ShutdownSigns shutdownSigns;
private java.util.concurrent.CompletableFuture<Void> shutdownAttempt;
private record ShutdownSigns(com.bencodez.votingplugin.data.ServerData data,
java.util.List<com.bencodez.votingplugin.data.ServerData.SignSnapshot> snapshot,
com.bencodez.votingplugin.util.ServerDataPublicationFence.Lease lease) { }
/** No YAML lock or disk wait on the lifecycle caller; failures retain the original payload. */
public java.util.concurrent.CompletionStage<Void> storeSignsForShutdown() {
synchronized (shutdownLock) {
if (shutdownAttempt != null && !shutdownAttempt.isCompletedExceptionally())
return shutdownAttempt.minimalCompletionStage();
if (shutdownSigns == null) {
var snapshot = new java.util.ArrayList<com.bencodez.votingplugin.data.ServerData.SignSnapshot>();
for (var sign : java.util.List.copyOf(getSigns())) snapshot.add(sign.captureShutdownSnapshot());
if (snapshot.isEmpty()) {
shutdownAttempt = java.util.concurrent.CompletableFuture.completedFuture(null);
return shutdownAttempt.minimalCompletionStage();
}
var data = java.util.Objects.requireNonNull(plugin.getServerData());
var fence = java.util.Objects.requireNonNull(plugin.getServerDataPublicationFence());
shutdownSigns = new ShutdownSigns(data, java.util.List.copyOf(snapshot), fence.acquire());
}
var publication = shutdownSigns;
var attempt = new java.util.concurrent.CompletableFuture<Void>();
shutdownAttempt = attempt;
try {
startShutdownWorker(() -> {
try {
java.util.Objects.requireNonNull(publication.data().publishShutdownSigns(publication.snapshot()))
.whenComplete((ignored, failure) -> finishShutdownSigns(publication, attempt, failure));
} catch (Throwable failure) { finishShutdownSigns(publication, attempt, failure); }
});
} catch (RuntimeException | Error failure) {
finishShutdownSigns(publication, attempt, failure);
throw failure;
}
return attempt.minimalCompletionStage();
}
}
private void finishShutdownSigns(ShutdownSigns publication,
java.util.concurrent.CompletableFuture<Void> attempt, Throwable failure) {
if (failure == null) {
try { publication.lease().close(); attempt.complete(null); }
catch (Throwable releaseFailure) { attempt.completeExceptionally(releaseFailure); }
} else {
// Neither rejected admission nor failed I/O proves durability or writer drain.
// Keep the same detached payload and lease for an explicit repeated-unload attempt.
try { plugin.getLogger().warning("Sign shutdown persistence failed; its payload remains owned. Recovery is not confirmed."); }
catch (RuntimeException | Error ignored) { }
attempt.completeExceptionally(failure);
}
}
/** Admission seam for deterministic rejection/cancellation tests. */
protected void startShutdownWorker(Runnable task) {
var worker = new Thread(task, "VotingPlugin-sign-shutdown");
worker.setDaemon(true);
worker.start();
}
/**
* Update signs.
*/
@@ -146,9 +146,8 @@ public class VoteParty implements Listener {
public void commandVoteParty(CommandSender sender) {
if (plugin.getSpecialRewardsConfig().isVotePartyEnabled()) {
ArrayList<String> msg = plugin.getConfigFile().getFormatCommandsVoteParty();
var display = plugin.getServerData().getVotePartyDisplay();
int votesRequired = display.required(plugin.getSpecialRewardsConfig().getVotePartyVotesRequired());
int votes = display.total();
int votesRequired = getVotesRequired();
int votes = getTotalVotes();
int neededVotes = votesRequired - votes;
HashMap<String, String> placeholders = new HashMap<>();
placeholders.put("votesrequired", "" + votesRequired);
@@ -120,7 +120,7 @@ public final class VotePartyRewardHandler {
return triggeringUser;
}
VotingPluginUser user = onlinePlayer == null
? plugin.getVotingPluginUserManager().getVotingPluginUser(uuid, true)
? plugin.getVotingPluginUserManager().getVotingPluginUser(uuid)
: plugin.getVotingPluginUserManager().getVotingPluginUser(onlinePlayer);
user.userDataFetechMode(UserDataFetchMode.NO_CACHE);
return user;
@@ -24,7 +24,8 @@ public final class VotePartyState {
}
public void setTotalVotes(int value) {
plugin.getServerData().setInt(TOTAL_PATH, value);
plugin.getServerData().getData().set(TOTAL_PATH, value);
plugin.getServerData().saveData();
}
public List<String> getVotedUsers() {
@@ -33,7 +34,8 @@ public final class VotePartyState {
}
public void setVotedUsers(List<String> users) {
plugin.getServerData().setStringList(VOTED_PATH, users);
plugin.getServerData().getData().set(VOTED_PATH, users);
plugin.getServerData().saveData();
}
public int getVotesRequired() {
@@ -40,7 +40,6 @@ public class VoteStreakHandler {
private final Map<String, VoteStreakDefinition> byId = new LinkedHashMap<>();
private final Map<String, VoteStreakDefinition> byProgressGroup = new LinkedHashMap<>();
private final List<VoteStreakDefinition> ordered = new ArrayList<>();
private volatile List<VoteStreakDefinition> displayDefinitions = List.of();
public VoteStreakHandler(VotingPluginMain plugin) {
this.plugin = plugin;
@@ -57,26 +56,6 @@ public class VoteStreakHandler {
// VoteStreak definitions live in specialrewards.yml now (Option B)
ConfigurationSection root = plugin.getSpecialRewardsConfig().getData();
new VoteStreakConfigLoader().load(root);
displayDefinitions = ordered.stream().filter(VoteStreakDefinition::isEnabled).toList();
}
/** Worker-only, observational view. Does not advance periods, save state or execute rewards. */
public com.bencodez.votingplugin.streaks.VoteStreaksSnapshot snapshotForDisplay(VotingPluginUser user) {
var definitions = displayDefinitions;
var periods = List.of(
new com.bencodez.votingplugin.streaks.VoteStreaksSnapshot.Period(VoteStreakType.DAILY, user.getDayVoteStreak(), user.getBestDayVoteStreak()),
new com.bencodez.votingplugin.streaks.VoteStreaksSnapshot.Period(VoteStreakType.WEEKLY, user.getWeekVoteStreak(), user.getBestWeekVoteStreak()),
new com.bencodez.votingplugin.streaks.VoteStreaksSnapshot.Period(VoteStreakType.MONTHLY, user.getMonthVoteStreak(), user.getBestMonthVoteStreak()));
var states = new LinkedHashMap<String, StreakState>();
var rows = new ArrayList<com.bencodez.votingplugin.streaks.VoteStreaksSnapshot.Milestone>();
for (var definition : definitions) {
if (rows.size() >= com.bencodez.votingplugin.streaks.VoteStreaksSnapshot.MAX_MILESTONES) break;
var state = states.computeIfAbsent(getColumnName(definition), ignored -> readState(user, definition));
String label = definition.getId().codePoints().limit(80).collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append).toString();
rows.add(new com.bencodez.votingplugin.streaks.VoteStreaksSnapshot.Milestone(label, definition.getType(), state.streakCount,
state.bestStreakCount, definition.getRequiredAmount(), definition.getVotesRequired(), definition.isRecurring()));
}
return new com.bencodez.votingplugin.streaks.VoteStreaksSnapshot(periods, rows, definitions.size() > rows.size());
}
public List<VoteStreakDefinition> getDefinitions() {
@@ -1,20 +0,0 @@
package com.bencodez.votingplugin.streaks;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.bencodez.advancedcore.api.command.CommandHandler;
import com.bencodez.votingplugin.VotingPluginMain;
public final class VoteStreaksCommand {
private VoteStreaksCommand() { }
public static void register(VotingPluginMain plugin) {
plugin.getVoteCommand().add(new CommandHandler(plugin, new String[] { "Streaks" },
VoteStreaksMenu.PERMISSION + "|VotingPlugin.Player", "View your vote streak progression", false) {
@Override public void execute(CommandSender sender, String[] args) {
if (sender instanceof Player player && plugin.getVoteStreaksMenu() != null) {
plugin.getVoteStreaksMenu().open(player);
}
}
});
}
}
@@ -1,277 +0,0 @@
package com.bencodez.votingplugin.streaks;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import java.util.function.BiFunction;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.event.inventory.InventoryDragEvent;
import org.bukkit.event.inventory.InventoryOpenEvent;
import org.bukkit.event.player.PlayerChangedWorldEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import com.bencodez.simpleapi.messages.MessageAPI;
import com.bencodez.votingplugin.VotingPluginMain;
import com.bencodez.votingplugin.util.BukkitCompletionScheduler;
/** One isolated native inventory view; no registrations in existing production GUI managers. */
public final class VoteStreaksMenu implements Listener, AutoCloseable {
public static final String PERMISSION = "VotingPlugin.Commands.Vote.Streaks";
private static final int MAX_SESSIONS = 128, MAX_LOADS = 16;
private final VotingPluginMain plugin;
private final Consumer<Runnable> worker;
private final BiFunction<UUID, String, VoteStreaksSnapshot> snapshot;
private final Map<UUID, Session> sessions = new ConcurrentHashMap<>();
private final AtomicInteger loading = new AtomicInteger();
private final AtomicInteger reloadDepth = new AtomicInteger();
private volatile boolean closed;
public VoteStreaksMenu(VotingPluginMain plugin) {
this(plugin, task -> plugin.getUserManager().getDataManager().getTimer().execute(task), (uuid, name) ->
plugin.getVoteStreakHandler().snapshotForDisplay(plugin.getVotingPluginUserManager().getVotingPluginUser(uuid, name)));
}
VoteStreaksMenu(VotingPluginMain plugin, Consumer<Runnable> worker, BiFunction<UUID, String, VoteStreaksSnapshot> snapshot) {
this.plugin = plugin; this.worker = worker; this.snapshot = snapshot;
}
private static final class Session {
final Player player;
final UUID owner;
final String name;
final Inventory previous;
final boolean ownsPrevious;
final long created = System.nanoTime();
volatile Holder view;
Session(Player player, VoteStreaksMenu manager) {
this.player = player; owner = player.getUniqueId(); name = player.getName();
previous = player.getOpenInventory().getTopInventory();
Holder holder = manager.holder(previous);
ownsPrevious = holder != null && holder.session.owner.equals(owner);
}
}
static final class Holder implements InventoryHolder {
final VoteStreaksMenu manager;
final Session session;
final VoteStreaksSnapshot snapshot;
final int page;
Inventory inventory;
Holder(VoteStreaksMenu manager, Session session, VoteStreaksSnapshot snapshot, int page) {
this.manager = manager; this.session = session; this.snapshot = snapshot; this.page = snapshot.clampPage(page);
}
@Override public Inventory getInventory() { return inventory; }
}
private static boolean permitted(Player player) {
return player.isOnline() && (player.hasPermission(PERMISSION) || player.hasPermission("VotingPlugin.Player"));
}
private void onPlayer(Player player, Runnable work, Runnable rejected) {
BukkitCompletionScheduler.run(plugin, player, work, rejected, rejected);
}
public void open(Player player) {
onPlayer(player, () -> begin(player), () -> { });
}
private void begin(Player player) {
if (closed || reloadDepth.get() != 0 || !permitted(player)) return;
if (loading.incrementAndGet() > MAX_LOADS) {
loading.decrementAndGet(); player.sendMessage("Vote streaks are busy. Please try again shortly."); return;
}
Session session;
synchronized (sessions) {
if (closed || reloadDepth.get() != 0 || (sessions.size() >= MAX_SESSIONS && !sessions.containsKey(player.getUniqueId()))) {
loading.decrementAndGet(); player.sendMessage("Vote streaks are unavailable. Please try again shortly."); return;
}
session = new Session(player, this); sessions.put(session.owner, session);
}
try {
worker.accept(() -> {
try {
if (!current(session)) return;
VoteStreaksSnapshot data = snapshot.apply(session.owner, session.name);
onPlayer(player, () -> {
if (!current(session)) return;
if (!permitted(player) || System.nanoTime() - session.created > 30_000_000_000L
|| player.getOpenInventory().getTopInventory() != session.previous) {
retire(session); return;
}
renderSafely(session, data, 0);
}, () -> retire(session));
} catch (RuntimeException failure) {
onPlayer(player, () -> {
if (retire(session) && player.isOnline())
player.sendMessage("Unable to read vote streaks. Please try again later.");
}, () -> retire(session));
} finally { loading.decrementAndGet(); }
});
} catch (RuntimeException rejected) {
loading.decrementAndGet(); retire(session);
player.sendMessage("Vote streaks are unavailable. Please try again later.");
}
}
private boolean current(Session session) { return !closed && sessions.get(session.owner) == session; }
private Holder holder(Inventory inventory) {
return inventory != null && inventory.getHolder() instanceof Holder holder && holder.manager == this ? holder : null;
}
private void renderSafely(Session session, VoteStreaksSnapshot data, int page) {
try { render(session, data, page); }
catch (RuntimeException failure) {
if (sessions.remove(session.owner, session)) {
closeView(session);
if (session.player.isOnline()) session.player.sendMessage("Unable to open vote streaks. Please try again later.");
}
}
}
private void navigate(Holder holder, int page) {
onPlayer(holder.session.player, () -> {
if (current(holder.session) && holder.session.view == holder
&& holder.session.player.getOpenInventory().getTopInventory() == holder.inventory)
renderSafely(holder.session, holder.snapshot, page);
}, () -> sessions.remove(holder.session.owner, holder.session));
}
private void render(Session session, VoteStreaksSnapshot data, int page) {
if (!current(session) || !permitted(session.player)) return;
Holder holder = new Holder(this, session, data, page);
String title = plugin.getGui().getChestVoteStreaksName();
holder.inventory = Bukkit.createInventory(holder, 54, MessageAPI.colorize(title));
for (int i = 0; i < data.periods().size(); i++) {
var period = data.periods().get(i); String unit = VoteStreaksSnapshot.unit(period.type());
holder.inventory.setItem(11 + i * 2, item(Material.CLOCK, "&6" + period.type() + " streak",
List.of("&7Current: &e" + period.current() + " " + unit, "&7Best: &e" + period.best() + " " + unit)));
}
List<VoteStreaksSnapshot.Milestone> milestones = data.page(holder.page);
for (int i = 0; i < milestones.size(); i++) {
var milestone = milestones.get(i); String unit = VoteStreaksSnapshot.unit(milestone.type());
var lore = new ArrayList<String>();
lore.add("&7Current: &e" + milestone.current() + " " + unit);
lore.add("&7Best: &e" + milestone.best() + " " + unit);
lore.add("&7Milestone: &e" + milestone.threshold() + " " + unit);
lore.add("&7Votes per period: &e" + milestone.votesRequired());
lore.add(milestone.recurring() ? "&7Repeats every " + milestone.threshold() + " " + unit + "; next: " + milestone.nextThreshold()
: milestone.current() >= milestone.threshold() ? "&aCurrent streak meets this milestone" : "&7Upcoming milestone");
lore.add("&7Progress only; this does not claim rewards.");
holder.inventory.setItem(20 + i, item(Material.PAPER, "&e" + milestone.id(), lore));
}
if (milestones.isEmpty()) holder.inventory.setItem(22, item(Material.PAPER, "&7No enabled streak milestones",
List.of("&7Configure VoteStreaks in SpecialRewards.yml.")));
holder.inventory.setItem(45, item(Material.ARROW, "&ePrevious", List.of()));
holder.inventory.setItem(49, item(Material.BARRIER, "&cClose", List.of()));
holder.inventory.setItem(50, item(Material.CLOCK, "&eRefresh", List.of("&7Read current streaks again.")));
holder.inventory.setItem(53, item(Material.ARROW, "&eNext", List.of("&7Page " + (holder.page + 1) + "/" + data.pages(),
data.truncated() ? "&7Showing the first 512 enabled milestones." : "&7Read-only streak progression.")));
session.view = holder;
if (!current(session) || !permitted(session.player)) return;
session.player.openInventory(holder.inventory);
if (!current(session) && session.player.getOpenInventory().getTopInventory() == holder.inventory)
session.player.closeInventory();
if (session.player.getOpenInventory().getTopInventory() != holder.inventory) sessions.remove(session.owner, session);
}
private static ItemStack item(Material material, String name, List<String> lore) {
ItemStack item = new ItemStack(material); ItemMeta meta = item.getItemMeta();
if (meta != null) {
meta.setDisplayName(MessageAPI.colorize(name));
meta.setLore(lore.stream().map(MessageAPI::colorize).toList()); item.setItemMeta(meta);
}
return item;
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = false)
public void inventoryOpen(InventoryOpenEvent event) {
if (!(event.getPlayer() instanceof Player player)) return;
Holder holder = holder(event.getInventory());
if (holder == null) return;
if (holder.session.player != player || !current(holder.session) || holder.session.view != holder || !permitted(player)) {
event.setCancelled(true); return;
}
if (event.isCancelled()) sessions.remove(holder.session.owner, holder.session);
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void unrelatedInventoryOpen(InventoryOpenEvent event) {
if (!event.isCancelled() && holder(event.getInventory()) == null && event.getPlayer() instanceof Player player)
sessions.remove(player.getUniqueId());
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = false)
public void click(InventoryClickEvent event) {
Holder holder = holder(event.getView().getTopInventory());
if (holder == null) return;
boolean cancelled = event.isCancelled(); event.setCancelled(true);
if (cancelled || event.getWhoClicked() != holder.session.player || !current(holder.session)
|| holder.session.view != holder || !permitted(holder.session.player)) return;
// Only ordinary top-inventory clicks navigate; shift/number/drop actions cannot move previews.
if (event.getRawSlot() < 0 || event.getRawSlot() >= 54 || !event.isLeftClick() || event.isShiftClick()) return;
switch (event.getRawSlot()) {
case 45 -> navigate(holder, holder.page - 1);
case 53 -> navigate(holder, holder.page + 1);
case 49 -> { sessions.remove(holder.session.owner, holder.session); closeView(holder.session); }
case 50 -> begin(holder.session.player);
default -> { }
}
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = false)
public void drag(InventoryDragEvent event) {
if (holder(event.getView().getTopInventory()) != null) event.setCancelled(true);
}
@EventHandler public void inventoryClose(InventoryCloseEvent event) {
Holder holder = holder(event.getInventory());
if (holder != null && holder.session.view == holder) sessions.remove(holder.session.owner, holder.session);
else if (event.getPlayer() instanceof Player player) {
Session pending = sessions.get(player.getUniqueId());
if (pending != null && pending.view == null && pending.previous == event.getInventory()) sessions.remove(pending.owner, pending);
}
}
@EventHandler public void quit(PlayerQuitEvent event) { sessions.remove(event.getPlayer().getUniqueId()); }
@EventHandler public void worldChange(PlayerChangedWorldEvent event) { end(event.getPlayer()); }
@EventHandler public void death(PlayerDeathEvent event) { end(event.getEntity()); }
private void end(Player player) { Session session = sessions.remove(player.getUniqueId()); if (session != null) closeView(session); }
private boolean retire(Session session) {
if (!sessions.remove(session.owner, session)) return false;
closeView(session); return true;
}
private void closeView(Session session) {
if (session.view == null && !session.ownsPrevious) return;
Runnable cleanup = () -> {
// A queued cleanup must never close an inventory adopted by a newer request.
Session replacement = sessions.get(session.owner);
if (replacement != null && replacement != session) return;
Inventory top = session.player.getOpenInventory().getTopInventory();
if ((session.view != null && top == session.view.inventory)
|| (session.ownsPrevious && top == session.previous)) session.player.closeInventory();
};
// Bukkit rejects scheduling after disable. Its primary thread already owns this interaction.
if (closed && ownsForShutdown(Bukkit.class, session.player)) cleanup.run();
else onPlayer(session.player, cleanup, () -> { });
}
/** Public Folia ownership also recognizes its stopped-region shutdown owner. */
static boolean ownsForShutdown(Class<?> platform, Player player) {
try {
return Boolean.TRUE.equals(platform.getMethod("isOwnedByCurrentRegion", org.bukkit.entity.Entity.class).invoke(null, player));
} catch (NoSuchMethodException legacy) {
try {
Class.forName("io.papermc.paper.threadedregions.RegionizedServer", false, VoteStreaksMenu.class.getClassLoader());
return false; // A regional server without its ownership API must fail closed.
} catch (ClassNotFoundException ordinaryServer) { return Bukkit.isPrimaryThread(); }
catch (LinkageError unavailable) { return false; }
} catch (ReflectiveOperationException | LinkageError unavailable) { return false; }
}
public void suspend() { reloadDepth.incrementAndGet(); reset(); }
public void resume() { reloadDepth.updateAndGet(value -> Math.max(0, value - 1)); }
public void reset() {
List<Session> old;
synchronized (sessions) { old = List.copyOf(sessions.values()); sessions.clear(); }
old.forEach(this::closeView);
}
@Override public void close() { synchronized (sessions) { closed = true; } reset(); }
int sessionCount() { return sessions.size(); }
}
@@ -1,37 +0,0 @@
package com.bencodez.votingplugin.streaks;
import java.util.List;
import com.bencodez.votingplugin.specialrewards.votestreak.VoteStreakType;
/** Read-only observations of existing state; never evidence that a reward was delivered. */
public record VoteStreaksSnapshot(List<Period> periods, List<Milestone> milestones, boolean truncated) {
public static final int MAX_MILESTONES = 512;
public static final int PAGE_SIZE = 5;
public VoteStreaksSnapshot {
periods = List.copyOf(periods);
milestones = List.copyOf(milestones);
if (periods.size() != 3 || milestones.size() > MAX_MILESTONES) throw new IllegalArgumentException("Invalid streak snapshot size");
}
public record Period(VoteStreakType type, int current, int best) {
public Period { current = Math.max(0, current); best = Math.max(current, best); }
}
public record Milestone(String id, VoteStreakType type, int current, int best,
int threshold, int votesRequired, boolean recurring) {
public Milestone {
current = Math.max(0, current); best = Math.max(current, best);
threshold = Math.max(1, threshold); votesRequired = Math.max(1, votesRequired);
}
public long nextThreshold() {
return recurring ? ((long) current / threshold + 1L) * threshold : threshold;
}
}
public int pages() { return Math.max(1, (milestones.size() + PAGE_SIZE - 1) / PAGE_SIZE); }
public int clampPage(int page) { return Math.max(0, Math.min(page, pages() - 1)); }
public List<Milestone> page(int page) {
int start = clampPage(page) * PAGE_SIZE;
return milestones.subList(start, Math.min(start + PAGE_SIZE, milestones.size()));
}
public static String unit(VoteStreakType type) {
return switch (type) { case DAILY -> "days"; case WEEKLY -> "weeks"; case MONTHLY -> "months"; };
}
}
@@ -3,15 +3,10 @@ package com.bencodez.votingplugin.timequeue;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Queue;
import java.util.UUID;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.event.EventHandler;
@@ -29,24 +24,11 @@ import lombok.Getter;
* The TimeQueueHandler class manages time-based vote queue processing.
*/
public class TimeQueueHandler implements Listener {
private static final long TICKS_PER_SECOND = 20L;
@Getter
private Queue<VoteTimeQueue> timeChangeQueue = new ConcurrentLinkedQueue<>();
private VotingPluginMain plugin;
private final Object persistenceLock = new Object();
private volatile boolean stopping;
private final AtomicReference<FutureTask<Void>> shutdownSave = new AtomicReference<>();
// A failed task is retryable, but cannot release its unsaved suffix to a successor.
private final AtomicReference<ShutdownPublication> shutdownPublicationOwner = new AtomicReference<>();
private record ShutdownPublication(com.bencodez.votingplugin.util.ServerDataPublicationFence.Lease lease,
java.util.concurrent.ScheduledExecutorService producers,
java.util.concurrent.ScheduledExecutorService[] coreWriters) { }
private final AtomicBoolean processing = new AtomicBoolean();
private VoteTimeQueue dispatchingVote;
private UUID dispatchId;
private boolean dispatchEnded;
private boolean dispatchStarted;
private int persistedShutdownVotes;
private final AtomicBoolean retryPending = new AtomicBoolean();
private final AtomicInteger retryAttempts = new AtomicInteger();
@@ -67,13 +49,8 @@ public class TimeQueueHandler implements Listener {
* @param voteSiteName the vote site name
*/
public void addVote(String voteUsername, String voteSiteName) {
synchronized (persistenceLock) {
timeChangeQueue.add(new VoteTimeQueue(voteUsername, voteSiteName,
LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()));
// A vote task can outlive shutdownNow(). Persist its late admission
// through the same owner rather than appending to an already-saved queue.
if (stopping) persistPendingVotes();
}
timeChangeQueue.add(new VoteTimeQueue(voteUsername, voteSiteName,
LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()));
}
/**
@@ -99,11 +76,17 @@ public class TimeQueueHandler implements Listener {
}
private void scheduleQueueProcessing(long delay, TimeUnit unit) {
synchronized (persistenceLock) { if (stopping) return; }
boolean admitted = VoteTaskAdmission.trySchedule(plugin.getVoteTimer(), this::processQueue, delay, unit);
boolean admitted = VoteTaskAdmission.trySchedule(plugin.getVoteTimer(), () -> {
// Clear only after the bounded executor has admitted the task. If it is
// rejected, shutdown persistence can still recover the in-memory queue.
plugin.getServerData().clearTimedVoteCache();
processQueue();
}, delay, unit);
if (!admitted) {
plugin.getLogger().warning("Unable to schedule time-queue processing because vote processing is busy; queued votes were retained.");
scheduleRetry();
} else {
retryAttempts.set(0);
}
}
@@ -111,14 +94,15 @@ public class TimeQueueHandler implements Listener {
if (timeChangeQueue.isEmpty() || !retryPending.compareAndSet(false, true)) return;
int attempt = Math.min(6, retryAttempts.getAndIncrement());
long delaySeconds = Math.min(60L, 1L << attempt);
long delayTicks = delaySeconds * TICKS_PER_SECOND;
try {
plugin.getBukkitScheduler().runTaskLaterAsynchronously(plugin, () -> {
retryPending.set(false);
if (!timeChangeQueue.isEmpty()) scheduleQueueProcessing(0, TimeUnit.SECONDS);
}, delaySeconds);
}, delayTicks);
} catch (RuntimeException rejected) {
retryPending.set(false);
plugin.getLogger().warning("Unable to queue a time-queue retry; pending votes remain owned for recovery.");
plugin.getLogger().warning("Unable to queue a time-queue retry; pending votes remain persisted for recovery.");
}
}
@@ -126,239 +110,32 @@ public class TimeQueueHandler implements Listener {
* Processes all votes in the queue.
*/
public void processQueue() {
if (!processing.compareAndSet(false, true)) return;
boolean retry = false;
try {
synchronized (persistenceLock) {
if (stopping) return;
if (dispatchingVote != null) {
if (!dispatchEnded) return;
retainUncertainDispatch();
clearDispatch();
}
persistedShutdownVotes = 0;
while (getTimeChangeQueue().size() > 0) {
VoteTimeQueue vote = getTimeChangeQueue().remove();
PlayerVoteEvent voteEvent = new PlayerVoteEvent(
plugin.getVoteSiteManager().getVoteSite(plugin.getVoteSiteManager().getVoteSiteName(true, vote.getService()), true), vote.getName(),
vote.getService(), true);
voteEvent.setTime(vote.getTime());
plugin.getServer().getPluginManager().callEvent(voteEvent);
if (voteEvent.isCancelled()) {
plugin.debug("Vote cancelled");
continue;
}
while (true) {
VoteTimeQueue vote;
synchronized (persistenceLock) {
if (stopping || dispatchingVote != null) return;
vote = timeChangeQueue.peek();
}
if (vote == null) return;
PlayerVoteEvent voteEvent = new PlayerVoteEvent(
plugin.getVoteSiteManager().getVoteSite(plugin.getVoteSiteManager().getVoteSiteName(true, vote.getService()), true), vote.getName(),
vote.getService(), true);
voteEvent.setTime(vote.getTime());
synchronized (persistenceLock) {
if (stopping) return;
if (timeChangeQueue.peek() != vote) continue;
dispatchingVote = vote;
if (vote.getVoteId() == null) vote.setVoteId(UUID.randomUUID());
dispatchId = vote.getVoteId();
dispatchEnded = false;
try {
plugin.getServerData().prepareTimedVoteDispatch(dispatchId, vote,
timeChangeQueue.stream().filter(pending -> pending != vote).toList());
} catch (RuntimeException | Error failure) {
clearDispatch();
throw failure;
}
// A preparation resumed after stop is still eligible for normal recovery.
if (stopping) return;
dispatchStarted = true;
}
try {
plugin.getServer().getPluginManager().callEvent(voteEvent);
} catch (RuntimeException | Error failure) {
synchronized (persistenceLock) {
dispatchEnded = true;
try {
retainUncertainDispatch();
clearDispatch();
if (!stopping) checkpointPendingVotes();
} catch (RuntimeException | Error persistenceFailure) {
if (failure != persistenceFailure) failure.addSuppressed(persistenceFailure);
}
}
throw failure;
}
synchronized (persistenceLock) {
dispatchEnded = true;
if (!stopping) plugin.getServerData().completeTimedVoteDispatch(dispatchId);
timeChangeQueue.remove(vote);
clearDispatch();
if (voteEvent.isCancelled() && !stopping) checkpointPendingVotes();
}
if (voteEvent.isCancelled()) {
plugin.debug("Vote cancelled");
continue;
}
}
} catch (RuntimeException | Error failure) {
retry = !stopping;
throw failure;
} finally {
processing.set(false);
if (retry) scheduleRetry();
else retryAttempts.set(0);
}
}
private void clearDispatch() {
dispatchingVote = null;
dispatchId = null;
dispatchEnded = false;
dispatchStarted = false;
}
private void checkpointPendingVotes() {
plugin.getServerData().replaceTimedVoteCache(
timeChangeQueue.stream().filter(vote -> vote != dispatchingVote).toList());
persistedShutdownVotes = 0;
}
/** Uncertain event delivery is retained for review, never automatically replayed. */
private void retainUncertainDispatch() {
if (dispatchingVote == null || !timeChangeQueue.contains(dispatchingVote)) return;
plugin.getServerData().addUncertainTimedVote(dispatchId, dispatchingVote);
timeChangeQueue.remove(dispatchingVote);
plugin.getLogger().warning("Timed vote event delivery is uncertain; retained in ServerData.yml VotingPlugin.UncertainTimedVotes for manual review.");
}
/**
* Saves pending votes to server data.
*/
public void save() {
if (stopping) {
saveForShutdown();
return;
}
synchronized (persistenceLock) {
if (stopping) persistPendingVotes();
else checkpointPendingVotes();
}
}
/** Seal processing and retain one persistence owner without an unbounded lifecycle wait. */
public void saveForShutdown() {
stopping = true;
FutureTask<Void> save;
while (true) {
save = shutdownSave.get();
if (save != null) {
if (!save.isDone()) break;
shutdownSave.compareAndSet(save, null);
continue;
}
FutureTask<Void> candidate = new FutureTask<Void>(() -> {
try {
var publication = java.util.Objects.requireNonNull(shutdownPublicationOwner.get());
try { synchronized (persistenceLock) { persistPendingVotes(); } }
finally {
// Publication failure does not terminate previously admitted producers.
awaitRetiringProducers(publication.producers());
if (publication.coreWriters() != null)
for (var writer : publication.coreWriters()) awaitWriterTermination(writer);
}
synchronized (persistenceLock) { persistPendingVotes(); }
if (publication.lease() != null) publication.lease().close();
shutdownPublicationOwner.compareAndSet(publication, null);
} catch (RuntimeException | Error failure) {
try {
plugin.getLogger().warning("Timed vote shutdown persistence failed; pending votes remain owned for retry. Recovery is not confirmed.");
} catch (RuntimeException | Error ignored) { }
throw failure;
}
return null;
}) {
@Override protected void done() {
// Late admission failures must be retryable after this owner completes.
shutdownSave.compareAndSet(this, null);
}
};
FutureTask<Void> existing = shutdownSave.compareAndExchange(null, candidate);
if (existing == null) {
save = candidate;
try {
if (shutdownPublicationOwner.get() == null) {
// Unload can clear these fields even while their original work survives.
// Keep the snapshot with its lease through every rejected or failed attempt.
var producers = plugin.getVoteTimer();
var coreWriters = plugin.getServerDataWriterExecutors();
var retainedWriters = coreWriters == null ? null : coreWriters.clone();
var fence = plugin.getServerDataPublicationFence();
shutdownPublicationOwner.set(new ShutdownPublication(
fence == null ? null : fence.acquire(), producers, retainedWriters));
}
startShutdownWorker(candidate);
}
catch (RuntimeException | Error failure) {
// Even a rejected worker retains the queue owner for an explicit retry.
candidate.cancel(false);
shutdownSave.compareAndSet(candidate, null);
throw failure;
}
break;
}
}
try {
save.get(1, TimeUnit.SECONDS);
shutdownSave.compareAndSet(save, null);
} catch (TimeoutException pending) {
plugin.getLogger().warning("Timed vote shutdown persistence is still pending; its worker retains ownership. Recovery is not yet confirmed.");
} catch (InterruptedException interrupted) {
Thread.currentThread().interrupt();
plugin.getLogger().warning("Timed vote shutdown persistence wait was interrupted; its worker retains ownership.");
} catch (ExecutionException failure) {
shutdownSave.compareAndSet(save, null);
Throwable cause = failure.getCause();
if (cause instanceof Error error) throw error;
if (cause instanceof RuntimeException runtime) throw runtime;
throw new IllegalStateException("Timed vote shutdown persistence failed", cause);
}
}
/** Kept separate so worker-admission failure can be exercised without replacing persistence. */
protected void startShutdownWorker(Runnable task) {
Thread worker = new Thread(task, "VotingPlugin-timed-vote-shutdown");
worker.setDaemon(true);
worker.start();
}
private void awaitRetiringProducers(java.util.concurrent.ScheduledExecutorService producers) {
if (producers == null || !producers.isShutdown()) return;
awaitWriterTermination(producers);
}
private void awaitWriterTermination(java.util.concurrent.ScheduledExecutorService producers) {
if (producers == null) return;
boolean interrupted = false;
try {
while (!producers.isTerminated()) {
try { producers.awaitTermination(100, TimeUnit.MILLISECONDS); }
catch (InterruptedException ignored) { interrupted = true; }
}
} finally { if (interrupted) Thread.currentThread().interrupt(); }
}
/** Remove only a successfully saved prefix; failures retain the same next slot for retry. */
private void persistPendingVotes() {
VoteTimeQueue vote;
while ((vote = timeChangeQueue.peek()) != null) {
if (vote == dispatchingVote) {
if (dispatchStarted) retainUncertainDispatch();
else {
var pending = timeChangeQueue.stream().toList();
plugin.getServerData().abortTimedVoteDispatch(dispatchId, pending);
timeChangeQueue.removeAll(pending);
persistedShutdownVotes = pending.size();
clearDispatch();
}
} else {
plugin.getServerData().addTimeVoted(persistedShutdownVotes, vote);
persistedShutdownVotes++;
timeChangeQueue.remove(vote);
if (!timeChangeQueue.isEmpty()) {
int num = 0;
for (VoteTimeQueue vote : timeChangeQueue) {
plugin.getServerData().addTimeVoted(num, vote);
num++;
}
}
timeChangeQueue.clear();
}
}
@@ -1,269 +0,0 @@
package com.bencodez.votingplugin.topvoter;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Set;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.CompletableFuture;
import java.util.function.Function;
import java.util.function.BiFunction;
import java.util.function.LongSupplier;
import com.bencodez.advancedcore.api.user.presence.PlayerPresence;
import org.bukkit.event.Listener;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.player.PlayerJoinEvent;
/** Bounded display snapshots only; raw rankings and award inputs stay untouched. */
public final class TopVoterDisplayFilter implements AutoCloseable, Listener {
private static final int MAX_PENDING = 128;
private static final int MAX_CACHED = 8192;
private static final long MAX_AGE = java.util.concurrent.TimeUnit.SECONDS.toNanos(30);
private record Identity(UUID uuid, String name) { }
private static final class Evidence {
private PlayerPresence value = PlayerPresence.UNKNOWN;
private long completed;
private boolean pending = true;
private Set<UUID> identities = Set.of();
private long joinGeneration;
private TopVoterPlayer snapshot;
private List<UUID> aliases;
private final CompletableFuture<Void> settled = new CompletableFuture<>();
}
private final Function<TopVoterPlayer, List<UUID>> identities;
private final BiFunction<TopVoterPlayer, List<UUID>, CompletionStage<PlayerPresence>> lookup;
private final LongSupplier clock;
private final LongSupplier rankingRowBudget;
private volatile int cacheLimit = MAX_CACHED;
private final LinkedHashMap<Identity, Evidence> cache = new LinkedHashMap<>(16, 0.75f, true);
private int pending;
private boolean closed;
private long joinGeneration;
public TopVoterDisplayFilter(Function<TopVoterPlayer, CompletionStage<PlayerPresence>> lookup) {
this(lookup, System::nanoTime);
}
public TopVoterDisplayFilter(Function<TopVoterPlayer, CompletionStage<PlayerPresence>> lookup, LongSupplier clock) {
this(player -> List.of(player.getUuid()), (player, aliases) -> lookup.apply(player), clock);
Objects.requireNonNull(lookup);
}
/** Check the captured cache-only scope asynchronously; revalidate it before using negative evidence. */
public TopVoterDisplayFilter(Function<TopVoterPlayer, List<UUID>> identities,
BiFunction<TopVoterPlayer, List<UUID>, CompletionStage<PlayerPresence>> lookup) {
this(identities, lookup, System::nanoTime);
}
public TopVoterDisplayFilter(Function<TopVoterPlayer, List<UUID>> identities,
BiFunction<TopVoterPlayer, List<UUID>, CompletionStage<PlayerPresence>> lookup, LongSupplier clock) {
this(identities, lookup, clock, () -> 0L);
}
/** The owner supplies the row count already retained in current and historical ranking maps. */
public TopVoterDisplayFilter(Function<TopVoterPlayer, List<UUID>> identities,
BiFunction<TopVoterPlayer, List<UUID>, CompletionStage<PlayerPresence>> lookup, LongSupplier clock,
LongSupplier rankingRowBudget) {
this.identities = Objects.requireNonNull(identities);
this.lookup = Objects.requireNonNull(lookup);
this.clock = Objects.requireNonNull(clock);
this.rankingRowBudget = Objects.requireNonNull(rankingRowBudget);
}
/** Pending, failed, missing or stale evidence remains visible until a checked result arrives. */
public LinkedHashMap<TopVoterPlayer, Integer> project(Map<TopVoterPlayer, Integer> rankings, boolean enabled) {
if (enabled) reserveRankingRows(rankings.size());
var visible = new LinkedHashMap<TopVoterPlayer, Integer>();
for (var entry : rankings.entrySet()) {
if (!enabled || evidence(entry.getKey()) != PlayerPresence.NEVER_JOINED)
visible.put(entry.getKey(), entry.getValue());
}
return visible;
}
private void reserveRankingRows(int rows) {
long requested = rows;
// Read owner state outside the evidence monitor. A racing replacement may leave
// a temporary unknown budget; keep the previous bound until the next refresh.
try { requested = Math.max(requested, rankingRowBudget.getAsLong()); }
catch (RuntimeException unavailable) { requested = Math.max(requested, cacheLimit); }
synchronized (cache) {
cacheLimit = (int) Math.min(Integer.MAX_VALUE, Math.max(MAX_CACHED, requested));
trimCompletedEvidence(cacheLimit);
}
}
/** Called under cache; in-flight requests retain their bounded admission until completion. */
private void trimCompletedEvidence(int limit) {
var oldest = cache.entrySet().iterator();
while (cache.size() > limit && oldest.hasNext()) {
if (!oldest.next().getValue().pending) oldest.remove();
}
}
/** Await admitted checks without blocking their worker; unavailable rows stay visible. */
public CompletionStage<LinkedHashMap<TopVoterPlayer, Integer>> projectAsync(
Map<TopVoterPlayer, Integer> rankings, boolean enabled) {
var snapshot = new LinkedHashMap<>(rankings);
if (!enabled) return CompletableFuture.completedFuture(snapshot);
project(snapshot, true);
var captured = new LinkedHashMap<Identity, Evidence>();
var waiting = new java.util.ArrayList<CompletableFuture<Void>>();
synchronized (cache) {
for (TopVoterPlayer player : snapshot.keySet()) {
if (player == null || player.getUuid() == null) continue;
Identity key = new Identity(player.getUuid(), player.getPlayerName());
Evidence record = cache.get(key);
if (record != null) {
captured.put(key, record);
if (record.pending) waiting.add(record.settled);
}
}
}
return CompletableFuture.allOf(waiting.toArray(CompletableFuture[]::new))
.completeOnTimeout(null, 5, java.util.concurrent.TimeUnit.SECONDS).thenApply(ignored -> {
var visible = new LinkedHashMap<TopVoterPlayer, Integer>();
for (var entry : snapshot.entrySet()) {
TopVoterPlayer player = entry.getKey();
Identity key = player == null ? null : new Identity(player.getUuid(), player.getPlayerName());
Evidence record = captured.get(key);
if (record == null || cachedValue(key, record) != PlayerPresence.NEVER_JOINED)
visible.put(player, entry.getValue());
}
return visible;
});
}
private PlayerPresence evidence(TopVoterPlayer player) {
if (player == null || player.getUuid() == null) return PlayerPresence.UNKNOWN;
Identity key = new Identity(player.getUuid(), player.getPlayerName());
Evidence record;
boolean reuse;
synchronized (cache) {
if (closed) return PlayerPresence.UNKNOWN;
record = cache.get(key);
reuse = record != null && (record.pending || clock.getAsLong() - record.completed < MAX_AGE);
if (!reuse) {
if (pending >= MAX_PENDING) return PlayerPresence.UNKNOWN;
if (record != null) cache.remove(key);
if (cache.size() >= cacheLimit) trimCompletedEvidence(cacheLimit - 1);
if (cache.size() >= cacheLimit) return PlayerPresence.UNKNOWN;
record = new Evidence(); cache.put(key, record); pending++;
record.joinGeneration = joinGeneration;
record.snapshot = new TopVoterPlayer(key.uuid(), key.name(), player.getLastVoteTime());
}
}
if (reuse) return cachedValue(key, record);
Evidence admitted = record;
try {
List<UUID> aliases = resolveScope(admitted.snapshot);
if (aliases == null) {
finish(key, admitted, PlayerPresence.UNKNOWN);
return PlayerPresence.UNKNOWN;
}
var checked = new java.util.HashSet<UUID>();
for (UUID alias : aliases) if (alias != null) checked.add(alias);
boolean valid;
synchronized (cache) {
valid = !closed && cache.get(key) == admitted && admitted.joinGeneration == joinGeneration;
if (valid) {
admitted.identities = Set.copyOf(checked);
admitted.aliases = aliases;
} else cache.remove(key, admitted);
}
if (!valid) {
finish(key, admitted, PlayerPresence.UNKNOWN);
return PlayerPresence.UNKNOWN;
}
CompletionStage<PlayerPresence> request = lookup.apply(admitted.snapshot, aliases);
if (request == null) finish(key, admitted, PlayerPresence.UNKNOWN);
else request.whenComplete((result, failure) -> finish(key, admitted,
failure == null && result != null ? result : PlayerPresence.UNKNOWN));
} catch (RuntimeException unavailable) {
finish(key, admitted, PlayerPresence.UNKNOWN);
}
return cachedValue(key, admitted);
}
private List<UUID> resolveScope(TopVoterPlayer snapshot) {
List<UUID> resolved = identities.apply(snapshot);
if (resolved == null || resolved.isEmpty() || resolved.size() > 8) return null;
// Preserve null uncertainty markers and detach the provider from mutable cache data.
return java.util.Collections.unmodifiableList(new java.util.ArrayList<>(resolved));
}
private boolean matchesScope(Evidence record) {
try {
return record.aliases != null && record.aliases.equals(resolveScope(record.snapshot));
} catch (RuntimeException unavailable) {
return false;
}
}
private PlayerPresence cachedValue(Identity key, Evidence record) {
PlayerPresence value;
synchronized (cache) {
if (closed || cache.get(key) != record || record.pending
|| clock.getAsLong() - record.completed >= MAX_AGE) return PlayerPresence.UNKNOWN;
value = record.value;
}
// The resolver is cache-only, but must never run under the evidence-cache monitor.
if (value == PlayerPresence.NEVER_JOINED && !matchesScope(record)) {
synchronized (cache) { cache.remove(key, record); }
return PlayerPresence.UNKNOWN;
}
synchronized (cache) {
return !closed && cache.get(key) == record && !record.pending
&& clock.getAsLong() - record.completed < MAX_AGE ? record.value : PlayerPresence.UNKNOWN;
}
}
private void finish(Identity key, Evidence record, PlayerPresence result) {
boolean currentScope = result != PlayerPresence.NEVER_JOINED || matchesScope(record);
synchronized (cache) {
if (!record.pending) return;
record.pending = false; pending--;
if (!closed && cache.get(key) == record) {
if (!currentScope) cache.remove(key, record);
else { record.value = result; record.completed = clock.getAsLong(); }
}
trimCompletedEvidence(cacheLimit);
}
// Completion may invoke projection callbacks, which resolve aliases outside this monitor.
record.settled.complete(null);
}
/** A newly observed join revokes matching negative snapshots and pending stale completions. */
public void joined(UUID uuid, String name) {
var invalidated = new java.util.ArrayList<Evidence>();
synchronized (cache) {
joinGeneration++;
cache.entrySet().removeIf(entry -> {
boolean matches = Objects.equals(entry.getKey().uuid(), uuid)
|| (uuid != null && entry.getValue().identities.contains(uuid))
|| (name != null && name.equalsIgnoreCase(entry.getKey().name()));
if (matches) invalidated.add(entry.getValue());
return matches;
});
}
for (Evidence record : invalidated) record.settled.complete(null);
}
@EventHandler(priority = EventPriority.LOWEST)
public void onJoin(PlayerJoinEvent event) {
joined(event.getPlayer().getUniqueId(), event.getPlayer().getName());
}
@Override public void close() {
List<Evidence> retiring;
synchronized (cache) {
closed = true;
retiring = new java.util.ArrayList<>(cache.values());
cache.clear();
}
for (Evidence record : retiring) record.settled.complete(null);
}
}
@@ -113,12 +113,11 @@ public class TopVoterHandler implements Listener {
*/
public String[] getTopVotersWeekly() {
ArrayList<String> msg = new ArrayList<>();
var board = plugin.getTopVoterDisplay(TopVoter.Weekly);
ArrayList<TopVoterPlayer> users = new ArrayList<>(board.keySet());
ArrayList<TopVoterPlayer> users = new ArrayList<>(plugin.getTopVoter(TopVoter.Weekly).keySet());
for (int i = 0; i < users.size(); i++) {
String line = plugin.getConfigFile().getFormatCommandsVoteTopLine().replace("%num%", "" + (i + 1))
.replace("%player%", users.get(i).getPlayerName())
.replace("%votes%", "" + board.get(users.get(i)));
.replace("%votes%", "" + plugin.getTopVoter(TopVoter.Weekly).get(users.get(i)));
msg.add(line);
}
msg = ArrayUtils.colorize(msg);
@@ -639,12 +638,11 @@ public class TopVoterHandler implements Listener {
* @return the string[]
*/
public String[] topVoterAllTime(int page) {
page = Math.max(1, page);
int pagesize = Math.max(1, plugin.getConfigFile().getFormatPageSize());
int pagesize = plugin.getConfigFile().getFormatPageSize();
ArrayList<String> msg = new ArrayList<>();
ArrayList<String> topVoters = new ArrayList<>();
int count = 1;
for (Entry<TopVoterPlayer, Integer> entry : plugin.getTopVoterDisplay(TopVoter.AllTime).entrySet()) {
for (Entry<TopVoterPlayer, Integer> entry : plugin.getTopVoter(TopVoter.AllTime).entrySet()) {
String line = plugin.getConfigFile().getFormatCommandsVoteTopLine();
line = line.replace("%num%", "" + count);
line = line.replace("%player%", entry.getKey().getPlayerName());
@@ -664,8 +662,7 @@ public class TopVoterHandler implements Listener {
title = title.replace("%Top%", plugin.getConfigFile().getFormatTopVoterAllTime());
msg.add(MessageAPI.colorize(title));
long start = (long) (page - 1) * pagesize;
for (int i = (int) Math.min(start, topVoters.size()); i < topVoters.size() && i < start + pagesize; i++) {
for (int i = (page - 1) * pagesize; (i < topVoters.size()) && (i < (((page - 1) * pagesize) + 10)); i++) {
msg.add(topVoters.get(i));
}
@@ -679,12 +676,11 @@ public class TopVoterHandler implements Listener {
* @return array of formatted top voter lines
*/
public String[] topVoterDaily(int page) {
page = Math.max(1, page);
int pagesize = Math.max(1, plugin.getConfigFile().getFormatPageSize());
int pagesize = plugin.getConfigFile().getFormatPageSize();
ArrayList<String> msg = new ArrayList<>();
ArrayList<String> topVoters = new ArrayList<>();
int count = 1;
for (Entry<TopVoterPlayer, Integer> entry : plugin.getTopVoterDisplay(TopVoter.Daily).entrySet()) {
for (Entry<TopVoterPlayer, Integer> entry : plugin.getTopVoter(TopVoter.Daily).entrySet()) {
String line = plugin.getConfigFile().getFormatCommandsVoteTopLine();
line = line.replace("%num%", "" + count);
line = line.replace("%player%", entry.getKey().getPlayerName());
@@ -704,8 +700,7 @@ public class TopVoterHandler implements Listener {
title = title.replace("%Top%", plugin.getConfigFile().getFormatTopVoterDaily());
msg.add(MessageAPI.colorize(title));
long start = (long) (page - 1) * pagesize;
for (int i = (int) Math.min(start, topVoters.size()); i < topVoters.size() && i < start + pagesize; i++) {
for (int i = (page - 1) * pagesize; (i < topVoters.size()) && (i < (((page - 1) * pagesize) + 10)); i++) {
msg.add(topVoters.get(i));
}
@@ -719,12 +714,11 @@ public class TopVoterHandler implements Listener {
* @return array of formatted top voter lines
*/
public String[] topVoterMonthly(int page) {
page = Math.max(1, page);
int pagesize = Math.max(1, plugin.getConfigFile().getFormatPageSize());
int pagesize = plugin.getConfigFile().getFormatPageSize();
ArrayList<String> msg = new ArrayList<>();
ArrayList<String> topVoters = new ArrayList<>();
int count = 1;
for (Entry<TopVoterPlayer, Integer> entry : plugin.getTopVoterDisplay(TopVoter.Monthly).entrySet()) {
for (Entry<TopVoterPlayer, Integer> entry : plugin.getTopVoter(TopVoter.Monthly).entrySet()) {
String line = plugin.getConfigFile().getFormatCommandsVoteTopLine();
line = line.replace("%num%", "" + count);
line = line.replace("%player%", entry.getKey().getPlayerName());
@@ -744,8 +738,7 @@ public class TopVoterHandler implements Listener {
title = title.replace("%Top%", plugin.getConfigFile().getFormatTopVoterMonthly());
msg.add(MessageAPI.colorize(title));
long start = (long) (page - 1) * pagesize;
for (int i = (int) Math.min(start, topVoters.size()); i < topVoters.size() && i < start + pagesize; i++) {
for (int i = (page - 1) * pagesize; (i < topVoters.size()) && (i < (((page - 1) * pagesize) + 10)); i++) {
msg.add(topVoters.get(i));
}
@@ -759,7 +752,7 @@ public class TopVoterHandler implements Listener {
*/
public String[] topVotersAllTime() {
ArrayList<String> msg = new ArrayList<>();
List<Entry<TopVoterPlayer, Integer>> list = new LinkedList<>(plugin.getTopVoterDisplay(TopVoter.AllTime).entrySet());
List<Entry<TopVoterPlayer, Integer>> list = new LinkedList<>(plugin.getTopVoter(TopVoter.AllTime).entrySet());
int i = 0;
for (Entry<TopVoterPlayer, Integer> entry : list) {
String line = "%num%: %player%, %votes%";
@@ -785,8 +778,7 @@ public class TopVoterHandler implements Listener {
*/
public String[] topVotersDaily() {
ArrayList<String> msg = new ArrayList<>();
var board = plugin.getTopVoterDisplay(TopVoter.Daily);
ArrayList<TopVoterPlayer> users = new ArrayList<>(board.keySet());
ArrayList<TopVoterPlayer> users = new ArrayList<>(plugin.getTopVoter(TopVoter.Daily).keySet());
for (int i = 0; i < users.size(); i++) {
String line = "%num%: %player%, %votes%";
line = line.replace("%num%", "" + (i + 1));
@@ -795,7 +787,7 @@ public class TopVoterHandler implements Listener {
} catch (Exception ex) {
VotingPluginMain.plugin.debug(ex);
}
line = line.replace("%votes%", "" + board.get(users.get(i)));
line = line.replace("%votes%", "" + plugin.getTopVoter(TopVoter.Monthly).get(users.get(i)));
msg.add(line);
}
@@ -809,7 +801,7 @@ public class TopVoterHandler implements Listener {
*/
public String[] topVotersMonthly() {
ArrayList<String> msg = new ArrayList<>();
List<Entry<TopVoterPlayer, Integer>> list = new LinkedList<>(plugin.getTopVoterDisplay(TopVoter.Monthly).entrySet());
List<Entry<TopVoterPlayer, Integer>> list = new LinkedList<>(plugin.getTopVoter(TopVoter.Monthly).entrySet());
int i = 0;
for (Entry<TopVoterPlayer, Integer> entry : list) {
String line = "%num%: %player%, %votes%";
@@ -835,12 +827,11 @@ public class TopVoterHandler implements Listener {
* @return array of formatted top voter lines
*/
public String[] topVoterWeekly(int page) {
page = Math.max(1, page);
int pagesize = Math.max(1, plugin.getConfigFile().getFormatPageSize());
int pagesize = plugin.getConfigFile().getFormatPageSize();
ArrayList<String> msg = new ArrayList<>();
ArrayList<String> topVoters = new ArrayList<>();
int count = 1;
for (Entry<TopVoterPlayer, Integer> entry : plugin.getTopVoterDisplay(TopVoter.Weekly).entrySet()) {
for (Entry<TopVoterPlayer, Integer> entry : plugin.getTopVoter(TopVoter.Weekly).entrySet()) {
String line = plugin.getConfigFile().getFormatCommandsVoteTopLine();
line = line.replace("%num%", "" + count);
line = line.replace("%player%", entry.getKey().getPlayerName());
@@ -860,8 +851,7 @@ public class TopVoterHandler implements Listener {
title = title.replace("%Top%", plugin.getConfigFile().getFormatTopVoterWeekly());
msg.add(MessageAPI.colorize(title));
long start = (long) (page - 1) * pagesize;
for (int i = (int) Math.min(start, topVoters.size()); i < topVoters.size() && i < start + pagesize; i++) {
for (int i = (page - 1) * pagesize; (i < topVoters.size()) && (i < (((page - 1) * pagesize) + 10)); i++) {
msg.add(topVoters.get(i));
}
@@ -1,41 +0,0 @@
package com.bencodez.votingplugin.topvoter;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.function.Function;
/** UUID-only evidence scopes; never resolves a profile or loads plugin/server storage. */
public final class TopVoterPresenceIdentity {
private TopVoterPresenceIdentity() { }
/** A null alias explicitly prevents uncertain migration evidence becoming negative. */
public static List<UUID> identities(TopVoterPlayer row, boolean onlineMode, Function<String, String> cachedUuid) {
var identities = new ArrayList<UUID>();
if (row == null || row.getUuid() == null) { identities.add(null); return identities; }
identities.add(row.getUuid());
String name = row.getPlayerName();
if (name == null || name.isBlank() || name.length() > 64 || !name.equals(name.trim())) {
identities.add(null); return identities;
}
UUID offline = UUID.nameUUIDFromBytes(("OfflinePlayer:" + name).getBytes(StandardCharsets.UTF_8));
if (!identities.contains(offline)) identities.add(offline);
UUID current = null;
try {
String known = cachedUuid.apply(name);
if (known != null && !known.isBlank()) {
current = UUID.fromString(known);
if (!current.toString().equalsIgnoreCase(known)) { identities.add(null); return identities; }
}
} catch (RuntimeException unavailable) { identities.add(null); return identities; }
if (current != null && !identities.contains(current)) identities.add(current);
// This validates known aliases; online historical completeness is checked
// separately against retained server history by the asynchronous provider.
boolean resolvable = onlineMode ? row.getUuid().version() == 4 && row.getUuid().variant() == 2
&& (current == null || current.equals(row.getUuid()))
: offline.equals(row.getUuid()) || offline.equals(current);
if (!resolvable) identities.add(null);
return identities;
}
}
@@ -93,20 +93,10 @@ public final class SharedMysqlCacheReconciler {
public static void invalidateAndRefresh(VotingPluginMain plugin, String uuid, String... columns) {
invalidate(plugin, uuid, columns);
if (plugin == null || uuid == null) return;
String pointColumn = plugin.getBungeeSettings().isPerServerPoints()
? plugin.getBungeeSettings().getServerNameStorage() + "_Points" : "Points";
boolean affectsPoints = columns != null && java.util.Arrays.asList(columns).contains(pointColumn);
var placeholders = plugin.getPlaceholders();
java.util.function.Consumer<Boolean> completion = affectsPoints && placeholders != null
? placeholders.sharedPointRefillCompletion(UUID.fromString(uuid)) : null;
try {
plugin.getBukkitScheduler().runTaskAsynchronously(plugin,
() -> tryInvalidateAndRefreshOnWorker(plugin, uuid, columns));
plugin.getVotingPluginUserManager().getVotingPluginUser(UUID.fromString(uuid), false).cacheAsync();
} catch (RuntimeException refreshFailure) {
plugin.debug(refreshFailure);
} finally {
// This admission is not storage evidence. Only the actual worker can recover rendering.
if (completion != null) completion.accept(false);
}
}
@@ -116,37 +106,13 @@ public final class SharedMysqlCacheReconciler {
* A failed refill leaves the snapshot explicitly unavailable, not false zero.
*/
public static void invalidateAndRefreshOnWorker(VotingPluginMain plugin, String uuid, String... columns) {
tryInvalidateAndRefreshOnWorker(plugin, uuid, columns);
}
static boolean tryInvalidateAndRefreshOnWorker(VotingPluginMain plugin, String uuid, String... columns) {
if (plugin == null || uuid == null) return false;
UUID playerUuid = UUID.fromString(uuid);
String pointColumn = plugin.getBungeeSettings().isPerServerPoints()
? plugin.getBungeeSettings().getServerNameStorage() + "_Points" : "Points";
boolean affectsPoints = columns != null && java.util.Arrays.asList(columns).contains(pointColumn);
var placeholders = plugin.getPlaceholders();
java.util.function.Consumer<Boolean> completion = affectsPoints && placeholders != null
? placeholders.sharedPointRefillCompletion(playerUuid) : null;
boolean verified = false;
invalidate(plugin, uuid, columns);
if (plugin == null || uuid == null) return;
try {
invalidate(plugin, uuid, columns);
var manager = plugin.getUserManager().getDataManager();
manager.cacheUser(playerUuid, null);
var cache = manager.getUserDataCache().get(playerUuid);
if (cache != null) synchronized (cache) {
// A complete published row may legitimately omit the selected points key.
// Rendering separately rejects present malformed/unsupported values.
verified = manager.getUserDataCache().get(playerUuid) == cache
&& cache.hasPublishedStorageSnapshot();
}
return true;
plugin.getUserManager().getDataManager().cacheUser(UUID.fromString(uuid), null);
} catch (RuntimeException refreshFailure) {
plugin.getLogger().warning("Shared MySQL cache refresh is unavailable after mutation; stale data was not published.");
plugin.debug(refreshFailure);
return false;
} finally {
if (completion != null) completion.accept(verified);
}
}
@@ -185,29 +185,16 @@ final class SharedMysqlPointMutator {
AddResult addCommittedToColumn(VotingPluginUser user, int amount, String operationId, String pointsColumn) {
if (operationId == null || operationId.isEmpty()) return addCommittedToColumn(user, amount, pointsColumn);
var placeholders = plugin.getPlaceholders();
UUID uuid = UUID.fromString(user.getUUID());
if (placeholders != null) placeholders.beginSharedPointDebit(uuid);
boolean confirmed = false;
drainCache(user, pointsColumn);
try {
drainCache(user, pointsColumn);
SharedPointAdditionJournal.AdditionResult result = SharedPointAdditionJournal.forTable(plugin.getMysql())
.add(operationId, user.getUUID(), pointsColumn, amount, System.currentTimeMillis());
confirmed = true;
return new AddResult(true, result.total());
} catch (SQLException failure) {
logFailure(failure);
return new AddResult(MutationOutcome.INDETERMINATE, 0);
} finally {
boolean refreshed = SharedMysqlCacheReconciler.tryInvalidateAndRefreshOnWorker(plugin, user.getUUID(), pointsColumn);
if (placeholders != null) {
var cache = plugin.getUserManager().getDataManager().getUserDataCache().get(uuid);
boolean available = false;
if (cache != null) synchronized (cache) {
available = refreshed && confirmed && cache.hasPublishedStorageSnapshot();
}
placeholders.finishSharedPointDebit(uuid, confirmed, available);
}
discardPointsCache(user, pointsColumn);
}
}
@@ -222,36 +209,18 @@ final class SharedMysqlPointMutator {
AddResult removeCommittedFromColumn(VotingPluginUser user, int amount, String operationId, String pointsColumn) {
if (operationId == null || operationId.isEmpty()) return new AddResult(false, 0);
var placeholders = plugin.getPlaceholders();
UUID uuid = UUID.fromString(user.getUUID());
if (placeholders != null) placeholders.beginSharedPointDebit(uuid);
AddResult outcome = new AddResult(MutationOutcome.INDETERMINATE, 0);
boolean refreshed;
drainCache(user, pointsColumn);
try {
drainCache(user, pointsColumn);
SharedPointAdditionJournal.AdditionResult result = SharedPointAdditionJournal.forTable(plugin.getMysql())
.subtract(operationId, user.getUUID(), pointsColumn, amount, System.currentTimeMillis());
outcome = new AddResult(true, result.total());
return new AddResult(true, result.total());
} catch (SQLException failure) {
if (failure instanceof SharedPointAdditionJournal.DebitRejectedException) {
outcome = new AddResult(MutationOutcome.REJECTED, 0);
} else {
logFailure(failure);
outcome = new AddResult(MutationOutcome.INDETERMINATE, 0);
}
logFailure(failure);
return new AddResult(failure instanceof SharedPointAdditionJournal.DebitRejectedException
? MutationOutcome.REJECTED : MutationOutcome.INDETERMINATE, 0);
} finally {
refreshed = SharedMysqlCacheReconciler.tryInvalidateAndRefreshOnWorker(plugin, user.getUUID(), pointsColumn);
if (placeholders != null) {
var cache = plugin.getUserManager().getDataManager().getUserDataCache().get(uuid);
boolean available = false;
if (cache != null) synchronized (cache) {
available = refreshed && outcome.outcome() != MutationOutcome.INDETERMINATE
&& cache.hasPublishedStorageSnapshot();
}
placeholders.finishSharedPointDebit(uuid, outcome.outcome() != MutationOutcome.INDETERMINATE, available);
}
discardPointsCache(user, pointsColumn);
}
return new AddResult(outcome.outcome(), outcome.total(), refreshed);
}
/** Looks up a completed retry before its Bukkit receive event is dispatched. */
@@ -357,20 +326,7 @@ final class SharedMysqlPointMutator {
boolean set(VotingPluginUser user, int value, boolean async) {
String pointsColumn = user.getPointsPath();
var placeholders = plugin.getPlaceholders();
Consumer<Boolean> admission = placeholders == null ? null
: placeholders.sharedPointAdmissionCompletion(UUID.fromString(user.getUUID()));
boolean accepted = run(() -> {
boolean settled = false;
try {
setAbsolute(user, value, pointsColumn);
settled = true;
} finally {
if (admission != null) admission.accept(settled);
}
}, async);
if (!accepted && admission != null) admission.accept(false);
return accepted;
return run(() -> setAbsolute(user, value, pointsColumn), async);
}
boolean setCommitted(VotingPluginUser user, int value) {
@@ -542,40 +498,41 @@ final class SharedMysqlPointMutator {
org.bukkit.entity.Player approvalPlayer = targetPlayer != null ? targetPlayer : sourcePlayer;
String sourcePoints = source.getPointsPath();
String targetPoints = target.getPointsPath();
var reservationPublication = beginPointPublication(source);
try {
plugin.getTimer().execute(() -> {
MySQL table = plugin.getMysql();
String transferId = UUID.randomUUID().toString();
String owner = UUID.randomUUID().toString();
SharedPointTransferJournal prepared = null;
boolean known = true;
boolean reserved = false;
PointTransferResult failed = PointTransferResult.UNAVAILABLE;
try {
drainCache(source);
drainCache(target);
prepared = SharedPointTransferJournal.forTable(table);
recoverTransfers(plugin, prepared);
known = false;
reserved = prepared.reserve(transferId, source.getUUID(), sourcePoints, debitAmount,
target.getUUID(), debitAmount, System.currentTimeMillis());
known = true;
failed = PointTransferResult.INSUFFICIENT_POINTS;
} catch (SQLException failure) {
known |= failure instanceof SharedPointTransferJournal.PreparationFailure;
logFailure(failure);
} catch (RuntimeException cacheFailure) {
plugin.debug(cacheFailure);
} finally {
boolean refreshed = SharedMysqlCacheReconciler.tryInvalidateAndRefreshOnWorker(plugin, source.getUUID(), sourcePoints);
finishPointPublication(reservationPublication, source, sourcePoints, known, refreshed);
}
if (!reserved) {
completeOnBukkit(sourcePlayer, completion, failed);
completeOnBukkit(sourcePlayer, completion, PointTransferResult.UNAVAILABLE);
return;
}
MySQL table = plugin.getMysql();
String transferId = UUID.randomUUID().toString();
String owner = UUID.randomUUID().toString();
SharedPointTransferJournal journal;
try {
journal = SharedPointTransferJournal.forTable(table);
recoverTransfers(plugin, journal);
if (!journal.reserve(transferId, source.getUUID(), sourcePoints, debitAmount, target.getUUID(),
debitAmount, System.currentTimeMillis())) {
completeOnBukkit(sourcePlayer, completion, PointTransferResult.INSUFFICIENT_POINTS);
return;
}
// The source cache may have been recreated while the reservation was being
// committed. Invalidate its points after the durable debit, before any later
// dump can restore the pre-debit balance.
discardPointsCache(source, sourcePoints);
} catch (SQLException failure) {
// An acknowledgement/confirmation failure can follow a committed
// reservation debit. Never allow a cache recreated during the unknown
// outcome to flush the pre-debit source balance over it.
discardPointsCache(source, sourcePoints);
logFailure(failure);
completeOnBukkit(sourcePlayer, completion, PointTransferResult.UNAVAILABLE);
return;
}
SharedPointTransferJournal journal = prepared;
/*
* Do not claim the reservation until the Bukkit approval task has actually
@@ -605,7 +562,6 @@ final class SharedMysqlPointMutator {
// No reservation exists when the initial persistence task is rejected.
// Still complete the command contract on the source entity lane.
plugin.debug(schedulingFailure);
finishPointPublication(reservationPublication, source, sourcePoints, true, false);
completeOnBukkit(sourcePlayer, completion, PointTransferResult.UNAVAILABLE);
}
}
@@ -618,7 +574,8 @@ final class SharedMysqlPointMutator {
System.currentTimeMillis());
if (claim == SharedPointTransferJournal.ClaimOutcome.NOT_CLAIMED) {
try {
refundReservedWithPublication(source, journal, transferId, sourcePoints, debitAmount);
journal.refundReserved(transferId, source.getUUID(), sourcePoints, debitAmount);
discardPointsCache(source, sourcePoints);
} catch (SQLException failure) {
logFailure(failure);
}
@@ -756,7 +713,10 @@ final class SharedMysqlPointMutator {
} catch (SQLException markerFailure) {
boolean refunded = false;
try {
refunded = refundClaimedWithPublication(source, journal, transferId, sourcePoints, debitAmount);
refunded = journal.refundHookStarted(transferId, source.getUUID(), sourcePoints, debitAmount);
if (refunded) {
discardPointsCache(source, sourcePoints);
}
} catch (SQLException refundFailure) {
logFailure(refundFailure);
}
@@ -776,24 +736,17 @@ final class SharedMysqlPointMutator {
int debitAmount,
Consumer<PointTransferResult> completion, SharedPointTransferJournal journal, String transferId, String owner,
String sourcePoints, String targetPoints, Integer approvedAmount) {
var sourcePublication = beginPointPublication(source);
var targetPublication = beginPointPublication(target);
boolean known = false;
PointTransferResult result;
try {
// The hook may have recreated either cache while it ran on Bukkit.
drainCache(target);
SharedPointTransferJournal.SettlementOutcome outcome;
try {
drainCache(target);
outcome = journal.settleWithConfirmation(transferId, owner, source.getUUID(), sourcePoints,
target.getUUID(), targetPoints, debitAmount, approvedAmount);
known = outcome != SharedPointTransferJournal.SettlementOutcome.INDETERMINATE;
} finally {
boolean sourceRefreshed = SharedMysqlCacheReconciler.tryInvalidateAndRefreshOnWorker(plugin, source.getUUID(), sourcePoints);
boolean targetRefreshed = SharedMysqlCacheReconciler.tryInvalidateAndRefreshOnWorker(plugin, target.getUUID(), targetPoints);
finishPointPublication(sourcePublication, source, sourcePoints, known, sourceRefreshed);
finishPointPublication(targetPublication, target, targetPoints, known, targetRefreshed);
discardPointsCache(source, sourcePoints);
discardPointsCache(target, targetPoints);
}
result = outcome == SharedPointTransferJournal.SettlementOutcome.COMPLETED ? PointTransferResult.SUCCESS
: outcome == SharedPointTransferJournal.SettlementOutcome.REFUNDED ? PointTransferResult.CANCELLED
@@ -807,29 +760,14 @@ final class SharedMysqlPointMutator {
completeOnBukkit(sourcePlayer, completion, result);
}
private boolean refundReservedWithPublication(VotingPluginUser source, SharedPointTransferJournal journal,
String transferId, String sourcePoints, int debitAmount) throws SQLException {
var publication = beginPointPublication(source);
boolean known = false;
try {
boolean refunded = journal.refundReserved(transferId, source.getUUID(), sourcePoints, debitAmount);
known = true;
return refunded;
} catch (SQLException failure) {
known = failure instanceof SharedPointTransferJournal.PreparationFailure;
throw failure;
} finally {
boolean refreshed = SharedMysqlCacheReconciler.tryInvalidateAndRefreshOnWorker(plugin, source.getUUID(), sourcePoints);
finishPointPublication(publication, source, sourcePoints, known, refreshed);
}
}
private void refundReservedAfterSchedulingFailure(VotingPluginUser source, org.bukkit.entity.Player sourcePlayer,
Consumer<PointTransferResult> completion,
SharedPointTransferJournal journal, String transferId, String sourcePoints, int debitAmount,
RuntimeException failure) {
try {
refundReservedWithPublication(source, journal, transferId, sourcePoints, debitAmount);
if (journal.refundReserved(transferId, source.getUUID(), sourcePoints, debitAmount)) {
discardPointsCache(source, sourcePoints);
}
} catch (SQLException refundFailure) {
logFailure(refundFailure);
}
@@ -845,23 +783,24 @@ final class SharedMysqlPointMutator {
// HOOK_STARTED is safe to compensate because the approval task has not
// been submitted yet. A RESERVED row is handled by its normal refund.
if (journal.markCompensating(transferId)) {
refunded = refundClaimedWithPublication(source, journal, transferId, sourcePoints, debitAmount);
refunded = journal.refundHookStarted(transferId, source.getUUID(), sourcePoints, debitAmount);
} else {
refunded = refundReservedWithPublication(source, journal, transferId, sourcePoints, debitAmount);
refunded = journal.refundReserved(transferId, source.getUUID(), sourcePoints, debitAmount);
}
} catch (SQLException markerFailure) {
// A lost marker acknowledgement may still have committed. Both refund
// operations are idempotent and cover either durable pre-hook state.
try {
refunded = refundClaimedWithPublication(source, journal, transferId, sourcePoints, debitAmount);
refunded = journal.refundHookStarted(transferId, source.getUUID(), sourcePoints, debitAmount);
if (!refunded) {
refunded = refundReservedWithPublication(source, journal, transferId, sourcePoints, debitAmount);
refunded = journal.refundReserved(transferId, source.getUUID(), sourcePoints, debitAmount);
}
} catch (SQLException refundFailure) {
logFailure(refundFailure);
}
logFailure(markerFailure);
}
if (refunded) discardPointsCache(source, sourcePoints);
if (!refunded) {
rememberPendingCompensationMarker(plugin, transferId);
logIndeterminateClaim(transferId);
@@ -876,32 +815,19 @@ final class SharedMysqlPointMutator {
completeOnBukkit(sourcePlayer, completion, PointTransferResult.UNAVAILABLE);
}
private boolean refundClaimedWithPublication(VotingPluginUser source, SharedPointTransferJournal journal,
String transferId, String sourcePoints, int debitAmount) throws SQLException {
var publication = beginPointPublication(source);
boolean known = false;
try {
boolean refunded = journal.refundHookStarted(transferId, source.getUUID(), sourcePoints, debitAmount);
known = true;
return refunded;
} catch (SQLException refundFailure) {
known = refundFailure instanceof SharedPointTransferJournal.PreparationFailure;
throw refundFailure;
} finally {
// A later guarded fallback or refill cannot erase an earlier ambiguous write.
boolean refreshed = SharedMysqlCacheReconciler.tryInvalidateAndRefreshOnWorker(plugin, source.getUUID(), sourcePoints);
finishPointPublication(publication, source, sourcePoints, known, refreshed);
}
}
void refundClaimedAfterSchedulingFailure(VotingPluginUser source, org.bukkit.entity.Player sourcePlayer,
Consumer<PointTransferResult> completion,
SharedPointTransferJournal journal, String transferId, String sourcePoints, int debitAmount,
RuntimeException failure) {
try {
refundClaimedWithPublication(source, journal, transferId, sourcePoints, debitAmount);
journal.refundHookStarted(transferId, source.getUUID(), sourcePoints, debitAmount);
} catch (SQLException refundFailure) {
logFailure(refundFailure);
} finally {
// The refund may have committed even when its acknowledgement and
// confirmation read both failed. Invalidate a cache recreated after the
// original debit so it cannot later overwrite either durable outcome.
discardPointsCache(source, sourcePoints);
}
plugin.debug(failure);
completeOnBukkit(sourcePlayer, completion, PointTransferResult.UNAVAILABLE);
@@ -1064,12 +990,9 @@ final class SharedMysqlPointMutator {
enum MutationOutcome { CONFIRMED, REJECTED, INDETERMINATE }
record AddResult(MutationOutcome outcome, int total, boolean sourceRefreshed) {
AddResult(MutationOutcome outcome, int total) {
this(outcome, total, false);
}
record AddResult(MutationOutcome outcome, int total) {
AddResult(boolean success, int total) {
this(success ? MutationOutcome.CONFIRMED : MutationOutcome.INDETERMINATE, total, false);
this(success ? MutationOutcome.CONFIRMED : MutationOutcome.INDETERMINATE, total);
}
boolean success() { return outcome == MutationOutcome.CONFIRMED; }
}
@@ -1079,29 +1002,21 @@ final class SharedMysqlPointMutator {
}
private boolean setAbsolute(VotingPluginUser user, int value, String points) {
var publication = beginPointPublication(user);
boolean known = true;
try {
drainCache(user, points);
MySQL table = plugin.getMysql();
String sql = "UPDATE " + table.qi(table.getTableName()) + " SET " + table.qi(points)
+ " = ? WHERE " + table.qi("uuid")
+ (table.getDbType() == DbType.POSTGRESQL ? " = ?::uuid" : " = ?");
try (Connection connection = requireConnection(table);
PreparedStatement statement = connection.prepareStatement(sql)) {
statement.setInt(1, value);
statement.setString(2, user.getUUID());
known = false;
int affected = statement.executeUpdate();
known = true;
return affected == 1;
} catch (SQLException failure) {
logFailure(failure);
return false;
}
drainCache(user, points);
MySQL table = plugin.getMysql();
String sql = "UPDATE " + table.qi(table.getTableName()) + " SET " + table.qi(points)
+ " = ? WHERE " + table.qi("uuid")
+ (table.getDbType() == DbType.POSTGRESQL ? " = ?::uuid" : " = ?");
try (Connection connection = requireConnection(table);
PreparedStatement statement = connection.prepareStatement(sql)) {
statement.setInt(1, value);
statement.setString(2, user.getUUID());
return statement.executeUpdate() == 1;
} catch (SQLException failure) {
logFailure(failure);
return false;
} finally {
boolean refreshed = SharedMysqlCacheReconciler.tryInvalidateAndRefreshOnWorker(plugin, user.getUUID(), points);
finishPointPublication(publication, user, points, known, refreshed);
discardPointsCache(user, points);
}
}
@@ -1186,27 +1101,6 @@ final class SharedMysqlPointMutator {
* deliberately not discarded here because it is a distinct, later write and
* the generic absolute-value API cannot provide cross-server atomic semantics.
*/
private com.bencodez.votingplugin.placeholders.PlaceHolders beginPointPublication(VotingPluginUser user) {
var placeholders = plugin.getPlaceholders();
if (placeholders != null) placeholders.beginSharedPointDebit(UUID.fromString(user.getUUID()));
return placeholders;
}
private void finishPointPublication(com.bencodez.votingplugin.placeholders.PlaceHolders placeholders,
VotingPluginUser user, String column, boolean known, boolean refreshed) {
if (placeholders == null) return;
UUID uuid = UUID.fromString(user.getUUID());
var caches = plugin.getUserManager().getDataManager().getUserDataCache();
var cache = caches.get(uuid);
boolean available = false;
if (cache != null) synchronized (cache) {
available = known && refreshed && caches.get(uuid) == cache && cache.hasPublishedStorageSnapshot()
&& column.equals(user.getPointsPath())
&& plugin.isEnabled() && plugin.getPlaceholders() == placeholders;
}
placeholders.finishSharedPointDebit(uuid, known, available);
}
private void discardPointsCache(VotingPluginUser user) {
discardPointsCache(user, user.getPointsPath());
}
@@ -28,14 +28,6 @@ import com.bencodez.simpleapi.sql.mysql.DbType;
* settlement is a second short, idempotent transaction.</p>
*/
final class SharedPointTransferJournal {
/** Positive proof that this invocation did not attempt a points write. */
static final class PreparationFailure extends SQLException {
private static final long serialVersionUID = 1L;
PreparationFailure(SQLException cause) {
super(cause.getMessage(), cause.getSQLState(), cause.getErrorCode(), cause);
}
}
private static final String RESERVED = "RESERVED";
private static final String HOOK_STARTED = "HOOK_STARTED";
/*
@@ -152,59 +144,51 @@ final class SharedPointTransferJournal {
*/
boolean reserve(String transferId, String sourceUuid, String sourcePointsColumn, int debitPoints, String targetUuid,
int requestedCreditPoints, long now) throws SQLException {
boolean pointWriteAttempted = false;
try {
TransferRow existing = find(transferId);
if (existing != null) {
return existing.matches(sourceUuid, targetUuid, debitPoints, requestedCreditPoints)
&& !REFUNDED.equals(existing.state);
}
TransferRow existing = find(transferId);
if (existing != null) {
return existing.matches(sourceUuid, targetUuid, debitPoints, requestedCreditPoints)
&& !REFUNDED.equals(existing.state);
}
String insert = "INSERT INTO " + qiJournal() + " (" + qi("transfer_id") + ", " + qi("source_uuid")
+ ", " + qi("source_points_column") + ", " + qi("target_uuid") + ", " + qi("debit_points")
+ ", " + qi("requested_credit_points") + ", " + qi("state") + ", " + qi("created_at")
+ ") VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
String points = qi(sourcePointsColumn);
String debit = "UPDATE " + qi(table.getTableName()) + " SET " + points + " = " + points
+ " - ? WHERE " + qi("uuid") + uuidCast() + " AND " + points + " >= ?";
try (Connection connection = connection()) {
connection.setAutoCommit(false);
try (PreparedStatement insertStatement = connection.prepareStatement(insert);
PreparedStatement debitStatement = connection.prepareStatement(debit)) {
insertStatement.setString(1, transferId);
insertStatement.setString(2, sourceUuid);
insertStatement.setString(3, sourcePointsColumn);
insertStatement.setString(4, targetUuid);
insertStatement.setInt(5, debitPoints);
insertStatement.setInt(6, requestedCreditPoints);
insertStatement.setString(7, RESERVED);
insertStatement.setLong(8, now);
insertStatement.executeUpdate();
String insert = "INSERT INTO " + qiJournal() + " (" + qi("transfer_id") + ", " + qi("source_uuid")
+ ", " + qi("source_points_column") + ", " + qi("target_uuid") + ", " + qi("debit_points")
+ ", " + qi("requested_credit_points") + ", " + qi("state") + ", " + qi("created_at")
+ ") VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
String points = qi(sourcePointsColumn);
String debit = "UPDATE " + qi(table.getTableName()) + " SET " + points + " = " + points
+ " - ? WHERE " + qi("uuid") + uuidCast() + " AND " + points + " >= ?";
try (Connection connection = connection()) {
connection.setAutoCommit(false);
try (PreparedStatement insertStatement = connection.prepareStatement(insert);
PreparedStatement debitStatement = connection.prepareStatement(debit)) {
insertStatement.setString(1, transferId);
insertStatement.setString(2, sourceUuid);
insertStatement.setString(3, sourcePointsColumn);
insertStatement.setString(4, targetUuid);
insertStatement.setInt(5, debitPoints);
insertStatement.setInt(6, requestedCreditPoints);
insertStatement.setString(7, RESERVED);
insertStatement.setLong(8, now);
insertStatement.executeUpdate();
debitStatement.setInt(1, debitPoints);
debitStatement.setString(2, sourceUuid);
debitStatement.setInt(3, debitPoints);
pointWriteAttempted = true;
if (debitStatement.executeUpdate() != 1) {
connection.rollback();
return false;
}
return commitAndConfirm(connection, transferId, RESERVED);
} catch (SQLException failure) {
rollback(connection);
if (isDuplicate(failure)) {
closeQuietly(connection);
TransferRow duplicate = find(transferId);
return duplicate != null && duplicate.matches(sourceUuid, targetUuid, debitPoints,
requestedCreditPoints) && !REFUNDED.equals(duplicate.state);
}
throw failure;
debitStatement.setInt(1, debitPoints);
debitStatement.setString(2, sourceUuid);
debitStatement.setInt(3, debitPoints);
if (debitStatement.executeUpdate() != 1) {
connection.rollback();
return false;
}
return commitAndConfirm(connection, transferId, RESERVED);
} catch (SQLException failure) {
rollback(connection);
if (isDuplicate(failure)) {
closeQuietly(connection);
TransferRow duplicate = find(transferId);
return duplicate != null && duplicate.matches(sourceUuid, targetUuid, debitPoints,
requestedCreditPoints) && !REFUNDED.equals(duplicate.state);
}
throw failure;
}
} catch (SQLException failure) {
if (failure instanceof PreparationFailure) throw failure;
if (!pointWriteAttempted) throw new PreparationFailure(failure);
throw failure;
}
}
@@ -302,50 +286,42 @@ final class SharedPointTransferJournal {
*/
boolean refundReserved(String transferId, String sourceUuid, String sourcePointsColumn, int debitPoints)
throws SQLException {
boolean pointWriteAttempted = false;
try {
if (!isSafeColumn(sourcePointsColumn)) return false;
String select = "SELECT " + qi("state") + " FROM " + qiJournal() + " WHERE " + qi("transfer_id")
+ " = ? FOR UPDATE";
String points = qi(sourcePointsColumn);
String refund = "UPDATE " + qi(table.getTableName()) + " SET " + points + " = " + points
+ " + ? WHERE " + qi("uuid") + uuidCast();
String update = "UPDATE " + qiJournal() + " SET " + qi("state") + " = ? WHERE " + qi("transfer_id")
+ " = ?";
try (Connection connection = connection()) {
connection.setAutoCommit(false);
try (PreparedStatement selectStatement = connection.prepareStatement(select)) {
selectStatement.setString(1, transferId);
try (ResultSet result = selectStatement.executeQuery()) {
if (!result.next() || !RESERVED.equals(result.getString(1))) {
connection.rollback();
return false;
}
}
}
try (PreparedStatement refundStatement = connection.prepareStatement(refund)) {
refundStatement.setInt(1, debitPoints);
refundStatement.setString(2, sourceUuid);
pointWriteAttempted = true;
if (refundStatement.executeUpdate() != 1) {
if (!isSafeColumn(sourcePointsColumn)) return false;
String select = "SELECT " + qi("state") + " FROM " + qiJournal() + " WHERE " + qi("transfer_id")
+ " = ? FOR UPDATE";
String points = qi(sourcePointsColumn);
String refund = "UPDATE " + qi(table.getTableName()) + " SET " + points + " = " + points
+ " + ? WHERE " + qi("uuid") + uuidCast();
String update = "UPDATE " + qiJournal() + " SET " + qi("state") + " = ? WHERE " + qi("transfer_id")
+ " = ?";
try (Connection connection = connection()) {
connection.setAutoCommit(false);
try (PreparedStatement selectStatement = connection.prepareStatement(select)) {
selectStatement.setString(1, transferId);
try (ResultSet result = selectStatement.executeQuery()) {
if (!result.next() || !RESERVED.equals(result.getString(1))) {
connection.rollback();
return false;
}
}
try (PreparedStatement updateStatement = connection.prepareStatement(update)) {
updateStatement.setString(1, REFUNDED);
updateStatement.setString(2, transferId);
if (updateStatement.executeUpdate() != 1) {
connection.rollback();
return false;
}
}
return commitAndConfirm(connection, transferId, REFUNDED);
}
} catch (SQLException failure) {
if (failure instanceof PreparationFailure) throw failure;
if (!pointWriteAttempted) throw new PreparationFailure(failure);
throw failure;
try (PreparedStatement refundStatement = connection.prepareStatement(refund)) {
refundStatement.setInt(1, debitPoints);
refundStatement.setString(2, sourceUuid);
if (refundStatement.executeUpdate() != 1) {
connection.rollback();
return false;
}
}
try (PreparedStatement updateStatement = connection.prepareStatement(update)) {
updateStatement.setString(1, REFUNDED);
updateStatement.setString(2, transferId);
if (updateStatement.executeUpdate() != 1) {
connection.rollback();
return false;
}
}
return commitAndConfirm(connection, transferId, REFUNDED);
}
}
@@ -364,7 +340,6 @@ final class SharedPointTransferJournal {
+ " + ? WHERE " + qi("uuid") + uuidCast();
String update = "UPDATE " + qiJournal() + " SET " + qi("state") + " = ? WHERE " + qi("transfer_id")
+ " = ?";
boolean pointWriteAttempted = false;
try (Connection connection = connection()) {
connection.setAutoCommit(false);
try (PreparedStatement selectStatement = connection.prepareStatement(select)) {
@@ -388,7 +363,6 @@ final class SharedPointTransferJournal {
try (PreparedStatement refundStatement = connection.prepareStatement(refund)) {
refundStatement.setInt(1, debitPoints);
refundStatement.setString(2, sourceUuid);
pointWriteAttempted = true;
if (refundStatement.executeUpdate() != 1) {
connection.rollback();
return false;
@@ -404,7 +378,6 @@ final class SharedPointTransferJournal {
}
return commitAndConfirm(connection, transferId, REFUNDED);
} catch (SQLException failure) {
if (!pointWriteAttempted) throw new PreparationFailure(failure);
throw failure;
}
}
@@ -2,11 +2,7 @@ package com.bencodez.votingplugin.user;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.UUID;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import com.bencodez.votingplugin.placeholders.PlaceholderPlayerPresence.LiveIdentity;
import java.util.UUID;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
@@ -26,8 +22,7 @@ import com.bencodez.votingplugin.topvoter.TopVoter;
* Manages VotingPlugin user operations and data.
*/
public class UserManager {
private VotingPluginMain plugin;
private final Set<UUID> warnedOfflineUuidPlayers = ConcurrentHashMap.newKeySet();
private VotingPluginMain plugin;
private boolean sharedPointTransferRecoveryScheduled;
/**
@@ -262,50 +257,18 @@ public class UserManager {
* Gets a VotingPluginUser by UUID.
* @param uuid the player UUID
* @return the VotingPluginUser
* @deprecated UUID-only lookups can be ambiguous in offline mode because Minecraft
* preserves name capitalization, while VotingPlugin derives its
* offline UUID from the player name lowercased with Locale.ROOT.
* Prefer {@link #getVotingPluginUser(UUID, String)} when both UUID
* and player name are available; supplying the name allows the
* existing offline UUID normalization. Use
* {@link #getVotingPluginUser(Player)} for an online player,
* {@link #getVotingPluginUser(OfflinePlayer)} when an offline
* player object with a known name is available, or
* {@link #getVotingPluginUser(String)} when only the name is known.
*/
@Deprecated
@SuppressWarnings("deprecation")
public VotingPluginUser getVotingPluginUser(UUID uuid) {
LiveIdentity identity = offlineLiveIdentity(uuid);
if (identity == null) return new VotingPluginUser(plugin, uuid);
VotingPluginUser user = new VotingPluginUser(plugin, identity.storageUuid(), false);
user.setPlayerName(identity.playerName());
warnOfflineUuidCorrection(uuid, identity);
return user;
return new VotingPluginUser(plugin, uuid);
}
/**
* Gets a VotingPluginUser by exact storage UUID with optional name loading.
* This overload preserves the supplied key for storage iteration, recovery
* and administrative operations, even when loadName is true.
* Gets a VotingPluginUser by UUID with optional name loading.
* @param uuid the player UUID
* @param loadName whether to load the player name
* @return the VotingPluginUser
* @deprecated UUID-only lookups can be ambiguous in offline mode because Minecraft
* preserves name capitalization, while VotingPlugin derives its
* offline UUID from the player name lowercased with Locale.ROOT.
* Prefer {@link #getVotingPluginUser(UUID, String)} when both UUID
* and player name are available; supplying the name allows the
* existing offline UUID normalization. Use
* {@link #getVotingPluginUser(Player)} for an online player,
* {@link #getVotingPluginUser(OfflinePlayer)} when an offline
* player object with a known name is available, or
* {@link #getVotingPluginUser(String)} when only the name is known.
* Retain this overload when the exact stored UUID and explicit
* name-loading behavior are required; name-aware alternatives
* may normalize the supplied identity in offline mode.
*/
@Deprecated
@SuppressWarnings("deprecation")
public VotingPluginUser getVotingPluginUser(UUID uuid, boolean loadName) {
return new VotingPluginUser(plugin, uuid, loadName);
@@ -322,24 +285,6 @@ public class UserManager {
return new VotingPluginUser(plugin, uuid, playerName);
}
/** Resolve only immutable live identity captured by the presence lifecycle. */
private LiveIdentity offlineLiveIdentity(UUID uuid) {
if (plugin.getOptions().isOnlineMode()) return null;
var presence = plugin.getPlaceholderPlayerPresence();
LiveIdentity identity = presence == null ? null : presence.liveIdentity(uuid);
if (identity == null || identity.serverUuid() == null || identity.storageUuid() == null
|| identity.playerName() == null || identity.playerName().isBlank()) return null;
return identity;
}
private void warnOfflineUuidCorrection(UUID uuid, LiveIdentity identity) {
if (!uuid.equals(identity.storageUuid()) && warnedOfflineUuidPlayers.add(identity.storageUuid())) {
plugin.getLogger().warning("Offline UUID compatibility workaround used for " + identity.playerName()
+ ". Server UUID: " + identity.serverUuid() + " -> VotingPlugin UUID: " + identity.storageUuid()
+ ". Applied for third-party compatibility: a plugin may be using the server UUID instead of VotingPlugin's UUID.");
}
}
/**
* Purges old players with no voting data.
*/
File diff suppressed because it is too large. Load diff
@@ -1,217 +0,0 @@
package com.bencodez.votingplugin.util;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HexFormat;
import java.util.Locale;
import java.util.Properties;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/** Memory-only admission for participating plugin generations sharing one server-data path in a JVM. */
public final class ServerDataPublicationFence {
private static final String PREFIX = "com.bencodez.votingplugin.ServerDataPublicationFence.owner.";
private static final int MAX_OWNERS = 1024;
private final Properties registry;
private final String key;
private final String generation;
private final AtomicBoolean retirementStarted = new AtomicBoolean();
private final java.util.concurrent.CompletableFuture<Void> retirementCompleted = new java.util.concurrent.CompletableFuture<>();
private final CompletableFuture<Long> processShutdownStarted = new CompletableFuture<>();
private final CompletableFuture<Void> processExitCompletion = new CompletableFuture<>();
private final AtomicBoolean processHookRemoved = new AtomicBoolean();
private volatile Runtime processRuntime;
private volatile Thread processHook;
/** Opt in during startup, before the JVM can begin invoking shutdown hooks. */
public synchronized void retainForProcessExit() {
if (processHook != null) return;
var runtime = Runtime.getRuntime();
var hook = new Thread(this::awaitProcessExit, "VotingPlugin-ServerData-Exit");
runtime.addShutdownHook(hook);
processRuntime = runtime;
processHook = hook;
processExitCompletion.whenComplete((ignored, failure) -> removeProcessHook());
}
/** The first disable entry fixes the deadline; retries cannot renew it. No caller wait. */
public void beginShutdown(long startedNanos) {
if (processShutdownStarted.complete(startedNanos) && processHook != null) {
CompletableFuture.delayedExecutor(remainingProcessWait(startedNanos), TimeUnit.NANOSECONDS)
.execute(this::removeProcessHook);
}
}
private static long remainingProcessWait(long startedNanos) {
long elapsed = Math.max(0L, System.nanoTime() - startedNanos);
return Math.max(0L, TimeUnit.SECONDS.toNanos(15) - elapsed);
}
private void awaitProcessExit() {
long exitStarted = System.nanoTime();
try {
long disableStarted = processShutdownStarted.get(remainingProcessWait(exitStarted), TimeUnit.NANOSECONDS);
long remaining = Math.min(remainingProcessWait(exitStarted), remainingProcessWait(disableStarted));
if (remaining > 0) processExitCompletion.get(remaining, TimeUnit.NANOSECONDS);
} catch (InterruptedException interrupted) {
Thread.currentThread().interrupt();
} catch (ExecutionException | TimeoutException pendingOrExpired) {
// Process exit is bounded. Timeout does not acknowledge publication or release a lease.
}
}
private void removeProcessHook() {
var hook = processHook;
if (hook == null || !processHookRemoved.compareAndSet(false, true)) return;
try { processRuntime.removeShutdownHook(hook); }
catch (IllegalStateException stopping) { /* The JVM is already invoking its hooks. */ }
}
private ServerDataPublicationFence(Properties registry, String key, String generation) {
this.registry = registry;
this.key = key;
this.generation = generation;
}
/** Runs before platform initialization and performs no filesystem operation or wait for storage. */
public static ServerDataPublicationFence beginGeneration(Path file) {
String identity = file.toAbsolutePath().normalize().toString();
if (DurableFiles.isWindowsName(System.getProperty("os.name", ""))) identity = identity.toLowerCase(Locale.ROOT);
String key;
try {
key = PREFIX + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256")
.digest(identity.getBytes(StandardCharsets.UTF_8)));
} catch (NoSuchAlgorithmException unavailable) { throw new IllegalStateException(unavailable); }
Properties registry = System.getProperties();
synchronized (registry) {
Object value = registry.get(key);
if (value != null) {
State previous = state(value);
if (previous.users != 0 || !previous.retiring)
throw new IllegalStateException("Previous server-data generation still owns storage work; replacement was not started");
} else if (registry.keySet().stream().filter(k -> k instanceof String s && s.startsWith(PREFIX)).count() >= MAX_OWNERS) {
throw new IllegalStateException("Server-data publication owner capacity is unavailable");
}
String generation = UUID.randomUUID().toString();
registry.setProperty(key, generation + ":0:false");
return new ServerDataPublicationFence(registry, key, generation);
}
}
/** Hold through the entire operation, including a blocked write or admitted shutdown handoff. */
public Lease acquire() {
synchronized (registry) {
State current = current();
if (current.users >= MAX_OWNERS) throw new IllegalStateException("Server-data publication admission is unavailable");
registry.setProperty(key, generation + ":" + (current.users + 1) + ":" + current.retiring);
return new Lease(this);
}
}
/** Existing operations/retries retain ownership; a successor requires zero outstanding leases. */
public void retire() {
boolean drained = false;
synchronized (registry) {
State current = state(registry.get(key));
if (generation.equals(current.generation)) {
registry.setProperty(key, generation + ":" + current.users + ":true");
drained = current.users == 0;
}
}
// Completion callbacks may remove a JVM hook; never run them under the registry monitor.
if (drained) processExitCompletion.complete(null);
}
/** Reserve before asynchronous admission; a failed stage never proves drain. */
public void retainUntilSuccessfulPublication(java.util.concurrent.CompletionStage<Void> publication) {
java.util.Objects.requireNonNull(publication);
Lease lease = acquire();
publication.whenComplete((ignored, failure) -> {
if (failure == null) lease.close();
});
}
/** Reserve before disable and release only after existing SDK writers actually terminate. */
public java.util.concurrent.CompletionStage<Void> retainUntilTermination(java.util.concurrent.ScheduledExecutorService[] writers) {
var snapshot = writers.clone();
if (!retirementStarted.compareAndSet(false, true)) return retirementCompleted.minimalCompletionStage();
Lease lease;
try { lease = acquire(); }
catch (RuntimeException | Error failure) { retirementStarted.set(false); throw failure; }
try {
Thread guardian = new Thread(() -> {
boolean interrupted = false;
try (lease) {
for (var writer : snapshot) {
if (writer == null) continue;
while (!writer.isTerminated()) {
try { writer.awaitTermination(100, java.util.concurrent.TimeUnit.MILLISECONDS); }
catch (InterruptedException ignored) { interrupted = true; }
}
}
} catch (RuntimeException | Error failure) {
retirementCompleted.completeExceptionally(failure);
return;
} finally { if (interrupted) Thread.currentThread().interrupt(); }
retirementCompleted.complete(null);
}, "VotingPlugin-server-data-retirement");
guardian.setDaemon(true);
guardian.start();
} catch (RuntimeException | Error failure) {
try { lease.close(); }
catch (RuntimeException | Error cleanupFailure) { if (cleanupFailure != failure) failure.addSuppressed(cleanupFailure); }
finally { retirementStarted.set(false); }
throw failure;
}
return retirementCompleted.minimalCompletionStage();
}
private State current() {
State current = state(registry.get(key));
if (registry != System.getProperties() || !generation.equals(current.generation))
throw new IllegalStateException("Server-data publication belongs to another generation");
return current;
}
private static State state(Object value) {
if (!(value instanceof String text) || text.length() > 64)
throw new IllegalStateException("Server-data publication ownership is invalid");
String[] fields = text.split(":", -1);
try {
if (fields.length != 3 || !UUID.fromString(fields[0]).toString().equals(fields[0])
|| !(fields[2].equals("true") || fields[2].equals("false"))) throw new IllegalArgumentException();
int users = Integer.parseInt(fields[1]);
if (users < 0 || users > MAX_OWNERS || !Integer.toString(users).equals(fields[1])) throw new IllegalArgumentException();
return new State(fields[0], users, Boolean.parseBoolean(fields[2]));
} catch (IllegalArgumentException invalid) {
throw new IllegalStateException("Server-data publication ownership is invalid");
}
}
private record State(String generation, int users, boolean retiring) { }
public static final class Lease implements AutoCloseable {
private final ServerDataPublicationFence owner;
private final AtomicBoolean closed = new AtomicBoolean();
private Lease(ServerDataPublicationFence owner) { this.owner = owner; }
@Override public void close() {
boolean drained;
synchronized (owner.registry) {
if (closed.get()) return;
State current = owner.current();
if (current.users <= 0) throw new IllegalStateException("Server-data publication ownership is invalid");
owner.registry.setProperty(owner.key, owner.generation + ":" + (current.users - 1) + ":" + current.retiring);
closed.set(true);
drained = current.retiring && current.users == 1;
}
if (drained) owner.processExitCompletion.complete(null);
}
}
}
@@ -13,12 +13,11 @@ public final class VoteTaskAdmission {
/**
* Attempts to submit a one-shot vote task without running it on the caller.
*
* @param executor bounded vote executor, or null before startup/after shutdown
* @param executor bounded vote executor
* @param task task to submit
* @return true when the task was admitted
*/
public static boolean trySubmit(ScheduledExecutorService executor, Runnable task) {
if (executor == null) return false;
try {
executor.submit(task);
return true;
@@ -30,14 +29,13 @@ public final class VoteTaskAdmission {
/**
* Attempts to schedule a one-shot vote task without blocking the caller.
*
* @param executor bounded vote executor, or null before startup/after shutdown
* @param executor bounded vote executor
* @param task task to schedule
* @param delay delay before execution
* @param unit delay unit
* @return true when the task was admitted
*/
public static boolean trySchedule(ScheduledExecutorService executor, Runnable task, long delay, TimeUnit unit) {
if (executor == null) return false;
try {
executor.schedule(task, delay, unit);
return true;
@@ -29,14 +29,6 @@ import com.bencodez.simpleapi.sql.mysql.DbType;
* arbitrary, non-idempotent side effects.</p>
*/
final class SharedMysqlPurchaseJournal {
/** Positive proof that this invocation did not attempt a points write. */
static final class PreparationFailure extends SQLException {
private static final long serialVersionUID = 1L;
PreparationFailure(SQLException cause) {
super(cause.getMessage(), cause.getSQLState(), cause.getErrorCode(), cause);
}
}
private static final String PENDING = "PENDING";
private static final String HOOK_STARTED = "HOOK_STARTED";
private static final String COMPENSATING = "COMPENSATING";
@@ -127,68 +119,60 @@ final class SharedMysqlPurchaseJournal {
/** Atomically records a pending purchase and conditionally charges it. */
boolean reserve(String purchaseId, String uuid, String pointsColumn, String limitColumn, int cost, int limit,
String limitGeneration, long limitGenerationExpiresAt, long now) throws SQLException {
boolean pointWriteAttempted = false;
try {
String insert = "INSERT INTO " + qiJournal() + " (" + qi("purchase_id") + ", " + qi("player_uuid")
+ ", " + qi("points_column") + ", " + qi("limit_column") + ", " + qi("cost") + ", "
+ qi("limit_value") + ", " + qi("limit_generation") + ", "
+ qi("limit_generation_expires_at") + ", " + qi("limit_epoch") + ", " + qi("state")
+ ", " + qi("created_at") + ") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
String points = qi(pointsColumn);
StringBuilder debit = new StringBuilder("UPDATE ").append(qi(table.getTableName())).append(" SET ")
.append(points).append(" = COALESCE(").append(points).append(", 0) - ?");
if (limitColumn != null) {
debit.append(", ").append(qi(limitColumn)).append(" = COALESCE(").append(qi(limitColumn))
.append(", 0) + 1");
}
debit.append(" WHERE ").append(qi("uuid")).append(uuidCast()).append(" AND COALESCE(").append(points)
.append(", 0) >= ?");
if (limitColumn != null) {
debit.append(" AND COALESCE(").append(qi(limitColumn)).append(", 0) < ?");
}
try (Connection connection = connection()) {
connection.setAutoCommit(false);
try {
Long limitEpoch = limitColumn == null ? null : lockLimitEpoch(connection, limitColumn);
try (PreparedStatement insertStatement = connection.prepareStatement(insert);
PreparedStatement debitStatement = connection.prepareStatement(debit.toString())) {
insertStatement.setString(1, purchaseId);
insertStatement.setString(2, uuid);
insertStatement.setString(3, pointsColumn);
insertStatement.setString(4, limitColumn);
insertStatement.setInt(5, cost);
if (limitColumn == null) insertStatement.setNull(6, java.sql.Types.INTEGER);
else insertStatement.setInt(6, limit);
if (limitGeneration == null) insertStatement.setNull(7, java.sql.Types.VARCHAR);
else insertStatement.setString(7, limitGeneration);
if (limitGenerationExpiresAt <= 0L) insertStatement.setNull(8, java.sql.Types.BIGINT);
else insertStatement.setLong(8, limitGenerationExpiresAt);
if (limitEpoch == null) insertStatement.setNull(9, java.sql.Types.BIGINT);
else insertStatement.setLong(9, limitEpoch.longValue());
insertStatement.setString(10, PENDING);
insertStatement.setLong(11, now);
insertStatement.executeUpdate();
String insert = "INSERT INTO " + qiJournal() + " (" + qi("purchase_id") + ", " + qi("player_uuid")
+ ", " + qi("points_column") + ", " + qi("limit_column") + ", " + qi("cost") + ", "
+ qi("limit_value") + ", " + qi("limit_generation") + ", "
+ qi("limit_generation_expires_at") + ", " + qi("limit_epoch") + ", " + qi("state")
+ ", " + qi("created_at") + ") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
String points = qi(pointsColumn);
StringBuilder debit = new StringBuilder("UPDATE ").append(qi(table.getTableName())).append(" SET ")
.append(points).append(" = COALESCE(").append(points).append(", 0) - ?");
if (limitColumn != null) {
debit.append(", ").append(qi(limitColumn)).append(" = COALESCE(").append(qi(limitColumn))
.append(", 0) + 1");
}
debit.append(" WHERE ").append(qi("uuid")).append(uuidCast()).append(" AND COALESCE(").append(points)
.append(", 0) >= ?");
if (limitColumn != null) {
debit.append(" AND COALESCE(").append(qi(limitColumn)).append(", 0) < ?");
}
try (Connection connection = connection()) {
connection.setAutoCommit(false);
try {
Long limitEpoch = limitColumn == null ? null : lockLimitEpoch(connection, limitColumn);
try (PreparedStatement insertStatement = connection.prepareStatement(insert);
PreparedStatement debitStatement = connection.prepareStatement(debit.toString())) {
insertStatement.setString(1, purchaseId);
insertStatement.setString(2, uuid);
insertStatement.setString(3, pointsColumn);
insertStatement.setString(4, limitColumn);
insertStatement.setInt(5, cost);
if (limitColumn == null) insertStatement.setNull(6, java.sql.Types.INTEGER);
else insertStatement.setInt(6, limit);
if (limitGeneration == null) insertStatement.setNull(7, java.sql.Types.VARCHAR);
else insertStatement.setString(7, limitGeneration);
if (limitGenerationExpiresAt <= 0L) insertStatement.setNull(8, java.sql.Types.BIGINT);
else insertStatement.setLong(8, limitGenerationExpiresAt);
if (limitEpoch == null) insertStatement.setNull(9, java.sql.Types.BIGINT);
else insertStatement.setLong(9, limitEpoch.longValue());
insertStatement.setString(10, PENDING);
insertStatement.setLong(11, now);
insertStatement.executeUpdate();
debitStatement.setInt(1, cost);
debitStatement.setString(2, uuid);
debitStatement.setInt(3, cost);
if (limitColumn != null) debitStatement.setInt(4, limit);
pointWriteAttempted = true;
if (debitStatement.executeUpdate() != 1) {
rollback(connection);
return false;
}
return commitAndConfirm(connection, purchaseId, PENDING);
debitStatement.setInt(1, cost);
debitStatement.setString(2, uuid);
debitStatement.setInt(3, cost);
if (limitColumn != null) debitStatement.setInt(4, limit);
if (debitStatement.executeUpdate() != 1) {
rollback(connection);
return false;
}
} catch (SQLException failure) {
rollback(connection);
throw failure;
return commitAndConfirm(connection, purchaseId, PENDING);
}
} catch (SQLException failure) {
rollback(connection);
throw failure;
}
} catch (SQLException failure) {
if (failure instanceof PreparationFailure) throw failure;
if (!pointWriteAttempted) throw new PreparationFailure(failure);
throw failure;
}
}
@@ -386,73 +370,65 @@ final class SharedMysqlPurchaseJournal {
private RefundedPurchase setTerminalDetails(String purchaseId, String terminalState, long now,
String... refundableStates)
throws SQLException {
boolean pointWriteAttempted = false;
try {
boolean refund = REFUNDED.equals(terminalState);
String refundedUuid = null;
String refundedPointsColumn = null;
String refundedLimitColumn = null;
String select = "SELECT " + qi("state") + ", " + qi("player_uuid") + ", " + qi("points_column")
+ ", " + qi("limit_column") + ", " + qi("cost") + ", " + qi("limit_generation") + ", "
+ qi("limit_generation_expires_at") + ", " + qi("limit_epoch") + " FROM " + qiJournal() + " WHERE "
+ qi("purchase_id") + " = ? FOR UPDATE";
try (Connection connection = connection()) {
connection.setAutoCommit(false);
try (PreparedStatement selectStatement = connection.prepareStatement(select)) {
selectStatement.setString(1, purchaseId);
try (ResultSet result = selectStatement.executeQuery()) {
if (!result.next()) {
rollback(connection);
return null;
}
String state = result.getString(1);
if (COMPLETED.equals(state) || REFUNDED.equals(state)) {
rollback(connection);
return terminalState.equals(state) ? new RefundedPurchase(null, null, null) : null;
}
if (refund && !isRefundableState(state, refundableStates)) {
rollback(connection);
return null;
}
if (!refund && !HOOK_STARTED.equals(state)) {
rollback(connection);
return null;
}
String uuid = result.getString(2);
String pointsColumn = result.getString(3);
String limitColumn = result.getString(4);
refundedUuid = uuid;
refundedPointsColumn = pointsColumn;
refundedLimitColumn = limitColumn;
int cost = result.getInt(5);
String limitGeneration = result.getString(6);
Long limitEpoch = nullableLong(result, 8);
if (refund) {
boolean refundLimit = shouldRefundLimit(connection, limitColumn, limitGeneration, limitEpoch);
pointWriteAttempted = true;
refund(connection, uuid, pointsColumn, limitColumn, cost, refundLimit);
}
}
}
String update = "UPDATE " + qiJournal() + " SET " + qi("state") + " = ? WHERE " + qi("purchase_id")
+ " = ?";
try (PreparedStatement updateStatement = connection.prepareStatement(update)) {
updateStatement.setString(1, terminalState);
updateStatement.setString(2, purchaseId);
if (updateStatement.executeUpdate() != 1) {
boolean refund = REFUNDED.equals(terminalState);
String refundedUuid = null;
String refundedPointsColumn = null;
String refundedLimitColumn = null;
String select = "SELECT " + qi("state") + ", " + qi("player_uuid") + ", " + qi("points_column")
+ ", " + qi("limit_column") + ", " + qi("cost") + ", " + qi("limit_generation") + ", "
+ qi("limit_generation_expires_at") + ", " + qi("limit_epoch") + " FROM " + qiJournal() + " WHERE "
+ qi("purchase_id") + " = ? FOR UPDATE";
try (Connection connection = connection()) {
connection.setAutoCommit(false);
try (PreparedStatement selectStatement = connection.prepareStatement(select)) {
selectStatement.setString(1, purchaseId);
try (ResultSet result = selectStatement.executeQuery()) {
if (!result.next()) {
rollback(connection);
return null;
}
String state = result.getString(1);
if (COMPLETED.equals(state) || REFUNDED.equals(state)) {
rollback(connection);
return terminalState.equals(state) ? new RefundedPurchase(null, null, null) : null;
}
if (refund && !isRefundableState(state, refundableStates)) {
rollback(connection);
return null;
}
if (!refund && !HOOK_STARTED.equals(state)) {
rollback(connection);
return null;
}
String uuid = result.getString(2);
String pointsColumn = result.getString(3);
String limitColumn = result.getString(4);
refundedUuid = uuid;
refundedPointsColumn = pointsColumn;
refundedLimitColumn = limitColumn;
int cost = result.getInt(5);
String limitGeneration = result.getString(6);
Long limitEpoch = nullableLong(result, 8);
if (refund) {
refund(connection, uuid, pointsColumn, limitColumn, cost,
shouldRefundLimit(connection, limitColumn, limitGeneration, limitEpoch));
}
}
if (!commitAndConfirm(connection, purchaseId, terminalState)) return null;
return refund ? new RefundedPurchase(refundedUuid, refundedPointsColumn, refundedLimitColumn)
: new RefundedPurchase(null, null, null);
} catch (SQLException failure) {
throw failure;
}
String update = "UPDATE " + qiJournal() + " SET " + qi("state") + " = ? WHERE " + qi("purchase_id")
+ " = ?";
try (PreparedStatement updateStatement = connection.prepareStatement(update)) {
updateStatement.setString(1, terminalState);
updateStatement.setString(2, purchaseId);
if (updateStatement.executeUpdate() != 1) {
rollback(connection);
return null;
}
}
if (!commitAndConfirm(connection, purchaseId, terminalState)) return null;
return refund ? new RefundedPurchase(refundedUuid, refundedPointsColumn, refundedLimitColumn)
: new RefundedPurchase(null, null, null);
} catch (SQLException failure) {
if (failure instanceof PreparationFailure) throw failure;
if (!pointWriteAttempted) throw new PreparationFailure(failure);
throw failure;
}
}
@@ -466,28 +442,20 @@ final class SharedMysqlPurchaseJournal {
private void refund(Connection connection, String uuid, String pointsColumn, String limitColumn, int cost,
boolean refundLimit) throws SQLException {
boolean pointWriteAttempted = false;
try {
if (!isSafeColumn(pointsColumn) || (limitColumn != null && !isSafeColumn(limitColumn))) {
throw new SQLException("Unsafe durable purchase column");
}
StringBuilder refund = new StringBuilder("UPDATE ").append(qi(table.getTableName())).append(" SET ")
.append(qi(pointsColumn)).append(" = ").append(qi(pointsColumn)).append(" + ?");
if (refundLimit) {
refund.append(", ").append(qi(limitColumn)).append(" = GREATEST(COALESCE(").append(qi(limitColumn))
.append(", 0) - 1, 0)");
}
refund.append(" WHERE ").append(qi("uuid")).append(uuidCast());
try (PreparedStatement statement = connection.prepareStatement(refund.toString())) {
statement.setInt(1, cost);
statement.setString(2, uuid);
pointWriteAttempted = true;
if (statement.executeUpdate() != 1) throw new SQLException("Purchase refund player missing");
}
} catch (SQLException failure) {
if (failure instanceof PreparationFailure) throw failure;
if (!pointWriteAttempted) throw new PreparationFailure(failure);
throw failure;
if (!isSafeColumn(pointsColumn) || (limitColumn != null && !isSafeColumn(limitColumn))) {
throw new SQLException("Unsafe durable purchase column");
}
StringBuilder refund = new StringBuilder("UPDATE ").append(qi(table.getTableName())).append(" SET ")
.append(qi(pointsColumn)).append(" = ").append(qi(pointsColumn)).append(" + ?");
if (refundLimit) {
refund.append(", ").append(qi(limitColumn)).append(" = GREATEST(COALESCE(").append(qi(limitColumn))
.append(", 0) - 1, 0)");
}
refund.append(" WHERE ").append(qi("uuid")).append(uuidCast());
try (PreparedStatement statement = connection.prepareStatement(refund.toString())) {
statement.setInt(1, cost);
statement.setString(2, uuid);
if (statement.executeUpdate() != 1) throw new SQLException("Purchase refund player missing");
}
}
@@ -186,24 +186,15 @@ public class VoteShopPurchaseService {
// or entity task runs could pair an old debit with a newly loaded reward.
FileConfiguration shopData = plugin.getShopFile().getData();
HashMap<String, String> placeholders = purchasePlaceholders(item);
var pointPlaceholders = plugin.getPlaceholders();
Consumer<Boolean> admission = pointPlaceholders == null ? null
: pointPlaceholders.sharedPointAdmissionCompletion(UUID.fromString(user.getUUID()));
try {
plugin.getTimer().execute(() -> {
try {
SharedPurchaseDebit debit;
boolean settled = false;
try {
synchronized (purchaseLock(user.getUUID())) {
// Sample the reset window beside the conditional debit. A queued
// persistence task may otherwise cross into a new limit period.
debit = reserveSharedMysqlPurchase(user, item,
limitGeneration(item, System.currentTimeMillis()));
}
settled = true;
} finally {
if (admission != null) admission.accept(settled);
synchronized (purchaseLock(user.getUUID())) {
// Sample the reset window beside the conditional debit. A queued
// persistence task may otherwise cross into a new limit period.
debit = reserveSharedMysqlPurchase(user, item,
limitGeneration(item, System.currentTimeMillis()));
}
if (debit.result() != VoteShopPurchaseResult.SUCCESS) {
completePurchaseResult(player, completion, debit.result());
@@ -216,7 +207,6 @@ public class VoteShopPurchaseService {
}
});
} catch (RuntimeException persistenceRejected) {
if (admission != null) admission.accept(false);
plugin.debug(persistenceRejected);
completeFailedPurchase(player, completion);
}
@@ -489,29 +479,20 @@ public class VoteShopPurchaseService {
}
private void refundCompensatingMysqlDebit(VotingPluginUser user, SharedPurchaseDebit debit) {
var publication = plugin.getPlaceholders();
UUID uuid = publication == null ? null : UUID.fromString(user.getUUID());
if (publication != null) publication.beginSharedPointDebit(uuid);
boolean known = false;
try {
debit.journal().refundCompensatingReward(debit.purchaseId());
known = true;
if (debit.journal().refundCompensatingReward(debit.purchaseId())) {
refreshPurchaseCache(user, debit.pointsColumn(), debit.limitColumn());
}
} catch (SQLException failure) {
known = failure instanceof SharedMysqlPurchaseJournal.PreparationFailure;
// A commit/confirmation failure is indeterminate: the refund transaction
// may have committed even though this worker could not observe its terminal
// journal state. Drop the affected snapshots before any later cache dump so
// a stale debit cannot overwrite a durable refund. Recovery will reconcile
// the journal state if the transaction did not commit.
refreshPurchaseCache(user, debit.pointsColumn(), debit.limitColumn());
plugin.getLogger().severe("Unable to refund an incomplete vote shop purchase: "
+ failure.getClass().getSimpleName());
plugin.debug(failure);
} finally {
try {
refreshPurchaseCache(user, debit.pointsColumn(), debit.limitColumn());
} finally {
if (publication != null) publication.finishSharedPointDebit(uuid, known, false);
}
}
}
@@ -757,50 +738,37 @@ public class VoteShopPurchaseService {
private SharedPurchaseDebit reserveSharedMysqlPurchase(VotingPluginUser user, VoteShopItem item,
LimitGeneration limitGeneration) {
var publication = plugin.getPlaceholders();
UUID pointUuid = UUID.fromString(user.getUUID());
if (publication != null) publication.beginSharedPointDebit(pointUuid);
boolean known = true;
try {
MySQL table = plugin.getMysql();
String pointsColumn = user.getPointsPath();
String limitColumn = item.getLimit() > 0 ? "VoteShopLimit" + item.getIdentifier() : null;
ensurePerServerPointsColumn(table, pointsColumn);
drainPurchaseCache(user, pointsColumn);
if (limitColumn != null) {
table.checkColumn(limitColumn, DataType.INTEGER);
}
try {
SharedMysqlPurchaseJournal journal = SharedMysqlPurchaseJournal.forTable(table);
String purchaseId = UUID.randomUUID().toString();
known = false;
boolean reserved = journal.reserve(purchaseId, user.getUUID(), pointsColumn, limitColumn, item.getCost(), item.getLimit(),
limitGeneration.value(), limitGeneration.expiresAt(), System.currentTimeMillis());
known = true;
if (reserved) {
// reserve() returns only after its transaction and connection are closed;
// NO_CACHE reads must not contend with its one-connection pool handle.
refreshPurchaseCache(user, pointsColumn, limitColumn);
return new SharedPurchaseDebit(VoteShopPurchaseResult.SUCCESS, journal, purchaseId, pointsColumn,
limitColumn);
}
} catch (SQLException failure) {
known |= failure instanceof SharedMysqlPurchaseJournal.PreparationFailure;
// reserve() can throw after its commit acknowledgement and confirmation
// both fail. The debit may therefore be durable even though this caller
// reports FAILED; drop snapshots recreated during that transaction so a
// later cache dump cannot restore the pre-reservation values.
refreshPurchaseCache(user, pointsColumn, limitColumn);
plugin.getLogger().severe("Unable to atomically debit vote shop points: "
+ failure.getClass().getSimpleName());
plugin.debug(failure);
return new SharedPurchaseDebit(VoteShopPurchaseResult.FAILED, null, null, null, null);
}
refreshPurchaseCache(user, pointsColumn, limitColumn);
return new SharedPurchaseDebit(sharedMysqlFailure(user, item, limitColumn), null, null, null, null);
} finally {
if (publication != null) publication.finishSharedPointDebit(pointUuid, known, false);
MySQL table = plugin.getMysql();
String pointsColumn = user.getPointsPath();
String limitColumn = item.getLimit() > 0 ? "VoteShopLimit" + item.getIdentifier() : null;
ensurePerServerPointsColumn(table, pointsColumn);
drainPurchaseCache(user, pointsColumn);
if (limitColumn != null) {
table.checkColumn(limitColumn, DataType.INTEGER);
}
try {
SharedMysqlPurchaseJournal journal = SharedMysqlPurchaseJournal.forTable(table);
String purchaseId = UUID.randomUUID().toString();
if (journal.reserve(purchaseId, user.getUUID(), pointsColumn, limitColumn, item.getCost(), item.getLimit(),
limitGeneration.value(), limitGeneration.expiresAt(), System.currentTimeMillis())) {
// reserve() returns only after its transaction and connection are closed;
// NO_CACHE reads must not contend with its one-connection pool handle.
refreshPurchaseCache(user, pointsColumn, limitColumn);
return new SharedPurchaseDebit(VoteShopPurchaseResult.SUCCESS, journal, purchaseId, pointsColumn,
limitColumn);
}
} catch (SQLException failure) {
// reserve() can throw after its commit acknowledgement and confirmation
// both fail. The debit may therefore be durable even though this caller
// reports FAILED; drop snapshots recreated during that transaction so a
// later cache dump cannot restore the pre-reservation values.
refreshPurchaseCache(user, pointsColumn, limitColumn);
plugin.getLogger().severe("Unable to atomically debit vote shop points: "
+ failure.getClass().getSimpleName());
plugin.debug(failure);
return new SharedPurchaseDebit(VoteShopPurchaseResult.FAILED, null, null, null, null);
}
return new SharedPurchaseDebit(sharedMysqlFailure(user, item, limitColumn), null, null, null, null);
}
/** The legacy cache path created server-suffixed points columns before direct SQL used them. */
+6 -17
View File
@@ -188,7 +188,6 @@ DebugLevel: NONE
GiveDefaultPermission: true
# If true, plugin will automatically generate votesites upon getting a vote
# Disable after setup; a small periodic console reminder warns while enabled.
AutoCreateVoteSites: true
# Geyser/Bedrock player support
@@ -212,14 +211,6 @@ UseVoteGUIMainCommand: false
# Does not backup MySQL data
CreateBackups: true
# Player root command and standalone player aliases; admin commands remain available.
# These settings require a server restart; /av reload does not change registration.
VoteCommandEnabled: true
# Root label without a slash or namespace; 1-64 letters, digits, underscores or hyphens.
# Reserved/invalid names use vote. A foreign bare-name conflict uses votingplugin:<name>.
# Standalone aliases such as /votegui and /vgui keep their existing names.
VoteCommandName: vote
# Load command aliases, such as /avgui
# Requires restart to take effect
LoadCommandAliases: true
@@ -451,14 +442,6 @@ VoteLogging:
# Tracks and displays top voters by time period
###########################################
# Hide only confirmed never-joined identities from top voter displays.
# Missing, unreadable or ambiguous history stays visible. Awards are unchanged.
# Presence checks are asynchronous; pending snapshots stay visible until refreshed.
# Evidence expires after 30 seconds. GUI, chat and placeholder views can show
# previously hidden rows while fresh checks are pending; stale negatives are not reused.
# At most 128 checks run at once, so a large expired board may need several refreshes.
HideTopVoterIfNotPlayedBefore: false
# Top voter blacklist
# Hide these names from top voter lists
BlackList:
@@ -1273,3 +1256,9 @@ DisableUpdateChecking: false
# Disable checking permissions on tab complete
# Could increase performance slightly, but probably not
DisableAdvancedTab: false
# Optional public vanilla villagers opening the existing voting-site menu.
# Enable and /av reload, then /av npc create <id> [name]. No Citizens required.
# Definitions live in VotingNPCs.json; disabling keeps them but removes live NPCs.
VotingNPCs:
Enabled: false
-4
View File
@@ -294,10 +294,6 @@ CHEST:
Lore: '&c&lBest: &c%Best%'
Amount: 1
# Separate read-only /vote streaks progression menu.
VoteStreaks:
Name: '&6Vote streaks'
VoteStreak:
Name: 'VoteStreak: %player%'
BackButton: false
+5 -3
View File
@@ -170,6 +170,8 @@ permissions:
description: Allows mod commands
VotingPlugin.Admin:
description: Allows admincommands
children:
VotingPlugin.Commands.AdminVote: true
VotingPlugin.TopVoter.Ignore:
description: Allows you to be exempt from top voter
VotingPlugin.NoRemind:
@@ -196,8 +198,8 @@ permissions:
description: Remind if player can vote on all votesites, rather than any
default: false
VotingPlugin.Commands.Vote.Streaks:
description: View your read-only vote streak progression
VotingPlugin.Commands.AdminVote.NPC:
description: Create, inspect, list and remove saved vanilla voting NPCs
default: op
children:
VotingPlugin.Commands.Vote: true
VotingPlugin.Commands.AdminVote: true
@@ -1,7 +1,4 @@
package com.bencodez.votingplugin.tests;
import com.bencodez.votingplugin.VotingPluginHooks;
import com.bencodez.votingplugin.VotingPluginMain;
package com.bencodez.votingplugin;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -1,8 +1,4 @@
package com.bencodez.votingplugin.tests;
import com.bencodez.votingplugin.tests.support.ReflectiveAccess;
import com.bencodez.votingplugin.VotingPluginMain;
package com.bencodez.votingplugin;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertFalse;
@@ -48,7 +44,7 @@ class VotingPluginMainBackendProxyPublicationTest {
setField(plugin, "bungeeSettings", settings);
when(settings.isUseBungeecoord()).thenReturn(true);
VotingPluginMainAccess.reloadBackendProxyRuntime(plugin, true, false);
plugin.reloadBackendProxyRuntime(true, false);
verify(active).reloadSharedTransportSecurity();
verify(active).reloadPresenceReporting();
@@ -67,7 +63,7 @@ class VotingPluginMainBackendProxyPublicationTest {
// Full-editor Control preparation reloads settings before this replacement
// can be validated or published. It must not reconfigure the live handler.
VotingPluginMainAccess.reloadBackendProxyRuntime(plugin, false, false);
plugin.reloadBackendProxyRuntime(false, false);
VotingPluginMain.BackendProxyRestart restart = restart(previous, replacement);
assertThrows(IllegalStateException.class, () -> plugin.completeBackendProxyHandlerRestart(restart));
@@ -83,7 +79,7 @@ class VotingPluginMainBackendProxyPublicationTest {
setField(plugin, "bungeeSettings", settings);
when(settings.isUseBungeecoord()).thenReturn(true);
VotingPluginMainAccess.reloadBackendProxyRuntime(plugin, false, false);
plugin.reloadBackendProxyRuntime(false, false);
assertNull(plugin.getBackendProxyHandler());
}
@@ -100,7 +96,7 @@ class VotingPluginMainBackendProxyPublicationTest {
Method load = VotingPluginMain.class.getDeclaredMethod("loadBungeeHandler");
load.setAccessible(true);
assertDoesNotThrow(() -> ReflectiveAccess.invoke(load, plugin, new Object[]{}));
assertDoesNotThrow(() -> load.invoke(plugin));
assertNull(plugin.getBackendProxyHandler());
}
@@ -161,7 +157,7 @@ class VotingPluginMainBackendProxyPublicationTest {
return null;
}).when(replacement).activatePresenceReporting();
VotingPluginMainAccess.publishBackendProxyHandler(plugin, null, replacement);
plugin.publishBackendProxyHandler(null, replacement);
assertSame(replacement, plugin.getBackendProxyHandler());
}
@@ -175,7 +171,7 @@ class VotingPluginMainBackendProxyPublicationTest {
.when(replacement).activatePresenceReporting();
org.junit.jupiter.api.Assertions.assertThrows(IllegalStateException.class,
() -> VotingPluginMainAccess.publishBackendProxyHandler(plugin, previous, replacement));
() -> plugin.publishBackendProxyHandler(previous, replacement));
assertSame(previous, plugin.getBackendProxyHandler());
verify(replacement).abortStagedInboundTo(previous);
@@ -272,7 +268,7 @@ class VotingPluginMainBackendProxyPublicationTest {
org.mockito.ArgumentMatchers.anyLong());
verify(previous, never()).close();
VotingPluginMainAccess.closePublishedPreviousBackendProxyHandler(plugin, previous, "after publication");
plugin.closePublishedPreviousBackendProxyHandler(previous, "after publication");
assertTrue(closed.await(1, TimeUnit.SECONDS));
assertTrue(closeThread.get().startsWith("VotingPlugin-Retired-Backend"));
}
@@ -336,7 +332,7 @@ class VotingPluginMainBackendProxyPublicationTest {
try {
org.junit.jupiter.api.Assertions.assertTimeoutPreemptively(java.time.Duration.ofMillis(250),
() -> VotingPluginMainAccess.closePublishedPreviousBackendProxyHandler(plugin, previous, "after publication"));
() -> plugin.closePublishedPreviousBackendProxyHandler(previous, "after publication"));
assertTrue(closeStarted.await(1, TimeUnit.SECONDS));
assertTrue(closeThread.get().startsWith("VotingPlugin-Retired-Backend"));
} finally {
@@ -709,7 +705,7 @@ class VotingPluginMainBackendProxyPublicationTest {
Constructor<VotingPluginMain.BackendProxyRestart> constructor = VotingPluginMain.BackendProxyRestart.class
.getDeclaredConstructor(BackendProxyHandler.class, BackendProxyHandler.class, boolean.class, boolean.class);
constructor.setAccessible(true);
return ReflectiveAccess.newInstance(constructor, new Object[]{previous, replacement, replacement == null, previousRequiresPreparation});
return constructor.newInstance(previous, replacement, replacement == null, previousRequiresPreparation);
}
private void setBackendProxyHandler(VotingPluginMain plugin, BackendProxyHandler handler) throws Exception {
@@ -719,13 +715,13 @@ class VotingPluginMainBackendProxyPublicationTest {
private void setField(VotingPluginMain plugin, String name, Object value) throws Exception {
Field field = VotingPluginMain.class.getDeclaredField(name);
field.setAccessible(true);
ReflectiveAccess.set(field, plugin, value);
field.set(plugin, value);
}
private void setRestartField(VotingPluginMain.BackendProxyRestart restart, String name, Object value)
throws Exception {
Field field = VotingPluginMain.BackendProxyRestart.class.getDeclaredField(name);
field.setAccessible(true);
ReflectiveAccess.set(field, restart, value);
field.set(restart, value);
}
}
@@ -1,6 +1,4 @@
package com.bencodez.votingplugin.tests;
import com.bencodez.votingplugin.VotingPluginMain;
package com.bencodez.votingplugin;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.*;
@@ -147,18 +145,18 @@ class VotingPluginMainPlaceholderPresenceTest {
verify(plugin, times(2)).captureOnlineTopVoterIgnore(any(), any());
}
@Test
void offlineStorageIdentityWinsDuringColdPresenceRefresh() {
void cachedStorageIdentityWinsDuringColdPresenceRefresh() {
Player player = mock(Player.class);
UuidLookup lookup = mock(UuidLookup.class);
UUID bukkitUuid = UUID.randomUUID();
UUID storageUuid = UUID.randomUUID();
when(player.getName()).thenReturn("Player");
when(player.getUniqueId()).thenReturn(bukkitUuid);
when(lookup.getUUIDWithoutStorage("Player")).thenReturn(storageUuid.toString());
when(lookup.getCachedUUID("Player")).thenReturn(storageUuid.toString());
try (var uuidLookup = mockStatic(UuidLookup.class)) {
uuidLookup.when(UuidLookup::getInstance).thenReturn(lookup);
assertEquals(storageUuid, VotingPluginMainAccess.placeholderStorageUuid(player, false));
assertEquals(storageUuid, VotingPluginMain.placeholderStorageUuid(player, false));
}
}
@@ -169,11 +167,11 @@ class VotingPluginMainPlaceholderPresenceTest {
UUID bukkitUuid = UUID.randomUUID();
when(player.getName()).thenReturn("Player");
when(player.getUniqueId()).thenReturn(bukkitUuid);
when(lookup.getUUIDWithoutStorage("Player")).thenReturn("");
when(lookup.getCachedUUID("Player")).thenReturn("");
try (var uuidLookup = mockStatic(UuidLookup.class)) {
uuidLookup.when(UuidLookup::getInstance).thenReturn(lookup);
assertEquals(bukkitUuid, VotingPluginMainAccess.placeholderStorageUuid(player, false));
assertEquals(bukkitUuid, VotingPluginMain.placeholderStorageUuid(player, false));
}
}
@@ -186,7 +184,7 @@ class VotingPluginMainPlaceholderPresenceTest {
try (var uuidLookup = mockStatic(UuidLookup.class)) {
uuidLookup.when(UuidLookup::getInstance).thenReturn(lookup);
assertEquals(bukkitUuid, VotingPluginMainAccess.placeholderStorageUuid(player, true));
assertEquals(bukkitUuid, VotingPluginMain.placeholderStorageUuid(player, true));
}
}
}
@@ -1,10 +1,4 @@
package com.bencodez.votingplugin.tests.backendproxy;
import com.bencodez.votingplugin.tests.backendproxy.cache.ProcessedVoteCacheAccess;
import com.bencodez.votingplugin.tests.support.ReflectiveAccess;
import com.bencodez.votingplugin.backendproxy.BackendOrderedVoteOverflowQueue;
import com.bencodez.votingplugin.backendproxy.BackendProxyHandler;
package com.bencodez.votingplugin.backendproxy;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertNotNull;
@@ -203,7 +197,7 @@ class BackendProxyHandlerLifecycleTest {
TransportEnvelopeEncryption.Domain.PROXY_BACKEND, false));
BackendProxyTransportManager manager = (BackendProxyTransportManager) getField(handler, "transportManager");
BackendProxyTransport transport = method == BungeeMethod.REDIS
? new RedisBackendProxyTransport(plugin, ProcessedVoteCacheAccess.create())
? new RedisBackendProxyTransport(plugin, new ProcessedVoteCache())
: new MqttBackendProxyTransport(plugin);
setField(transport, "authenticator", SharedTransportEnvelopeAuthenticator.load(keyFile,
Mode.COMPATIBILITY));
@@ -239,7 +233,7 @@ class BackendProxyHandlerLifecycleTest {
setField(handler, "method", BungeeMethod.REDIS);
setField(handler, "sharedTransportMode", Mode.COMPATIBILITY);
setField(handler, "communicationEncryptionEnabled", false);
RedisBackendProxyTransport transport = new RedisBackendProxyTransport(plugin, ProcessedVoteCacheAccess.create());
RedisBackendProxyTransport transport = new RedisBackendProxyTransport(plugin, new ProcessedVoteCache());
SharedTransportEnvelopeAuthenticator original = SharedTransportEnvelopeAuthenticator.load(
dataDirectory.resolve("secretkey.key"), Mode.COMPATIBILITY);
setField(transport, "authenticator", original);
@@ -273,7 +267,7 @@ class BackendProxyHandlerLifecycleTest {
setField(handler, "communicationEncryption", originalEncryption);
BackendProxyTransportManager manager = (BackendProxyTransportManager) getField(handler, "transportManager");
BackendProxyTransport transport = method == BungeeMethod.REDIS
? new RedisBackendProxyTransport(plugin, ProcessedVoteCacheAccess.create())
? new RedisBackendProxyTransport(plugin, new ProcessedVoteCache())
: new MqttBackendProxyTransport(plugin);
SharedTransportEnvelopeAuthenticator originalAuthenticator =
SharedTransportEnvelopeAuthenticator.load(keyFile, Mode.REQUIRED);
@@ -304,7 +298,7 @@ class BackendProxyHandlerLifecycleTest {
handler.activateInboundMessages();
Runnable localDispatch = mock(Runnable.class);
BackendProxyHandlerAccess.dispatchIncomingAfterPublication(handler,
handler.dispatchIncomingAfterPublication(
JsonEnvelope.builder(VotingPluginWire.SUB_BUNGEE_TIME_CHANGE).build(), localDispatch);
verify(scheduler).runTaskAsynchronously(plugin, localDispatch);
@@ -344,9 +338,9 @@ class BackendProxyHandlerLifecycleTest {
return null;
}).when(router).handleOrderedVote(any(JsonEnvelope.class), any());
BackendProxyHandlerAccess.dispatchIncomingAfterPublication(handler, voteEnvelope, mock(Runnable.class));
BackendProxyHandlerAccess.dispatchIncomingAfterPublication(handler, updateEnvelope, mock(Runnable.class));
BackendProxyHandlerAccess.dispatchIncomingAfterPublication(handler, onlineEnvelope, mock(Runnable.class));
handler.dispatchIncomingAfterPublication(voteEnvelope, mock(Runnable.class));
handler.dispatchIncomingAfterPublication(updateEnvelope, mock(Runnable.class));
handler.dispatchIncomingAfterPublication(onlineEnvelope, mock(Runnable.class));
assertEquals(1, asyncTasks.size(), "only the head of the ordered vote lane should be scheduled");
@@ -397,9 +391,9 @@ class BackendProxyHandlerLifecycleTest {
return null;
}).when(router).handleOrderedVote(eq(release), any());
BackendProxyHandlerAccess.dispatchIncomingAfterPublication(handler, blockedVote, mock(Runnable.class));
BackendProxyHandlerAccess.dispatchIncomingAfterPublication(handler, release, mock(Runnable.class));
BackendProxyHandlerAccess.dispatchIncomingAfterPublication(handler, secondRelease, mock(Runnable.class));
handler.dispatchIncomingAfterPublication(blockedVote, mock(Runnable.class));
handler.dispatchIncomingAfterPublication(release, mock(Runnable.class));
handler.dispatchIncomingAfterPublication(secondRelease, mock(Runnable.class));
assertEquals(2, asyncTasks.size(), "only one durable release should use the bounded release worker");
asyncTasks.removeLast().run();
@@ -425,7 +419,7 @@ class BackendProxyHandlerLifecycleTest {
doThrow(new java.util.concurrent.RejectedExecutionException("stopping"))
.when(scheduler).runTaskAsynchronously(eq(plugin), any(Runnable.class));
BackendProxyHandlerAccess.dispatchIncomingAfterPublication(handler, release, mock(Runnable.class));
handler.dispatchIncomingAfterPublication(release, mock(Runnable.class));
verify(router, never()).handleOrderedVote(eq(release), any());
AtomicBoolean active = (AtomicBoolean) getField(handler, "durableReceiptReleaseActive");
@@ -488,8 +482,8 @@ class BackendProxyHandlerLifecycleTest {
"survival", UUID.randomUUID(), VotingPluginWire.SUB_VOTE);
when(router.isValidReceiptRelease(release)).thenReturn(true);
BackendProxyHandlerAccess.dispatchIncomingAfterPublication(handler, olderVote, mock(Runnable.class));
BackendProxyHandlerAccess.dispatchIncomingAfterPublication(handler, release, mock(Runnable.class));
handler.dispatchIncomingAfterPublication(olderVote, mock(Runnable.class));
handler.dispatchIncomingAfterPublication(release, mock(Runnable.class));
@SuppressWarnings("unchecked")
ArrayDeque<JsonEnvelope> queued = (ArrayDeque<JsonEnvelope>) getField(handler, "orderedVoteDispatchQueue");
@@ -527,7 +521,7 @@ class BackendProxyHandlerLifecycleTest {
VotingPluginWire.vote("Player", UUID.randomUUID().toString(), "site", 10L,
true, true, "", voteId, false, false, 1, 1));
BackendProxyHandlerAccess.dispatchIncomingAfterPublication(handler, envelope, mock(Runnable.class));
handler.dispatchIncomingAfterPublication(envelope, mock(Runnable.class));
dispatch.get().run();
verifyNoInteractions(messages);
completion.get().accept(OrderedVoteOutcome.COMPLETE);
@@ -566,7 +560,7 @@ class BackendProxyHandlerLifecycleTest {
VotingPluginWire.voteDelayRejected("Player", UUID.randomUUID().toString(),
"site", true, voteId));
BackendProxyHandlerAccess.dispatchIncomingAfterPublication(handler, envelope, mock(Runnable.class));
handler.dispatchIncomingAfterPublication(envelope, mock(Runnable.class));
dispatch.get().run();
verifyNoInteractions(messages);
completion.get().accept(OrderedVoteOutcome.COMPLETE);
@@ -586,19 +580,19 @@ class BackendProxyHandlerLifecycleTest {
when(plugin.getLogger()).thenReturn(Logger.getLogger("ordered-overflow-test"));
BackendOrderedVoteOverflowQueue overflow = new BackendOrderedVoteOverflowQueue(plugin);
try {
BackendProxyHandler handler = new BackendProxyHandler(plugin, ProcessedVoteCacheAccess.create(), overflow);
BackendProxyHandler handler = new BackendProxyHandler(plugin, new ProcessedVoteCache(), overflow);
setField(handler, "messageRouter", mock(BackendProxyMessageRouter.class));
handler.activateInboundMessages();
for (int i = 0; i < BackendProxyHandlerAccess.MAX_ORDERED_VOTE_QUEUE + 1; i++) {
BackendProxyHandlerAccess.dispatchIncomingAfterPublication(handler, JsonEnvelope.builder(VotingPluginWire.SUB_VOTE)
for (int i = 0; i < BackendProxyHandler.MAX_ORDERED_VOTE_QUEUE + 1; i++) {
handler.dispatchIncomingAfterPublication(JsonEnvelope.builder(VotingPluginWire.SUB_VOTE)
.put(VotingPluginWire.K_VOTE_ID, new java.util.UUID(0L, i + 1L).toString()).build(),
mock(Runnable.class));
}
@SuppressWarnings("unchecked")
ArrayDeque<JsonEnvelope> queued = (ArrayDeque<JsonEnvelope>) getField(handler, "orderedVoteDispatchQueue");
assertEquals(BackendProxyHandlerAccess.MAX_ORDERED_VOTE_QUEUE, queued.size());
assertEquals(BackendProxyHandler.MAX_ORDERED_VOTE_QUEUE, queued.size());
assertEquals(1, overflow.size());
} finally {
overflow.close();
@@ -656,14 +650,14 @@ class BackendProxyHandlerLifecycleTest {
blocker.start();
assertTrue(locked.await(3, TimeUnit.SECONDS));
try {
BackendProxyHandler handler = new BackendProxyHandler(plugin, ProcessedVoteCacheAccess.create(), overflow);
BackendProxyHandler handler = new BackendProxyHandler(plugin, new ProcessedVoteCache(), overflow);
setField(handler, "messageRouter", mock(BackendProxyMessageRouter.class));
handler.activateInboundMessages();
for (int index = 0; index < BackendProxyHandlerAccess.MAX_ORDERED_VOTE_QUEUE; index++) {
BackendProxyHandlerAccess.dispatchIncomingAfterPublication(handler, JsonEnvelope.builder(VotingPluginWire.SUB_VOTE)
for (int index = 0; index < BackendProxyHandler.MAX_ORDERED_VOTE_QUEUE; index++) {
handler.dispatchIncomingAfterPublication(JsonEnvelope.builder(VotingPluginWire.SUB_VOTE)
.put("sequence", Integer.toString(index)).build(), mock(Runnable.class));
}
CompletableFuture<Void> admission = CompletableFuture.runAsync(() -> BackendProxyHandlerAccess.dispatchIncomingAfterPublication(handler,
CompletableFuture<Void> admission = CompletableFuture.runAsync(() -> handler.dispatchIncomingAfterPublication(
JsonEnvelope.builder(VotingPluginWire.SUB_VOTE).put("sequence", "overflow").build(),
mock(Runnable.class)));
admission.get(500, TimeUnit.MILLISECONDS);
@@ -690,7 +684,7 @@ class BackendProxyHandlerLifecycleTest {
when(plugin.getLogger()).thenReturn(Logger.getLogger("ordered-unreadable-test"));
BackendOrderedVoteOverflowQueue overflow = new BackendOrderedVoteOverflowQueue(plugin);
try {
assertFalse(BackendOrderedVoteOverflowQueueAccess.enqueue(overflow, JsonEnvelope.builder(VotingPluginWire.SUB_VOTE).build()));
assertFalse(overflow.enqueue(JsonEnvelope.builder(VotingPluginWire.SUB_VOTE).build()));
} finally {
overflow.close();
}
@@ -711,7 +705,7 @@ class BackendProxyHandlerLifecycleTest {
Files.writeString(queueFile, malformed);
BackendOrderedVoteOverflowQueue malformedQueue = new BackendOrderedVoteOverflowQueue(plugin);
try {
assertFalse(BackendOrderedVoteOverflowQueueAccess.enqueue(malformedQueue, JsonEnvelope.builder(VotingPluginWire.SUB_VOTE).build()));
assertFalse(malformedQueue.enqueue(JsonEnvelope.builder(VotingPluginWire.SUB_VOTE).build()));
} finally {
malformedQueue.close();
}
@@ -725,7 +719,7 @@ class BackendProxyHandlerLifecycleTest {
Files.writeString(queueFile, unsupported);
BackendOrderedVoteOverflowQueue unsupportedQueue = new BackendOrderedVoteOverflowQueue(plugin);
try {
assertFalse(BackendOrderedVoteOverflowQueueAccess.enqueue(unsupportedQueue, JsonEnvelope.builder(VotingPluginWire.SUB_VOTE).build()));
assertFalse(unsupportedQueue.enqueue(JsonEnvelope.builder(VotingPluginWire.SUB_VOTE).build()));
} finally {
unsupportedQueue.close();
}
@@ -740,7 +734,7 @@ class BackendProxyHandlerLifecycleTest {
BackendOrderedVoteOverflowQueue overflow = new BackendOrderedVoteOverflowQueue(plugin);
try {
Files.createDirectory(tempDir.resolve("BackendProxyVoteQueue.yml"));
assertFalse(BackendOrderedVoteOverflowQueueAccess.enqueue(overflow, JsonEnvelope.builder(VotingPluginWire.SUB_VOTE).build()));
assertFalse(overflow.enqueue(JsonEnvelope.builder(VotingPluginWire.SUB_VOTE).build()));
assertEquals(0, overflow.size());
} finally {
overflow.close();
@@ -750,7 +744,7 @@ class BackendProxyHandlerLifecycleTest {
@Test
void oversizedFailureHistoryStopsRecoveryWithoutDiscardingEvidence(@TempDir Path tempDir) throws Exception {
StringBuilder yaml = new StringBuilder("Envelopes: []\nFailedEnvelopes:\n");
for (int index = 0; index < BackendOrderedVoteOverflowQueueAccess.MAX_FAILED_ENTRIES + 20; index++) {
for (int index = 0; index < BackendOrderedVoteOverflowQueue.MAX_FAILED_ENTRIES + 20; index++) {
yaml.append("- failed-").append(index).append('\n');
}
Files.writeString(tempDir.resolve("BackendProxyVoteQueue.yml"), yaml);
@@ -759,8 +753,8 @@ class BackendProxyHandlerLifecycleTest {
when(plugin.getLogger()).thenReturn(Logger.getLogger("ordered-failure-bound-test"));
BackendOrderedVoteOverflowQueue overflow = new BackendOrderedVoteOverflowQueue(plugin);
try {
assertEquals(0, BackendOrderedVoteOverflowQueueAccess.failedSize(overflow));
assertFalse(BackendOrderedVoteOverflowQueueAccess.enqueue(overflow, JsonEnvelope.builder(VotingPluginWire.SUB_VOTE).build()));
assertEquals(0, overflow.failedSize());
assertFalse(overflow.enqueue(JsonEnvelope.builder(VotingPluginWire.SUB_VOTE).build()));
assertTrue(Files.readString(tempDir.resolve("BackendProxyVoteQueue.yml")).contains("failed-0"));
} finally {
overflow.close();
@@ -770,7 +764,7 @@ class BackendProxyHandlerLifecycleTest {
@Test
void fullFailureHistoryRejectsNextQuarantineWithoutEviction(@TempDir Path tempDir) throws Exception {
StringBuilder yaml = new StringBuilder("Envelopes: []\nFailedEnvelopes:\n");
for (int index = 0; index < BackendOrderedVoteOverflowQueueAccess.MAX_FAILED_ENTRIES; index++) {
for (int index = 0; index < BackendOrderedVoteOverflowQueue.MAX_FAILED_ENTRIES; index++) {
yaml.append("- failed-").append(index).append('\n');
}
Files.writeString(tempDir.resolve("BackendProxyVoteQueue.yml"), yaml);
@@ -779,10 +773,10 @@ class BackendProxyHandlerLifecycleTest {
when(plugin.getLogger()).thenReturn(Logger.getLogger("ordered-failure-capacity-test"));
BackendOrderedVoteOverflowQueue overflow = new BackendOrderedVoteOverflowQueue(plugin);
try {
assertFalse(BackendOrderedVoteOverflowQueueAccess.quarantineForShutdown(overflow, null, JsonEnvelope.builder(VotingPluginWire.SUB_VOTE)
assertFalse(overflow.quarantineForShutdown(null, JsonEnvelope.builder(VotingPluginWire.SUB_VOTE)
.put("sequence", "rejected").build()));
assertEquals(BackendOrderedVoteOverflowQueueAccess.MAX_FAILED_ENTRIES, BackendOrderedVoteOverflowQueueAccess.failedSize(overflow));
assertTrue(BackendOrderedVoteOverflowQueueAccess.isQuarantineCapacityExhausted(overflow));
assertEquals(BackendOrderedVoteOverflowQueue.MAX_FAILED_ENTRIES, overflow.failedSize());
assertTrue(overflow.isQuarantineCapacityExhausted());
@SuppressWarnings("unchecked")
ArrayDeque<String> failures = (ArrayDeque<String>) getField(overflow, "failedEntries");
assertEquals("failed-0", failures.peekFirst());
@@ -790,9 +784,9 @@ class BackendProxyHandlerLifecycleTest {
BukkitScheduler scheduler = mock(BukkitScheduler.class);
when(plugin.getBukkitScheduler()).thenReturn(scheduler);
BackendProxyHandler handler = new BackendProxyHandler(plugin, ProcessedVoteCacheAccess.create(), overflow);
BackendProxyHandler handler = new BackendProxyHandler(plugin, new ProcessedVoteCache(), overflow);
handler.activateInboundMessages();
BackendProxyHandlerAccess.dispatchIncomingAfterPublication(handler, JsonEnvelope.builder(VotingPluginWire.SUB_VOTE).build(),
handler.dispatchIncomingAfterPublication(JsonEnvelope.builder(VotingPluginWire.SUB_VOTE).build(),
mock(Runnable.class));
verify(scheduler, never()).runTaskAsynchronously(eq(plugin), any(Runnable.class));
} finally {
@@ -810,19 +804,19 @@ class BackendProxyHandlerLifecycleTest {
UUID.randomUUID().toString(), "site", 10L, true, true, "", voteId, false, false, 1, 1));
BackendOrderedVoteOverflowQueue overflow = new BackendOrderedVoteOverflowQueue(plugin);
try {
assertTrue(BackendOrderedVoteOverflowQueueAccess.quarantineForShutdown(overflow, null, vote));
assertTrue(overflow.quarantineForShutdown(null, vote));
long firstDeadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(3);
while (BackendOrderedVoteOverflowQueueAccess.failedSize(overflow) != 1 && System.nanoTime() < firstDeadline) Thread.sleep(10L);
assertEquals(1, BackendOrderedVoteOverflowQueueAccess.failedSize(overflow));
while (overflow.failedSize() != 1 && System.nanoTime() < firstDeadline) Thread.sleep(10L);
assertEquals(1, overflow.failedSize());
assertTrue(BackendOrderedVoteOverflowQueueAccess.enqueue(overflow, vote));
BackendOrderedVoteOverflowQueueAccess.PendingEnvelope retry = BackendOrderedVoteOverflowQueueAccess.peekDurable(overflow);
assertTrue(overflow.enqueue(vote));
BackendOrderedVoteOverflowQueue.PendingEnvelope retry = overflow.peekDurable();
assertNotNull(retry);
CompletableFuture<Boolean> quarantined = new CompletableFuture<>();
BackendOrderedVoteOverflowQueueAccess.quarantineAsync(overflow, retry, vote, quarantined::complete);
overflow.quarantineAsync(retry, vote, quarantined::complete);
assertTrue(quarantined.get(3, TimeUnit.SECONDS));
assertEquals(1, BackendOrderedVoteOverflowQueueAccess.failedSize(overflow));
assertEquals(1, overflow.failedSize());
assertEquals(0, overflow.size());
} finally {
overflow.close();
@@ -830,7 +824,7 @@ class BackendProxyHandlerLifecycleTest {
BackendOrderedVoteOverflowQueue recovered = new BackendOrderedVoteOverflowQueue(plugin);
try {
assertEquals(1, BackendOrderedVoteOverflowQueueAccess.failedSize(recovered));
assertEquals(1, recovered.failedSize());
assertEquals(0, recovered.size());
} finally {
recovered.close();
@@ -851,7 +845,7 @@ class BackendProxyHandlerLifecycleTest {
}).when(scheduler).runTaskAsynchronously(eq(plugin), any(Runnable.class));
BackendOrderedVoteOverflowQueue overflow = new BackendOrderedVoteOverflowQueue(plugin);
try {
BackendProxyHandler handler = new BackendProxyHandler(plugin, ProcessedVoteCacheAccess.create(), overflow);
BackendProxyHandler handler = new BackendProxyHandler(plugin, new ProcessedVoteCache(), overflow);
BackendProxyMessageRouter router = mock(BackendProxyMessageRouter.class);
setField(handler, "messageRouter", router);
AtomicInteger attempts = new AtomicInteger();
@@ -862,9 +856,9 @@ class BackendProxyHandlerLifecycleTest {
return null;
}).when(router).handleOrderedVote(any(JsonEnvelope.class), any());
handler.activateInboundMessages();
assertTrue(BackendOrderedVoteOverflowQueueAccess.enqueue(overflow, JsonEnvelope.builder(VotingPluginWire.SUB_VOTE)
assertTrue(overflow.enqueue(JsonEnvelope.builder(VotingPluginWire.SUB_VOTE)
.put("sequence", "failed").build()));
assertTrue(BackendOrderedVoteOverflowQueueAccess.enqueue(overflow, JsonEnvelope.builder(VotingPluginWire.SUB_VOTE)
assertTrue(overflow.enqueue(JsonEnvelope.builder(VotingPluginWire.SUB_VOTE)
.put("sequence", "next").build()));
Runnable first = asyncTasks.poll(3, TimeUnit.SECONDS);
assertNotNull(first);
@@ -876,7 +870,7 @@ class BackendProxyHandlerLifecycleTest {
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(3);
while (overflow.size() != 0 && System.nanoTime() < deadline) Thread.sleep(10);
assertEquals(0, overflow.size());
assertEquals(1, BackendOrderedVoteOverflowQueueAccess.failedSize(overflow));
assertEquals(1, overflow.failedSize());
assertTrue(Files.exists(tempDir.resolve("BackendProxyVoteQueue.yml")));
} finally {
overflow.close();
@@ -884,7 +878,7 @@ class BackendProxyHandlerLifecycleTest {
BackendOrderedVoteOverflowQueue recovered = new BackendOrderedVoteOverflowQueue(plugin);
try {
assertEquals(0, recovered.size());
assertEquals(1, BackendOrderedVoteOverflowQueueAccess.failedSize(recovered));
assertEquals(1, recovered.failedSize());
} finally {
recovered.close();
}
@@ -904,22 +898,22 @@ class BackendProxyHandlerLifecycleTest {
}).when(scheduler).runTaskAsynchronously(eq(plugin), any(Runnable.class));
BackendOrderedVoteOverflowQueue overflow = new BackendOrderedVoteOverflowQueue(plugin);
try {
BackendProxyHandler handler = new BackendProxyHandler(plugin, ProcessedVoteCacheAccess.create(), overflow);
BackendProxyHandler handler = new BackendProxyHandler(plugin, new ProcessedVoteCache(), overflow);
BackendProxyMessageRouter router = mock(BackendProxyMessageRouter.class);
setField(handler, "messageRouter", router);
doThrow(new IllegalStateException("partial reward")).when(router)
.handleOrderedVote(any(JsonEnvelope.class), any());
handler.activateInboundMessages();
BackendProxyHandlerAccess.dispatchIncomingAfterPublication(handler, JsonEnvelope.builder(VotingPluginWire.SUB_VOTE)
handler.dispatchIncomingAfterPublication(JsonEnvelope.builder(VotingPluginWire.SUB_VOTE)
.put("sequence", "failed").build(), mock(Runnable.class));
Runnable first = asyncTasks.poll(3, TimeUnit.SECONDS);
assertNotNull(first);
assertThrows(IllegalStateException.class, first::run);
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(3);
while (BackendOrderedVoteOverflowQueueAccess.failedSize(overflow) == 0 && System.nanoTime() < deadline) {
while (overflow.failedSize() == 0 && System.nanoTime() < deadline) {
Thread.sleep(10);
}
assertEquals(1, BackendOrderedVoteOverflowQueueAccess.failedSize(overflow));
assertEquals(1, overflow.failedSize());
assertEquals(0, overflow.size());
assertTrue(asyncTasks.isEmpty(), "failed reward must not be retried");
} finally {
@@ -953,13 +947,13 @@ class BackendProxyHandlerLifecycleTest {
});
assertTrue(occupied.await(3, TimeUnit.SECONDS));
try {
BackendProxyHandler handler = new BackendProxyHandler(plugin, ProcessedVoteCacheAccess.create(), overflow);
BackendProxyHandler handler = new BackendProxyHandler(plugin, new ProcessedVoteCache(), overflow);
BackendProxyMessageRouter router = mock(BackendProxyMessageRouter.class);
setField(handler, "messageRouter", router);
doThrow(new IllegalStateException("partial reward")).when(router)
.handleOrderedVote(any(JsonEnvelope.class), any());
handler.activateInboundMessages();
BackendProxyHandlerAccess.dispatchIncomingAfterPublication(handler, JsonEnvelope.builder(VotingPluginWire.SUB_VOTE)
handler.dispatchIncomingAfterPublication(JsonEnvelope.builder(VotingPluginWire.SUB_VOTE)
.put("sequence", "failed").build(), mock(Runnable.class));
Runnable first = asyncTasks.poll(3, TimeUnit.SECONDS);
assertNotNull(first);
@@ -972,7 +966,7 @@ class BackendProxyHandlerLifecycleTest {
BackendOrderedVoteOverflowQueue recovered = new BackendOrderedVoteOverflowQueue(plugin);
try {
assertEquals(0, recovered.size());
assertEquals(1, BackendOrderedVoteOverflowQueueAccess.failedSize(recovered));
assertEquals(1, recovered.failedSize());
} finally {
recovered.close();
}
@@ -986,29 +980,29 @@ class BackendProxyHandlerLifecycleTest {
when(plugin.getLogger()).thenReturn(Logger.getLogger("ordered-capacity-test"));
BackendOrderedVoteOverflowQueue overflow = new BackendOrderedVoteOverflowQueue(plugin);
try {
BackendProxyHandler handler = new BackendProxyHandler(plugin, ProcessedVoteCacheAccess.create(), overflow);
BackendProxyHandler handler = new BackendProxyHandler(plugin, new ProcessedVoteCache(), overflow);
handler.activateInboundMessages();
for (int index = 0; index < BackendProxyHandlerAccess.MAX_ORDERED_VOTE_QUEUE; index++) {
BackendProxyHandlerAccess.dispatchIncomingAfterPublication(handler, JsonEnvelope.builder(VotingPluginWire.SUB_VOTE)
for (int index = 0; index < BackendProxyHandler.MAX_ORDERED_VOTE_QUEUE; index++) {
handler.dispatchIncomingAfterPublication(JsonEnvelope.builder(VotingPluginWire.SUB_VOTE)
.put("sequence", Integer.toString(index)).build(), mock(Runnable.class));
}
for (int index = 0; index < BackendOrderedVoteOverflowQueueAccess.MAX_NORMAL_ENTRIES; index++) {
assertTrue(BackendOrderedVoteOverflowQueueAccess.enqueue(overflow, JsonEnvelope.builder(VotingPluginWire.SUB_VOTE)
.put("sequence", Integer.toString(index + BackendProxyHandlerAccess.MAX_ORDERED_VOTE_QUEUE))
.build(), BackendProxyHandlerAccess.MAX_ORDERED_VOTE_QUEUE));
for (int index = 0; index < BackendOrderedVoteOverflowQueue.MAX_NORMAL_ENTRIES; index++) {
assertTrue(overflow.enqueue(JsonEnvelope.builder(VotingPluginWire.SUB_VOTE)
.put("sequence", Integer.toString(index + BackendProxyHandler.MAX_ORDERED_VOTE_QUEUE))
.build(), BackendProxyHandler.MAX_ORDERED_VOTE_QUEUE));
}
assertFalse(BackendOrderedVoteOverflowQueueAccess.enqueue(overflow, JsonEnvelope.builder(VotingPluginWire.SUB_VOTE).build(),
BackendProxyHandlerAccess.MAX_ORDERED_VOTE_QUEUE));
assertFalse(overflow.enqueue(JsonEnvelope.builder(VotingPluginWire.SUB_VOTE).build(),
BackendProxyHandler.MAX_ORDERED_VOTE_QUEUE));
handler.close();
assertEquals(BackendProxyHandlerAccess.MAX_ORDERED_VOTE_QUEUE
+ BackendOrderedVoteOverflowQueueAccess.MAX_NORMAL_ENTRIES, overflow.size());
assertEquals(BackendProxyHandler.MAX_ORDERED_VOTE_QUEUE
+ BackendOrderedVoteOverflowQueue.MAX_NORMAL_ENTRIES, overflow.size());
} finally {
overflow.close();
}
BackendOrderedVoteOverflowQueue recovered = new BackendOrderedVoteOverflowQueue(plugin);
try {
assertEquals(BackendProxyHandlerAccess.MAX_ORDERED_VOTE_QUEUE
+ BackendOrderedVoteOverflowQueueAccess.MAX_NORMAL_ENTRIES, recovered.size());
assertEquals(BackendProxyHandler.MAX_ORDERED_VOTE_QUEUE
+ BackendOrderedVoteOverflowQueue.MAX_NORMAL_ENTRIES, recovered.size());
} finally {
recovered.close();
}
@@ -1028,7 +1022,7 @@ class BackendProxyHandlerLifecycleTest {
}).when(scheduler).runTaskAsynchronously(eq(plugin), any(Runnable.class));
BackendOrderedVoteOverflowQueue overflow = new BackendOrderedVoteOverflowQueue(plugin);
try {
BackendProxyHandler handler = new BackendProxyHandler(plugin, ProcessedVoteCacheAccess.create(), overflow);
BackendProxyHandler handler = new BackendProxyHandler(plugin, new ProcessedVoteCache(), overflow);
BackendProxyMessageRouter router = mock(BackendProxyMessageRouter.class);
setField(handler, "messageRouter", router);
AtomicInteger attempts = new AtomicInteger();
@@ -1039,7 +1033,7 @@ class BackendProxyHandlerLifecycleTest {
return null;
}).when(router).handleOrderedVote(any(JsonEnvelope.class), any());
handler.activateInboundMessages();
assertTrue(BackendOrderedVoteOverflowQueueAccess.enqueue(overflow, JsonEnvelope.builder(VotingPluginWire.SUB_VOTE_UPDATE).build()));
assertTrue(overflow.enqueue(JsonEnvelope.builder(VotingPluginWire.SUB_VOTE_UPDATE).build()));
Runnable first = asyncTasks.poll(3, TimeUnit.SECONDS);
assertNotNull(first, "durable head must wake the ordered lane");
@@ -1073,7 +1067,7 @@ class BackendProxyHandlerLifecycleTest {
}).when(scheduler).runTaskAsynchronously(eq(plugin), any(Runnable.class));
BackendOrderedVoteOverflowQueue overflow = new BackendOrderedVoteOverflowQueue(plugin);
try {
BackendProxyHandler handler = new BackendProxyHandler(plugin, ProcessedVoteCacheAccess.create(), overflow);
BackendProxyHandler handler = new BackendProxyHandler(plugin, new ProcessedVoteCache(), overflow);
BackendProxyMessageRouter router = mock(BackendProxyMessageRouter.class);
setField(handler, "messageRouter", router);
doAnswer(invocation -> {
@@ -1082,7 +1076,7 @@ class BackendProxyHandlerLifecycleTest {
return null;
}).when(router).handleOrderedVote(any(JsonEnvelope.class), any());
handler.activateInboundMessages();
assertTrue(BackendOrderedVoteOverflowQueueAccess.enqueue(overflow, JsonEnvelope.builder(VotingPluginWire.SUB_VOTE).build()));
assertTrue(overflow.enqueue(JsonEnvelope.builder(VotingPluginWire.SUB_VOTE).build()));
asyncTasks.poll(3, TimeUnit.SECONDS).run();
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(3);
while (overflow.size() != 0 && System.nanoTime() < deadline) Thread.sleep(10);
@@ -1124,11 +1118,11 @@ class BackendProxyHandlerLifecycleTest {
try {
overflow.close();
assertTrue(System.nanoTime() - started < TimeUnit.SECONDS.toNanos(4));
assertEquals(BackendOrderedVoteOverflowQueueAccess.CloseState.WAITING_TO_PERSIST, BackendOrderedVoteOverflowQueueAccess.closeState(overflow));
assertEquals(BackendOrderedVoteOverflowQueue.CloseState.WAITING_TO_PERSIST, overflow.closeState());
} finally {
release.countDown();
blocker.join(3_000L);
assertTrue(BackendOrderedVoteOverflowQueueAccess.awaitClose(overflow, 3_000L));
assertTrue(overflow.awaitClose(3_000L));
}
}
@@ -1143,7 +1137,7 @@ class BackendProxyHandlerLifecycleTest {
when(plugin.getDataFolder()).thenReturn(tempDir.toFile());
when(plugin.getLogger()).thenReturn(logger);
BackendOrderedVoteOverflowQueue overflow = new BackendOrderedVoteOverflowQueue(plugin);
assertTrue(BackendOrderedVoteOverflowQueueAccess.enqueue(overflow, JsonEnvelope.builder(VotingPluginWire.SUB_VOTE).put("sequence", "slow").build()));
assertTrue(overflow.enqueue(JsonEnvelope.builder(VotingPluginWire.SUB_VOTE).put("sequence", "slow").build()));
Object persistenceLock = getField(overflow, "persistenceWriteLock");
CountDownLatch locked = new CountDownLatch(1);
Thread blocker = new Thread(() -> {
@@ -1162,7 +1156,7 @@ class BackendProxyHandlerLifecycleTest {
overflow.close();
blocker.join(3_000L);
assertTrue(System.nanoTime() - started >= TimeUnit.SECONDS.toNanos(1));
assertEquals(BackendOrderedVoteOverflowQueueAccess.CloseState.COMPLETE, BackendOrderedVoteOverflowQueueAccess.closeState(overflow));
assertEquals(BackendOrderedVoteOverflowQueue.CloseState.COMPLETE, overflow.closeState());
assertFalse(logs.hasLevel(Level.SEVERE));
BackendOrderedVoteOverflowQueue recovered = new BackendOrderedVoteOverflowQueue(plugin);
@@ -1189,7 +1183,7 @@ class BackendProxyHandlerLifecycleTest {
BackendOrderedVoteOverflowQueue overflow = new BackendOrderedVoteOverflowQueue(plugin);
overflow.close();
assertEquals(BackendOrderedVoteOverflowQueueAccess.CloseState.FAILED, BackendOrderedVoteOverflowQueueAccess.closeState(overflow));
assertEquals(BackendOrderedVoteOverflowQueue.CloseState.FAILED, overflow.closeState());
assertTrue(logs.hasLevel(Level.SEVERE));
LogRecord failure = logs.records.stream()
.filter(record -> record.getLevel() == Level.SEVERE)
@@ -1229,9 +1223,9 @@ class BackendProxyHandlerLifecycleTest {
return null;
}).when(router).handleOrderedVote(any(JsonEnvelope.class), any());
handler.activateInboundMessages();
BackendProxyHandlerAccess.dispatchIncomingAfterPublication(handler, JsonEnvelope.builder(VotingPluginWire.SUB_VOTE_UPDATE)
handler.dispatchIncomingAfterPublication(JsonEnvelope.builder(VotingPluginWire.SUB_VOTE_UPDATE)
.put("sequence", "first").build(), mock(Runnable.class));
BackendProxyHandlerAccess.dispatchIncomingAfterPublication(handler, JsonEnvelope.builder(VotingPluginWire.SUB_VOTE)
handler.dispatchIncomingAfterPublication(JsonEnvelope.builder(VotingPluginWire.SUB_VOTE)
.put("sequence", "second").build(), mock(Runnable.class));
asyncTasks.removeFirst().run();
@@ -1252,12 +1246,12 @@ class BackendProxyHandlerLifecycleTest {
when(plugin.getLogger()).thenReturn(Logger.getLogger("ordered-shutdown-test"));
BackendOrderedVoteOverflowQueue overflow = new BackendOrderedVoteOverflowQueue(plugin);
try {
BackendProxyHandler handler = new BackendProxyHandler(plugin, ProcessedVoteCacheAccess.create(), overflow);
BackendProxyHandler handler = new BackendProxyHandler(plugin, new ProcessedVoteCache(), overflow);
BackendProxyTransportManager transport = mock(BackendProxyTransportManager.class);
setField(handler, "transportManager", transport);
handler.activateInboundMessages();
doAnswer(invocation -> {
BackendProxyHandlerAccess.dispatchIncomingAfterPublication(handler,
handler.dispatchIncomingAfterPublication(
JsonEnvelope.builder(VotingPluginWire.SUB_VOTE).build(), mock(Runnable.class));
return null;
}).when(transport).close();
@@ -1289,7 +1283,7 @@ class BackendProxyHandlerLifecycleTest {
}).when(scheduler).runTaskAsynchronously(eq(plugin), any(Runnable.class));
BackendOrderedVoteOverflowQueue overflow = new BackendOrderedVoteOverflowQueue(plugin);
try {
BackendProxyHandler handler = new BackendProxyHandler(plugin, ProcessedVoteCacheAccess.create(), overflow);
BackendProxyHandler handler = new BackendProxyHandler(plugin, new ProcessedVoteCache(), overflow);
BackendProxyMessageRouter router = mock(BackendProxyMessageRouter.class);
setField(handler, "messageRouter", router);
AtomicReference<java.util.function.Consumer<OrderedVoteOutcome>> completion = new AtomicReference<>();
@@ -1298,9 +1292,9 @@ class BackendProxyHandlerLifecycleTest {
return null;
}).when(router).handleOrderedVote(any(JsonEnvelope.class), any());
handler.activateInboundMessages();
BackendProxyHandlerAccess.dispatchIncomingAfterPublication(handler, JsonEnvelope.builder(VotingPluginWire.SUB_VOTE)
handler.dispatchIncomingAfterPublication(JsonEnvelope.builder(VotingPluginWire.SUB_VOTE)
.put("sequence", "active").build(), mock(Runnable.class));
BackendProxyHandlerAccess.dispatchIncomingAfterPublication(handler, JsonEnvelope.builder(VotingPluginWire.SUB_VOTE)
handler.dispatchIncomingAfterPublication(JsonEnvelope.builder(VotingPluginWire.SUB_VOTE)
.put("sequence", "later").build(), mock(Runnable.class));
asyncTasks.removeFirst().run();
CompletableFuture<Void> closing = CompletableFuture.runAsync(handler::close);
@@ -1329,7 +1323,7 @@ class BackendProxyHandlerLifecycleTest {
BackendOrderedVoteOverflowQueue overflow = new BackendOrderedVoteOverflowQueue(plugin);
AtomicReference<java.util.function.Consumer<OrderedVoteOutcome>> completion = new AtomicReference<>();
try {
BackendProxyHandler handler = new BackendProxyHandler(plugin, ProcessedVoteCacheAccess.create(), overflow);
BackendProxyHandler handler = new BackendProxyHandler(plugin, new ProcessedVoteCache(), overflow);
BackendProxyMessageRouter router = mock(BackendProxyMessageRouter.class);
setField(handler, "messageRouter", router);
doAnswer(invocation -> {
@@ -1337,26 +1331,26 @@ class BackendProxyHandlerLifecycleTest {
return null;
}).when(router).handleOrderedVote(any(JsonEnvelope.class), any());
handler.activateInboundMessages();
BackendProxyHandlerAccess.dispatchIncomingAfterPublication(handler, JsonEnvelope.builder(VotingPluginWire.SUB_VOTE)
handler.dispatchIncomingAfterPublication(JsonEnvelope.builder(VotingPluginWire.SUB_VOTE)
.put("sequence", "active").build(), mock(Runnable.class));
BackendProxyHandlerAccess.dispatchIncomingAfterPublication(handler, JsonEnvelope.builder(VotingPluginWire.SUB_VOTE)
handler.dispatchIncomingAfterPublication(JsonEnvelope.builder(VotingPluginWire.SUB_VOTE)
.put("sequence", "later").build(), mock(Runnable.class));
asyncTasks.removeFirst().run();
CompletableFuture.runAsync(handler::close).get(3, TimeUnit.SECONDS);
long quarantineDeadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(3);
while (BackendOrderedVoteOverflowQueueAccess.failedSize(overflow) != 1 && System.nanoTime() < quarantineDeadline) Thread.sleep(10L);
assertEquals(1, BackendOrderedVoteOverflowQueueAccess.failedSize(overflow));
while (overflow.failedSize() != 1 && System.nanoTime() < quarantineDeadline) Thread.sleep(10L);
assertEquals(1, overflow.failedSize());
assertEquals(1, overflow.size());
completion.get().accept(OrderedVoteOutcome.COMPLETE);
assertEquals(1, BackendOrderedVoteOverflowQueueAccess.failedSize(overflow));
assertEquals(1, overflow.failedSize());
assertEquals(1, overflow.size());
} finally {
overflow.close();
}
BackendOrderedVoteOverflowQueue recovered = new BackendOrderedVoteOverflowQueue(plugin);
try {
assertEquals(1, BackendOrderedVoteOverflowQueueAccess.failedSize(recovered));
assertEquals(1, recovered.failedSize());
assertEquals(1, recovered.size());
} finally {
recovered.close();
@@ -1378,32 +1372,32 @@ class BackendProxyHandlerLifecycleTest {
BackendOrderedVoteOverflowQueue overflow = new BackendOrderedVoteOverflowQueue(plugin);
AtomicReference<java.util.function.Consumer<OrderedVoteOutcome>> completion = new AtomicReference<>();
try {
BackendProxyHandler handler = new BackendProxyHandler(plugin, ProcessedVoteCacheAccess.create(), overflow);
BackendProxyHandler handler = new BackendProxyHandler(plugin, new ProcessedVoteCache(), overflow);
BackendProxyMessageRouter router = mock(BackendProxyMessageRouter.class);
setField(handler, "messageRouter", router);
doAnswer(invocation -> {
completion.set(invocation.getArgument(1));
return null;
}).when(router).handleOrderedVote(any(JsonEnvelope.class), any());
assertTrue(BackendOrderedVoteOverflowQueueAccess.enqueue(overflow, JsonEnvelope.builder(VotingPluginWire.SUB_VOTE)
assertTrue(overflow.enqueue(JsonEnvelope.builder(VotingPluginWire.SUB_VOTE)
.put("sequence", "active").build()));
handler.activateInboundMessages();
asyncTasks.removeFirst().run();
CompletableFuture.runAsync(handler::close).get(3, TimeUnit.SECONDS);
long quarantineDeadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(3);
while (BackendOrderedVoteOverflowQueueAccess.failedSize(overflow) != 1 && System.nanoTime() < quarantineDeadline) Thread.sleep(10L);
assertEquals(1, BackendOrderedVoteOverflowQueueAccess.failedSize(overflow));
while (overflow.failedSize() != 1 && System.nanoTime() < quarantineDeadline) Thread.sleep(10L);
assertEquals(1, overflow.failedSize());
assertEquals(0, overflow.size());
completion.get().accept(OrderedVoteOutcome.COMPLETE);
assertEquals(1, BackendOrderedVoteOverflowQueueAccess.failedSize(overflow));
assertEquals(1, overflow.failedSize());
assertEquals(0, overflow.size());
} finally {
overflow.close();
}
BackendOrderedVoteOverflowQueue recovered = new BackendOrderedVoteOverflowQueue(plugin);
try {
assertEquals(1, BackendOrderedVoteOverflowQueueAccess.failedSize(recovered));
assertEquals(1, recovered.failedSize());
assertEquals(0, recovered.size());
} finally {
recovered.close();
@@ -1425,12 +1419,12 @@ class BackendProxyHandlerLifecycleTest {
JsonEnvelope first = JsonEnvelope.builder(VotingPluginWire.SUB_VOTE).put("sequence", "1").build();
JsonEnvelope second = JsonEnvelope.builder(VotingPluginWire.SUB_VOTE_UPDATE).put("sequence", "2").build();
BackendProxyHandlerAccess.dispatchIncomingAfterPublication(previous, first, mock(Runnable.class));
BackendProxyHandlerAccess.dispatchIncomingAfterPublication(previous, second, mock(Runnable.class));
previous.dispatchIncomingAfterPublication(first, mock(Runnable.class));
previous.dispatchIncomingAfterPublication(second, mock(Runnable.class));
previous.completeOrderedVoteHandoff(replacement);
JsonEnvelope late = JsonEnvelope.builder(VotingPluginWire.SUB_VOTE_ONLINE).put("sequence", "3").build();
BackendProxyHandlerAccess.dispatchIncomingAfterPublication(previous, late, mock(Runnable.class));
previous.dispatchIncomingAfterPublication(late, mock(Runnable.class));
ArrayDeque<Runnable> asyncTasks = new ArrayDeque<>();
doAnswer(invocation -> {
@@ -1504,7 +1498,7 @@ class BackendProxyHandlerLifecycleTest {
CompletableFuture<Void> callback = CompletableFuture.runAsync(() -> {
started.countDown();
BackendProxyHandlerAccess.dispatchIncomingAfterPublication(handler, envelope, localDispatch);
handler.dispatchIncomingAfterPublication(envelope, localDispatch);
});
assertTrue(started.await(1, TimeUnit.SECONDS));
assertFalse(callback.isDone());
@@ -1530,7 +1524,7 @@ class BackendProxyHandlerLifecycleTest {
CompletableFuture<Void> callback = CompletableFuture.runAsync(() -> {
started.countDown();
BackendProxyHandlerAccess.dispatchIncomingAfterPublication(replacement, envelope, replacementDispatch);
replacement.dispatchIncomingAfterPublication(envelope, replacementDispatch);
});
assertTrue(started.await(1, TimeUnit.SECONDS));
assertFalse(callback.isDone());
@@ -1562,7 +1556,7 @@ class BackendProxyHandlerLifecycleTest {
CompletableFuture<Void> callback = CompletableFuture.runAsync(() -> {
started.countDown();
BackendProxyHandlerAccess.dispatchIncomingAfterPublication(replacement, envelope, replacementDispatch);
replacement.dispatchIncomingAfterPublication(envelope, replacementDispatch);
});
assertTrue(started.await(1, TimeUnit.SECONDS));
assertFalse(callback.isDone());
@@ -1614,7 +1608,7 @@ class BackendProxyHandlerLifecycleTest {
try {
Field transportField = BackendProxyTransportManager.class.getDeclaredField("transport");
transportField.setAccessible(true);
ReflectiveAccess.set(transportField, manager, previous);
transportField.set(manager, previous);
manager.restoreAfterFailedReplacement();
} catch (ReflectiveOperationException failure) {
throw new AssertionError(failure);
@@ -1683,7 +1677,7 @@ class BackendProxyHandlerLifecycleTest {
Field targetField = com.bencodez.votingplugin.VotingPluginMain.class
.getDeclaredField("backendPluginMessageTarget");
targetField.setAccessible(true);
ReflectiveAccess.set(targetField, plugin, new AtomicReference<GlobalMessageHandler>());
targetField.set(plugin, new AtomicReference<GlobalMessageHandler>());
plugin.activateBackendPluginMessageHandler(firstTarget);
current.set(second);
@@ -1870,7 +1864,7 @@ class BackendProxyHandlerLifecycleTest {
BackendPresenceManager presence = mock(BackendPresenceManager.class);
Field field = BackendProxyHandler.class.getDeclaredField("presenceManager");
field.setAccessible(true);
ReflectiveAccess.set(field, handler, presence);
field.set(handler, presence);
verifyNoInteractions(presence);
handler.activatePresenceReporting();
@@ -1886,7 +1880,7 @@ class BackendProxyHandlerLifecycleTest {
org.mockito.Mockito.doThrow(new java.util.concurrent.RejectedExecutionException()).when(presence).start();
Field presenceField = BackendProxyHandler.class.getDeclaredField("presenceManager");
presenceField.setAccessible(true);
ReflectiveAccess.set(presenceField, handler, presence);
presenceField.set(handler, presence);
Field managerField = BackendProxyHandler.class.getDeclaredField("transportManager");
managerField.setAccessible(true);
@@ -1894,7 +1888,7 @@ class BackendProxyHandlerLifecycleTest {
BackendProxyTransport transport = mock(BackendProxyTransport.class);
Field transportField = BackendProxyTransportManager.class.getDeclaredField("transport");
transportField.setAccessible(true);
ReflectiveAccess.set(transportField, manager, transport);
transportField.set(manager, transport);
assertThrows(java.util.concurrent.RejectedExecutionException.class, handler::activatePresenceReporting);
@@ -1904,7 +1898,7 @@ class BackendProxyHandlerLifecycleTest {
@Test
void sharesVoteDeduplicationAcrossHandlerReplacement() {
ProcessedVoteCache cache = ProcessedVoteCacheAccess.create();
ProcessedVoteCache cache = new ProcessedVoteCache();
BackendProxyHandler previous = new BackendProxyHandler(null, cache);
BackendProxyHandler replacement = new BackendProxyHandler(null, cache);
@@ -1923,7 +1917,7 @@ class BackendProxyHandlerLifecycleTest {
BackendProxyTransport transport = mock(BackendProxyTransport.class);
Field transportField = BackendProxyTransportManager.class.getDeclaredField("transport");
transportField.setAccessible(true);
ReflectiveAccess.set(transportField, manager, transport);
transportField.set(manager, transport);
handler.prepareForReplacement(BungeeMethod.PLUGINMESSAGING);
@@ -1936,7 +1930,7 @@ class BackendProxyHandlerLifecycleTest {
SocketHandler socket = mock(SocketHandler.class);
Field field = SocketBackendProxyTransport.class.getDeclaredField("socketHandler");
field.setAccessible(true);
ReflectiveAccess.set(field, handler, socket);
field.set(handler, socket);
handler.prepareForReplacement();
@@ -2023,10 +2017,10 @@ class BackendProxyHandlerLifecycleTest {
RedisHandler redis = mock(RedisHandler.class);
Field field = RedisBackendProxyTransport.class.getDeclaredField("redisHandler");
field.setAccessible(true);
ReflectiveAccess.set(field, transport, redis);
field.set(transport, redis);
Field transportField = BackendProxyTransportManager.class.getDeclaredField("transport");
transportField.setAccessible(true);
ReflectiveAccess.set(transportField, manager, transport);
transportField.set(manager, transport);
handler.prepareForReplacement(BungeeMethod.REDIS);
@@ -2040,7 +2034,7 @@ class BackendProxyHandlerLifecycleTest {
MqttHandler mqtt = mock(MqttHandler.class);
Field field = MqttBackendProxyTransport.class.getDeclaredField("mqttHandler");
field.setAccessible(true);
ReflectiveAccess.set(field, handler, mqtt);
field.set(handler, mqtt);
handler.prepareForReplacement();
@@ -2772,7 +2766,7 @@ class BackendProxyHandlerLifecycleTest {
MySqlMessenger messenger = mock(MySqlMessenger.class);
Field field = MysqlBackendProxyTransport.class.getDeclaredField("messenger");
field.setAccessible(true);
ReflectiveAccess.set(field, handler, messenger);
field.set(handler, messenger);
handler.prepareForReplacement();
@@ -2917,7 +2911,7 @@ class BackendProxyHandlerLifecycleTest {
ScheduledExecutorService timer = mock(ScheduledExecutorService.class);
Field field = BackendGlobalDataSync.class.getDeclaredField("timer");
field.setAccessible(true);
ReflectiveAccess.set(field, handler, timer);
field.set(handler, timer);
handler.close();
@@ -2950,7 +2944,7 @@ class BackendProxyHandlerLifecycleTest {
try {
Field field = type.getDeclaredField(name);
field.setAccessible(true);
ReflectiveAccess.set(field, target, value);
field.set(target, value);
return;
} catch (NoSuchFieldException ignored) {
type = type.getSuperclass();
@@ -1,7 +1,4 @@
package com.bencodez.votingplugin.tests.backendproxy.cache;
import com.bencodez.votingplugin.tests.backendproxy.cache.DurableVoteReceiptStoreAccess;
import com.bencodez.votingplugin.backendproxy.cache.ProcessedVoteCache;
package com.bencodez.votingplugin.backendproxy.cache;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -19,7 +16,7 @@ class ProcessedVoteCacheDurabilityTest {
@Test
void duplicateRetryDoesNotScanAndPruneUnrelatedEntries() {
ProcessedVoteCache cache = ProcessedVoteCacheAccess.create(TimeUnit.MINUTES.toMillis(30), 2);
ProcessedVoteCache cache = new ProcessedVoteCache(TimeUnit.MINUTES.toMillis(30), 2);
UUID expired = UUID.randomUUID();
UUID live = UUID.randomUUID();
cache.getProcessedVotes().put(expired, 0L);
@@ -32,7 +29,7 @@ class ProcessedVoteCacheDurabilityTest {
@Test
void expiredHeadRetryReclaimsItsSlotBeforeSaturationCheck() {
ProcessedVoteCache cache = ProcessedVoteCacheAccess.create(TimeUnit.MINUTES.toMillis(30), 1);
ProcessedVoteCache cache = new ProcessedVoteCache(TimeUnit.MINUTES.toMillis(30), 1);
UUID expired = UUID.randomUUID();
cache.getProcessedVotes().put(expired, 0L);
@@ -47,44 +44,44 @@ class ProcessedVoteCacheDurabilityTest {
void releaseTombstoneCapacityCoversSustainedVoteThroughputForFullTtl() {
long threeVotesPerSecondForOneDay = TimeUnit.DAYS.toSeconds(1) * 3;
assertTrue(DurableVoteReceiptStoreAccess.MAX_RELEASE_TOMBSTONES >= threeVotesPerSecondForOneDay);
assertTrue(DurableVoteReceiptStore.MAX_RELEASE_TOMBSTONES >= threeVotesPerSecondForOneDay);
}
@Test
void completedVoteRemainsDeduplicatedAfterBackendRestart() {
Path receipts = directory.resolve("receipts.dat");
UUID voteId = UUID.randomUUID();
ProcessedVoteCache first = ProcessedVoteCacheAccess.create(receipts);
ProcessedVoteCache first = new ProcessedVoteCache(receipts);
assertTrue(first.reserve(voteId));
assertTrue(first.complete(voteId));
assertTrue(first.hasDurableReceipt(voteId));
assertFalse(ProcessedVoteCacheAccess.create(receipts).reserve(voteId));
assertFalse(new ProcessedVoteCache(receipts).reserve(voteId));
}
@Test
void reservationWithoutCompletionDoesNotSuppressRestartRetry() {
Path receipts = directory.resolve("receipts.dat");
UUID voteId = UUID.randomUUID();
assertTrue(ProcessedVoteCacheAccess.create(receipts).reserve(voteId));
assertTrue(new ProcessedVoteCache(receipts).reserve(voteId));
assertTrue(ProcessedVoteCacheAccess.create(receipts).reserve(voteId));
assertTrue(new ProcessedVoteCache(receipts).reserve(voteId));
}
@Test
void repairsTruncatedTailBeforeAppendingAnotherReceipt() throws Exception {
Path receipts = directory.resolve("receipts.dat");
UUID firstId = UUID.randomUUID();
ProcessedVoteCache first = ProcessedVoteCacheAccess.create(receipts);
ProcessedVoteCache first = new ProcessedVoteCache(receipts);
assertTrue(first.reserve(firstId));
assertTrue(first.complete(firstId));
Files.writeString(receipts, "truncated", StandardOpenOption.APPEND);
ProcessedVoteCache repaired = ProcessedVoteCacheAccess.create(receipts);
ProcessedVoteCache repaired = new ProcessedVoteCache(receipts);
UUID secondId = UUID.randomUUID();
assertTrue(repaired.reserve(secondId));
assertTrue(repaired.complete(secondId));
ProcessedVoteCache restarted = ProcessedVoteCacheAccess.create(receipts);
ProcessedVoteCache restarted = new ProcessedVoteCache(receipts);
assertFalse(restarted.reserve(firstId));
assertFalse(restarted.reserve(secondId));
}
@@ -94,14 +91,14 @@ class ProcessedVoteCacheDurabilityTest {
Path receipts = directory.resolve("receipts.dat");
UUID firstId = UUID.randomUUID();
UUID secondId = UUID.randomUUID();
ProcessedVoteCache cache = ProcessedVoteCacheAccess.create(receipts);
ProcessedVoteCache cache = new ProcessedVoteCache(receipts);
assertTrue(cache.reserve(firstId));
assertTrue(cache.complete(firstId));
Files.writeString(receipts, "partial", StandardOpenOption.APPEND);
assertTrue(cache.reserve(secondId));
assertTrue(cache.complete(secondId));
ProcessedVoteCache restarted = ProcessedVoteCacheAccess.create(receipts);
ProcessedVoteCache restarted = new ProcessedVoteCache(receipts);
assertFalse(restarted.reserve(firstId));
assertFalse(restarted.reserve(secondId));
}
@@ -112,7 +109,7 @@ class ProcessedVoteCacheDurabilityTest {
UUID incompleteId = UUID.randomUUID();
Files.writeString(receipts, "VP-VOTE-RECEIPTS-1\n" + incompleteId + "\t9");
ProcessedVoteCache repaired = ProcessedVoteCacheAccess.create(receipts);
ProcessedVoteCache repaired = new ProcessedVoteCache(receipts);
assertTrue(repaired.reserve(incompleteId));
assertTrue(Files.readString(receipts).endsWith("\n"));
@@ -123,7 +120,7 @@ class ProcessedVoteCacheDurabilityTest {
Path unusableParent = directory.resolve("not-a-directory");
Files.writeString(unusableParent, "file");
UUID voteId = UUID.randomUUID();
ProcessedVoteCache cache = ProcessedVoteCacheAccess.create(1L, unusableParent.resolve("receipts.dat"));
ProcessedVoteCache cache = new ProcessedVoteCache(1L, unusableParent.resolve("receipts.dat"));
assertTrue(cache.reserve(voteId));
assertFalse(cache.complete(voteId));
@@ -135,31 +132,31 @@ class ProcessedVoteCacheDurabilityTest {
void proxyConfirmedReleaseLeavesRestartSafeTombstone() {
Path receipts = directory.resolve("receipts.dat");
UUID voteId = UUID.randomUUID();
ProcessedVoteCache cache = ProcessedVoteCacheAccess.create(receipts);
ProcessedVoteCache cache = new ProcessedVoteCache(receipts);
assertTrue(cache.reserve(voteId));
assertTrue(cache.complete(voteId));
assertTrue(cache.releaseCompletedReceipt(voteId));
assertFalse(ProcessedVoteCacheAccess.create(receipts).reserve(voteId));
assertFalse(new ProcessedVoteCache(receipts).reserve(voteId));
}
@Test
void unknownReceiptReleaseLeavesRestartSafeTombstone() {
Path receipts = directory.resolve("receipts.dat");
UUID voteId = UUID.randomUUID();
ProcessedVoteCache cache = ProcessedVoteCacheAccess.create(receipts);
ProcessedVoteCache cache = new ProcessedVoteCache(receipts);
assertFalse(cache.hasDurableReceipt(voteId));
assertTrue(cache.releaseCompletedReceipt(voteId));
assertTrue(cache.hasDurableReceipt(voteId));
assertFalse(ProcessedVoteCacheAccess.create(receipts).reserve(voteId));
assertFalse(new ProcessedVoteCache(receipts).reserve(voteId));
}
@Test
void completionHeadroomAllowsPrecedingVotesBeforeRelease() throws Exception {
DurableVoteReceiptStoreAccess store = new DurableVoteReceiptStoreAccess(directory.resolve("receipts.dat"), 1, 2, 1);
DurableVoteReceiptStore store = new DurableVoteReceiptStore(directory.resolve("receipts.dat"), 1, 2, 1);
UUID first = UUID.randomUUID();
UUID second = UUID.randomUUID();
UUID third = UUID.randomUUID();
@@ -176,14 +173,14 @@ class ProcessedVoteCacheDurabilityTest {
@Test
void activeReceiptWaitsWhenTombstoneCapacityIsFull() throws Exception {
Path receipts = directory.resolve("receipts.dat");
DurableVoteReceiptStoreAccess store = new DurableVoteReceiptStoreAccess(receipts, 1, 0, 1);
DurableVoteReceiptStore store = new DurableVoteReceiptStore(receipts, 1, 0, 1);
UUID active = UUID.randomUUID();
assertTrue(store.complete(active) > 0L);
assertTrue(store.release(UUID.randomUUID()) > 0L);
assertFalse(store.release(active) > 0L);
new DurableVoteReceiptStoreAccess(receipts, 1, 0, 1);
new DurableVoteReceiptStore(receipts, 1, 0, 1);
}
@Test
@@ -192,12 +189,12 @@ class ProcessedVoteCacheDurabilityTest {
UUID voteId = UUID.randomUUID();
Files.writeString(receipts, "VP-VOTE-RECEIPTS-1\nR\t" + voteId + "\t1\n");
assertTrue(ProcessedVoteCacheAccess.create(receipts).reserve(voteId));
assertTrue(new ProcessedVoteCache(receipts).reserve(voteId));
}
@Test
void saturationDoesNotEvictLiveReplayFences() {
ProcessedVoteCache cache = ProcessedVoteCacheAccess.create(TimeUnit.MINUTES.toMillis(30), 2);
ProcessedVoteCache cache = new ProcessedVoteCache(TimeUnit.MINUTES.toMillis(30), 2);
UUID first = UUID.randomUUID();
UUID second = UUID.randomUUID();
@@ -211,19 +208,19 @@ class ProcessedVoteCacheDurabilityTest {
@Test
void defaultCapacityIncludesDurableCompletionHeadroom() {
assertTrue(ProcessedVoteCacheAccess.DEFAULT_MAX_TRACKED_VOTES
== DurableVoteReceiptStoreAccess.MAX_ACTIVE_RECEIPTS + DurableVoteReceiptStoreAccess.COMPLETION_HEADROOM);
assertTrue(ProcessedVoteCacheAccess.DEFAULT_MAX_TRACKED_VOTES <= DurableVoteReceiptStoreAccess.MAX_TOTAL_RECEIPTS);
assertTrue((long) DurableVoteReceiptStoreAccess.MAX_TOTAL_RECEIPTS * DurableVoteReceiptStoreAccess.MAX_RECORD_BYTES
+ "VP-VOTE-RECEIPTS-1\n".length() <= DurableVoteReceiptStoreAccess.MAX_FILE_BYTES);
assertTrue((long) (DurableVoteReceiptStoreAccess.MAX_TOTAL_RECEIPTS + 1)
* DurableVoteReceiptStoreAccess.MAX_RECORD_BYTES + "VP-VOTE-RECEIPTS-1\n".length()
> DurableVoteReceiptStoreAccess.MAX_FILE_BYTES);
assertTrue(ProcessedVoteCache.DEFAULT_MAX_TRACKED_VOTES
== DurableVoteReceiptStore.MAX_ACTIVE_RECEIPTS + DurableVoteReceiptStore.COMPLETION_HEADROOM);
assertTrue(ProcessedVoteCache.DEFAULT_MAX_TRACKED_VOTES <= DurableVoteReceiptStore.MAX_TOTAL_RECEIPTS);
assertTrue((long) DurableVoteReceiptStore.MAX_TOTAL_RECEIPTS * DurableVoteReceiptStore.MAX_RECORD_BYTES
+ "VP-VOTE-RECEIPTS-1\n".length() <= DurableVoteReceiptStore.MAX_FILE_BYTES);
assertTrue((long) (DurableVoteReceiptStore.MAX_TOTAL_RECEIPTS + 1)
* DurableVoteReceiptStore.MAX_RECORD_BYTES + "VP-VOTE-RECEIPTS-1\n".length()
> DurableVoteReceiptStore.MAX_FILE_BYTES);
}
@Test
void mixedActiveAndReleaseReceiptsRespectTheJournalByteAlignedLimit() throws Exception {
DurableVoteReceiptStoreAccess store = new DurableVoteReceiptStoreAccess(directory.resolve("mixed-receipts.dat"), 2, 0, 2, 2);
DurableVoteReceiptStore store = new DurableVoteReceiptStore(directory.resolve("mixed-receipts.dat"), 2, 0, 2, 2);
UUID released = UUID.randomUUID();
UUID active = UUID.randomUUID();
@@ -247,7 +244,7 @@ class ProcessedVoteCacheDurabilityTest {
+ "R\t" + firstReleased + "\t" + expiresAt + "\n"
+ "R\t" + secondReleased + "\t" + expiresAt + "\n");
DurableVoteReceiptStoreAccess store = new DurableVoteReceiptStoreAccess(receipts, 2, 0, 2, 2);
DurableVoteReceiptStore store = new DurableVoteReceiptStore(receipts, 2, 0, 2, 2);
assertTrue(store.contains(firstActive));
assertTrue(store.contains(secondActive));
@@ -258,11 +255,11 @@ class ProcessedVoteCacheDurabilityTest {
@Test
void mixedJournalUsesDurablePerKindCapacityForNewAdmission() throws Exception {
DurableVoteReceiptStoreAccess store = new DurableVoteReceiptStoreAccess(directory.resolve("mixed-capacity.dat"), 2, 1, 2, 4);
DurableVoteReceiptStore store = new DurableVoteReceiptStore(directory.resolve("mixed-capacity.dat"), 2, 1, 2, 4);
assertTrue(store.release(UUID.randomUUID()) > 0L);
assertTrue(store.release(UUID.randomUUID()) > 0L);
assertTrue(store.complete(UUID.randomUUID()) > 0L);
ProcessedVoteCache cache = ProcessedVoteCacheAccess.create(TimeUnit.MINUTES.toMillis(30), 2, store);
ProcessedVoteCache cache = new ProcessedVoteCache(TimeUnit.MINUTES.toMillis(30), 2, store);
UUID admitted = UUID.randomUUID();
UUID stale = UUID.randomUUID();
cache.getProcessedVotes().put(stale, 0L);
@@ -276,7 +273,7 @@ class ProcessedVoteCacheDurabilityTest {
@Test
void cancelledValidationReservationFreesCapacity() {
ProcessedVoteCache cache = ProcessedVoteCacheAccess.create(TimeUnit.MINUTES.toMillis(30), 1);
ProcessedVoteCache cache = new ProcessedVoteCache(TimeUnit.MINUTES.toMillis(30), 1);
UUID invalid = UUID.randomUUID();
assertTrue(cache.reserve(invalid));
@@ -1,8 +1,4 @@
package com.bencodez.votingplugin.tests.backendproxy.global;
import com.bencodez.votingplugin.tests.support.ReflectiveAccess;
import com.bencodez.votingplugin.backendproxy.global.BackendGlobalDataSync;
package com.bencodez.votingplugin.backendproxy.global;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
@@ -291,7 +287,7 @@ class BackendGlobalDataSyncTest {
oldSync.checkGlobalData();
org.junit.jupiter.api.Assertions.assertEquals(1, schedulerRuns.get());
oldSync.handoffCompletionSender(replacement);
BackendGlobalDataSyncAccess.close(oldSync, 1, TimeUnit.MILLISECONDS);
oldSync.close(1, TimeUnit.MILLISECONDS);
replacement.checkGlobalData();
org.junit.jupiter.api.Assertions.assertEquals(1, schedulerRuns.get());
@@ -404,7 +400,7 @@ class BackendGlobalDataSyncTest {
CompletableFuture<Void> execution = CompletableFuture.runAsync(asyncWrite.get());
assertTrue(writeStarted.await(1, TimeUnit.SECONDS));
oldSync.handoffCompletionSender(replacement);
BackendGlobalDataSyncAccess.close(oldSync, 1, TimeUnit.MILLISECONDS);
oldSync.close(1, TimeUnit.MILLISECONDS);
replacement.checkGlobalData();
verify(replacementHandler).setBoolean("lobby", "ForceUpdate", false);
@@ -555,7 +551,7 @@ class BackendGlobalDataSyncTest {
setField(sync, "globalDataHandler", handler);
setField(sync, "ownsGlobalMysql", false);
CompletableFuture<Void> heartbeat = CompletableFuture.runAsync(() -> BackendGlobalDataSyncAccess.updateLastOnline(sync));
CompletableFuture<Void> heartbeat = CompletableFuture.runAsync(sync::updateLastOnline);
assertTrue(heartbeatStarted.await(1, TimeUnit.SECONDS));
CompletableFuture<Void> close = CompletableFuture.runAsync(sync::close);
Thread.sleep(50L);
@@ -965,7 +961,7 @@ class BackendGlobalDataSyncTest {
assertTrue(oldSync.checkGlobalDataTime(TimeType.DAY, data));
scheduled.get().run();
oldSync.handoffCompletionSender(replacement);
BackendGlobalDataSyncAccess.close(oldSync, 1, TimeUnit.MILLISECONDS);
oldSync.close(1, TimeUnit.MILLISECONDS);
replacement.checkGlobalData();
verify(timeChecker).forceChanged(TimeType.DAY, false, true, true);
@@ -1087,7 +1083,7 @@ class BackendGlobalDataSyncTest {
week.put(TimeType.WEEK.toString(), new DataValueBoolean(true));
assertTrue(oldSync.checkGlobalDataTime(TimeType.DAY, day));
BackendGlobalDataSyncAccess.close(oldSync, 1, TimeUnit.MILLISECONDS);
oldSync.close(1, TimeUnit.MILLISECONDS);
assertFalse(replacement.checkGlobalDataTime(TimeType.DAY, day));
assertTrue(replacement.checkGlobalDataTime(TimeType.WEEK, week));
org.junit.jupiter.api.Assertions.assertEquals(2, scheduled.size());
@@ -1128,7 +1124,7 @@ class BackendGlobalDataSyncTest {
week.put(TimeType.WEEK.toString(), new DataValueBoolean(true));
assertTrue(oldSync.checkGlobalDataTime(TimeType.DAY, day));
BackendGlobalDataSyncAccess.close(oldSync, 1, TimeUnit.MILLISECONDS);
oldSync.close(1, TimeUnit.MILLISECONDS);
BackendGlobalDataSync replacement = new BackendGlobalDataSync(plugin, ignored -> { });
setField(replacement, "globalDataHandler", replacementHandler);
@@ -1223,7 +1219,7 @@ class BackendGlobalDataSyncTest {
() -> sync.checkGlobalDataTime(TimeType.DAY, data));
assertTrue(writeStarted.await(1, TimeUnit.SECONDS));
BackendGlobalDataSyncAccess.close(sync, 50L, TimeUnit.MILLISECONDS);
sync.close(50L, TimeUnit.MILLISECONDS);
verify(mysql).close();
releaseWrite.countDown();
@@ -1243,7 +1239,7 @@ class BackendGlobalDataSyncTest {
setField(sync, "globalDataHandler", handler);
setField(sync, "ownsGlobalMysql", false);
BackendGlobalDataSyncAccess.close(sync);
sync.close();
verify(mysql, never()).close();
}
@@ -1258,7 +1254,7 @@ class BackendGlobalDataSyncTest {
setField(sync, "globalDataHandler", handler);
setField(sync, "ownsGlobalMysql", true);
BackendGlobalDataSyncAccess.close(sync);
sync.close();
verify(mysql).close();
}
@@ -1267,7 +1263,7 @@ class BackendGlobalDataSyncTest {
try {
Field field = BackendGlobalDataSync.class.getDeclaredField(fieldName);
field.setAccessible(true);
ReflectiveAccess.set(field, target, value);
field.set(target, value);
} catch (ReflectiveOperationException failure) {
throw new AssertionError(failure);
}
@@ -1,6 +1,4 @@
package com.bencodez.votingplugin.tests.backendproxy.messaging;
import com.bencodez.votingplugin.backendproxy.messaging.BackendProxyMessageRouter;
package com.bencodez.votingplugin.backendproxy.messaging;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
@@ -116,7 +114,7 @@ class BackendProxyMessageRouterTest {
@Test
void ignoresLastVoteTimeForUnknownServiceSite() {
BackendProxyMessageRouterAccess.handleVoteUpdate(router, VotingPluginWire.voteUpdate(PLAYER_UUID.toString(), 1, 10,
router.handleVoteUpdate(VotingPluginWire.voteUpdate(PLAYER_UUID.toString(), 1, 10,
"unknown.example\nforged-entry", LAST_VOTE_TIME, ""));
verify(user, times(2)).cache();
@@ -132,7 +130,7 @@ class BackendProxyMessageRouterTest {
VoteSite voteSite = mock(VoteSite.class);
when(voteSiteManager.getVoteSite("known.example", true)).thenReturn(voteSite);
BackendProxyMessageRouterAccess.handleVoteUpdate(router, VotingPluginWire.voteUpdate(PLAYER_UUID.toString(), 1, 10,
router.handleVoteUpdate(VotingPluginWire.voteUpdate(PLAYER_UUID.toString(), 1, 10,
"known.example", LAST_VOTE_TIME, ""));
verify(user, times(2)).cache();
@@ -789,7 +787,7 @@ class BackendProxyMessageRouterTest {
}).when(coreUserManager).getUserAsync(eq(PLAYER_UUID), any(), any());
AtomicInteger completions = new AtomicInteger();
BackendProxyMessageRouterAccess.handleVoteUpdate(router, VotingPluginWire.voteUpdate(PLAYER_UUID.toString(), 1, 10,
router.handleVoteUpdate(VotingPluginWire.voteUpdate(PLAYER_UUID.toString(), 1, 10,
"known.example", LAST_VOTE_TIME, ""), completions::incrementAndGet);
assertEquals(1, completions.get());
@@ -1,8 +1,4 @@
package com.bencodez.votingplugin.tests.backendproxy.messaging;
import com.bencodez.votingplugin.tests.backendproxy.cache.ProcessedVoteCacheAccess;
import com.bencodez.votingplugin.backendproxy.messaging.BackendProxyMessageRouter;
package com.bencodez.votingplugin.backendproxy.messaging;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -96,7 +92,7 @@ class BackendProxyVoteDelayReplayTest {
fixture.assertEffects(1);
fixture.assertOccurrence(0, voteId, RECORDED_TIME - 60_000L);
verify(fixture.site, never()).giveWaitUntilVoteDelayRewards(any(), anyBoolean(), anyBoolean());
assertTrue(ProcessedVoteCacheAccess.create(fixture.receipts).hasDurableReceipt(voteId));
assertTrue(new ProcessedVoteCache(fixture.receipts).hasDurableReceipt(voteId));
});
}
@@ -281,7 +277,7 @@ class BackendProxyVoteDelayReplayTest {
private void restartReceiver() {
router = new BackendProxyMessageRouter(plugin, mock(BackendPresenceManager.class),
mock(BackendGlobalDataSync.class), mock(BackendVotePartySync.class),
ProcessedVoteCacheAccess.create(receipts));
new ProcessedVoteCache(receipts));
}
private void deliver(JsonEnvelope envelope) {
@@ -1,10 +1,4 @@
package com.bencodez.votingplugin.tests.backendproxy.transport;
import com.bencodez.votingplugin.tests.support.ReflectiveAccess;
import com.bencodez.votingplugin.backendproxy.transport.BackendProxyTransport;
import com.bencodez.votingplugin.backendproxy.transport.BackendProxyTransportManager;
import com.bencodez.votingplugin.backendproxy.transport.HttpBackendProxyTransport;
package com.bencodez.votingplugin.backendproxy.transport;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -70,7 +64,7 @@ class HttpBackendProxyTransportTest {
}).when(scheduler).runTask(org.mockito.ArgumentMatchers.eq(plugin), org.mockito.ArgumentMatchers.any(Runnable.class));
JsonEnvelope envelope = JsonEnvelope.builder("test").put("message", "payload").build();
HttpBackendProxyTransportAccess.dispatchIncoming(new HttpBackendProxyTransport(plugin), handler, envelope,
new HttpBackendProxyTransport(plugin).dispatchIncoming(handler, envelope,
System.nanoTime() + TimeUnit.SECONDS.toNanos(1));
assertTrue(callbackFinished.await(1, TimeUnit.SECONDS));
@@ -79,7 +73,7 @@ class HttpBackendProxyTransportTest {
@Test
void publicationActivatesTheSimpleApiInboundBarrier() throws Exception {
HttpBackendProxyTransport transport = HttpBackendProxyTransportAccess.create(mock(VotingPluginMain.class));
HttpBackendProxyTransport transport = new HttpBackendProxyTransport(mock(VotingPluginMain.class));
HttpBackendTransportConnector connector = mock(HttpBackendTransportConnector.class);
setField(transport, "connector", connector);
@@ -90,10 +84,10 @@ class HttpBackendProxyTransportTest {
@Test
void closedPublicationGateRejectsDeliveryForReplay() {
HttpBackendProxyTransport transport = HttpBackendProxyTransportAccess.create(mock(VotingPluginMain.class));
HttpBackendProxyTransport transport = new HttpBackendProxyTransport(mock(VotingPluginMain.class));
transport.close();
assertThrows(IllegalStateException.class, () -> HttpBackendProxyTransportAccess.dispatchAfterPublication(transport,
assertThrows(IllegalStateException.class, () -> transport.dispatchAfterPublication(
mock(GlobalMessageHandler.class), JsonEnvelope.builder("test").build()));
}
@@ -104,7 +98,7 @@ class HttpBackendProxyTransportTest {
when(connector.send(pending)).thenReturn(false, true);
when(connector.flushOutgoing(org.mockito.ArgumentMatchers.anyLong())).thenReturn(true);
assertTrue(HttpBackendProxyTransportAccess.flushHandoffForShutdown(connector, List.of(pending),
assertTrue(HttpBackendProxyTransport.flushHandoffForShutdown(connector, List.of(pending),
System.nanoTime() + TimeUnit.SECONDS.toNanos(1)));
org.mockito.InOrder order = org.mockito.Mockito.inOrder(connector);
@@ -115,7 +109,7 @@ class HttpBackendProxyTransportTest {
@Test
@SuppressWarnings("unchecked")
void unpublishedHandoffMessagesAreDiscardedOnRollback() throws Exception {
HttpBackendProxyTransport transport = HttpBackendProxyTransportAccess.create(mock(VotingPluginMain.class));
HttpBackendProxyTransport transport = new HttpBackendProxyTransport(mock(VotingPluginMain.class));
HttpBackendTransportConnector connector = mock(HttpBackendTransportConnector.class);
setField(transport, "connector", connector);
((java.util.ArrayDeque<JsonEnvelope>) field(transport, "handoffQueue"))
@@ -136,7 +130,7 @@ class HttpBackendProxyTransportTest {
when(connector.send(pending)).thenReturn(false);
assertThrows(IllegalStateException.class,
() -> HttpBackendProxyTransportAccess.transferStartupQueue(queue, connector));
() -> HttpBackendProxyTransport.transferStartupQueue(queue, connector));
assertEquals(java.util.List.of(pending), new java.util.ArrayList<>(queue));
}
@@ -148,7 +142,7 @@ class HttpBackendProxyTransportTest {
CountDownLatch completion = new CountDownLatch(1);
assertThrows(IllegalStateException.class,
() -> HttpBackendProxyTransportAccess.finishInitialization(false, connector, true, owner, completion));
() -> HttpBackendProxyTransport.finishInitialization(false, connector, true, owner, completion));
verify(connector).close();
assertEquals(1, owner.availablePermits());
@@ -158,7 +152,7 @@ class HttpBackendProxyTransportTest {
@Test
@SuppressWarnings("unchecked")
void orderlyShutdownFlushesRecoveryQueueBeforeHandoffQueue() throws Exception {
HttpBackendProxyTransport transport = HttpBackendProxyTransportAccess.create(mock(VotingPluginMain.class));
HttpBackendProxyTransport transport = new HttpBackendProxyTransport(mock(VotingPluginMain.class));
HttpBackendTransportConnector connector = mock(HttpBackendTransportConnector.class);
JsonEnvelope recovery = JsonEnvelope.builder("recovery").build();
JsonEnvelope handoff = JsonEnvelope.builder("handoff").build();
@@ -187,8 +181,8 @@ class HttpBackendProxyTransportTest {
setField(manager, "transport", failed);
org.mockito.Mockito.doThrow(new IllegalStateException("worker still stopping"))
.when(failed).prepareForReplacement();
when(HttpBackendProxyTransportAccess.isClosedForReplacement(failed)).thenReturn(true);
when(HttpBackendProxyTransportAccess.recreatePrepared(failed)).thenReturn(restored);
when(failed.isClosedForReplacement()).thenReturn(true);
when(failed.recreatePrepared()).thenReturn(restored);
assertThrows(IllegalStateException.class, manager::prepareForReplacement);
manager.send(queued);
@@ -209,7 +203,7 @@ class HttpBackendProxyTransportTest {
manager.send(queued);
verify(active).send(queued);
HttpBackendProxyTransportAccess.recreatePrepared(verify(active, org.mockito.Mockito.never()));
verify(active, org.mockito.Mockito.never()).recreatePrepared();
}
@Test
@@ -273,7 +267,7 @@ class HttpBackendProxyTransportTest {
});
assertThrows(IllegalStateException.class,
() -> HttpBackendProxyTransportAccess.dispatchIncoming(new HttpBackendProxyTransport(plugin), handler,
() -> new HttpBackendProxyTransport(plugin).dispatchIncoming(handler,
JsonEnvelope.builder("test").build(), System.nanoTime()));
assertTrue(scheduled.get() != null);
scheduled.get().run();
@@ -300,7 +294,7 @@ class HttpBackendProxyTransportTest {
AtomicReference<Throwable> dispatchFailure = new AtomicReference<>();
Thread dispatch = new Thread(() -> {
try {
HttpBackendProxyTransportAccess.dispatchIncoming(new HttpBackendProxyTransport(plugin), handler,
new HttpBackendProxyTransport(plugin).dispatchIncoming(handler,
JsonEnvelope.builder("test").build(), System.nanoTime() + TimeUnit.SECONDS.toNanos(5));
} catch (Throwable thrown) {
dispatchFailure.set(thrown);
@@ -323,28 +317,28 @@ class HttpBackendProxyTransportTest {
when(plugin.getDataFolder()).thenReturn(directory.toFile());
when(plugin.getBungeeSettings()).thenReturn(settings);
when(settings.getServer()).thenReturn("lobby-1");
HttpBackendProxyTransport transport = HttpBackendProxyTransportAccess.create(plugin);
HttpBackendProxyTransport transport = new HttpBackendProxyTransport(plugin);
when(settings.getHttpConnectionCode()).thenReturn("malformed");
assertThrows(IllegalStateException.class, () -> HttpBackendProxyTransportAccess.validate(transport));
assertThrows(IllegalStateException.class, transport::validate);
when(settings.getHttpConnectionCode()).thenReturn(code("lobby-1", Instant.now().minusSeconds(1)).encode());
assertThrows(IllegalStateException.class, () -> HttpBackendProxyTransportAccess.validate(transport));
assertThrows(IllegalStateException.class, transport::validate);
when(settings.getHttpConnectionCode()).thenReturn(code("survival", Instant.now().plusSeconds(60)).encode());
assertThrows(IllegalStateException.class, () -> HttpBackendProxyTransportAccess.validate(transport));
assertThrows(IllegalStateException.class, transport::validate);
assertThrows(IllegalStateException.class, () -> transport.start(mock(GlobalMessageHandler.class)),
"invalid configuration must fail before the enrollment worker starts");
when(settings.getHttpConnectionCode()).thenReturn(code("lobby-1", Instant.now().plusSeconds(60)).encode());
assertDoesNotThrow(() -> HttpBackendProxyTransportAccess.validate(transport));
assertDoesNotThrow(() -> transport.validate());
}
@Test
void ordinaryStartupRetriesTransientInitialEnrollmentWithBoundedBackoff() throws Exception {
VotingPluginMain plugin = mock(VotingPluginMain.class);
when(plugin.getLogger()).thenReturn(java.util.logging.Logger.getAnonymousLogger());
HttpBackendProxyTransport transport = HttpBackendProxyTransportAccess.create(plugin);
HttpBackendProxyTransport transport = new HttpBackendProxyTransport(plugin);
HttpConnectionCode enrollment = code("lobby-1", Instant.now().plusSeconds(60));
List<Long> delays = new ArrayList<>();
java.util.concurrent.atomic.AtomicInteger attempts = new java.util.concurrent.atomic.AtomicInteger();
@@ -355,7 +349,7 @@ class HttpBackendProxyTransportTest {
if (attempts.getAndIncrement() == 0) throw new IOException("proxy unavailable");
return null;
});
assertTrue(HttpBackendProxyTransportAccess.enrollForStartup(transport, enrollment, "lobby-1", directory, true,
assertTrue(transport.enrollForStartup(enrollment, "lobby-1", directory, true,
delay -> { delays.add(delay); return true; }));
}
@@ -365,11 +359,11 @@ class HttpBackendProxyTransportTest {
@Test
void replacementCancelsRetryingInitialEnrollmentWithoutCredential() throws Exception {
HttpBackendProxyTransport transport = HttpBackendProxyTransportAccess.create(mock(VotingPluginMain.class));
HttpBackendProxyTransport transport = new HttpBackendProxyTransport(mock(VotingPluginMain.class));
Path credentials = directory.resolve("http");
java.lang.reflect.Field directoryField = HttpBackendProxyTransport.class.getDeclaredField("configuredDirectory");
directoryField.setAccessible(true);
ReflectiveAccess.set(directoryField, transport, credentials);
directoryField.set(transport, credentials);
java.lang.reflect.Field ownersField = HttpBackendProxyTransport.class.getDeclaredField("DIRECTORY_OWNERS");
ownersField.setAccessible(true);
@SuppressWarnings("unchecked")
@@ -386,7 +380,7 @@ class HttpBackendProxyTransportTest {
});
java.lang.reflect.Field workerField = HttpBackendProxyTransport.class.getDeclaredField("worker");
workerField.setAccessible(true);
ReflectiveAccess.set(workerField, transport, retryingEnrollment);
workerField.set(transport, retryingEnrollment);
retryingEnrollment.start();
assertTrue(workerStarted.await(1, TimeUnit.SECONDS));
JsonEnvelope queued = JsonEnvelope.builder("queued-before-replacement").build();
@@ -398,7 +392,7 @@ class HttpBackendProxyTransportTest {
HttpBackendProxyTransport.class.getDeclaredField("restoreUnenrolledState");
restoreAbsent.setAccessible(true);
assertTrue(restoreAbsent.getBoolean(transport), "rollback must remember that no credential existed");
assertEquals(List.of(queued), HttpBackendProxyTransportAccess.drainPreparedMessages(transport),
assertEquals(List.of(queued), transport.drainPreparedMessages(),
"messages accepted before replacement must remain available for handoff");
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(2);
@@ -410,7 +404,7 @@ class HttpBackendProxyTransportTest {
@Test
void replacementSnapshotsInitialEnrollmentPublishedWhileCancellationCompletes() throws Exception {
HttpBackendProxyTransport transport = HttpBackendProxyTransportAccess.create(mock(VotingPluginMain.class));
HttpBackendProxyTransport transport = new HttpBackendProxyTransport(mock(VotingPluginMain.class));
Path credentials = directory.resolve("http");
HttpTlsIdentity identity = HttpTlsIdentity.loadOrCreate(directory.resolve("original-proxy"),
"proxy.example.test");
@@ -457,7 +451,7 @@ class HttpBackendProxyTransportTest {
assertTrue(HttpClientCredentialStore.hasEnrolledProfile(credentials));
HttpConnectionCode original = code("lobby-1", Instant.now().plusSeconds(60));
HttpBackendProxyTransportAccess.restoreUnenrolledCredentialState(credentials, "lobby-1", original.encode());
HttpBackendProxyTransport.restoreUnenrolledCredentialState(credentials, "lobby-1", original.encode());
assertFalse(HttpClientCredentialStore.hasEnrolledProfile(credentials),
"a failed staged first enrollment must not remain active during rollback");
@@ -472,7 +466,7 @@ class HttpBackendProxyTransportTest {
identity.serverCertificatePin(), identity.caCertificatePin(), Instant.now().plusSeconds(60), "F".repeat(43));
HttpClientCredentialStore.saveEnrolled(credentials, original, identity.issueClientCertificate("lobby-1"));
HttpBackendProxyTransportAccess.restoreUnenrolledCredentialState(credentials, "lobby-1", original.encode());
HttpBackendProxyTransport.restoreUnenrolledCredentialState(credentials, "lobby-1", original.encode());
assertTrue(HttpClientCredentialStore.hasEnrolledProfile(credentials),
"a credential issued for the consumed original code must remain recoverable");
@@ -482,13 +476,13 @@ class HttpBackendProxyTransportTest {
void stagedEnrollmentRemainsFailFast() throws Exception {
VotingPluginMain plugin = mock(VotingPluginMain.class);
when(plugin.getLogger()).thenReturn(java.util.logging.Logger.getAnonymousLogger());
HttpBackendProxyTransport transport = HttpBackendProxyTransportAccess.create(plugin);
HttpBackendProxyTransport transport = new HttpBackendProxyTransport(plugin);
HttpConnectionCode enrollment = code("lobby-1", Instant.now().plusSeconds(60));
try (MockedStatic<HttpBackendTransportConnector> connector = org.mockito.Mockito.mockStatic(HttpBackendTransportConnector.class)) {
connector.when(() -> HttpBackendTransportConnector.enroll(enrollment, "lobby-1", directory))
.thenThrow(new IOException("proxy unavailable"));
assertThrows(IOException.class,
() -> HttpBackendProxyTransportAccess.enrollForStartup(transport, enrollment, "lobby-1", directory, false,
() -> transport.enrollForStartup(enrollment, "lobby-1", directory, false,
delay -> { throw new AssertionError("staged enrollment must not retry"); }));
}
}
@@ -500,32 +494,32 @@ class HttpBackendProxyTransportTest {
HttpConnectionCode original = new HttpConnectionCode("lobby-1", URI.create("https://proxy.example.test:1297/"),
identity.serverCertificatePin(), identity.caCertificatePin(), Instant.now().minusSeconds(1), "A".repeat(43));
HttpClientCredentialStore.saveEnrolled(credentials, original, identity.issueClientCertificate("lobby-1"));
assertNull(HttpBackendProxyTransportAccess.enrollmentCode(credentials, "lobby-1", ""));
assertNull(HttpBackendProxyTransportAccess.enrollmentCode(credentials, "lobby-1", original.encode()),
assertNull(HttpBackendProxyTransport.enrollmentCode(credentials, "lobby-1", ""));
assertNull(HttpBackendProxyTransport.enrollmentCode(credentials, "lobby-1", original.encode()),
"the already-consumed code must not be retried, even after it expires");
HttpConnectionCode replacement = new HttpConnectionCode("lobby-1", original.endpoint(), original.serverCertificatePin(),
original.caCertificatePin(), Instant.now().plusSeconds(60), "B".repeat(43));
assertEquals(replacement.encode(), HttpBackendProxyTransportAccess.enrollmentCode(credentials, "lobby-1", replacement.encode()).encode());
assertEquals(replacement.encode(), HttpBackendProxyTransport.enrollmentCode(credentials, "lobby-1", replacement.encode()).encode());
assertThrows(IllegalStateException.class,
() -> HttpBackendProxyTransportAccess.enrollmentCode(credentials, "lobby-1", "malformed"));
() -> HttpBackendProxyTransport.enrollmentCode(credentials, "lobby-1", "malformed"));
}
@Test
void failedReplacementFlushResumesTheExistingConnector() {
HttpBackendTransportConnector connector = mock(HttpBackendTransportConnector.class);
when(connector.flushOutgoing(org.mockito.ArgumentMatchers.anyLong())).thenReturn(false);
HttpBackendProxyTransport transport = HttpBackendProxyTransportAccess.create(mock(VotingPluginMain.class));
HttpBackendProxyTransport transport = new HttpBackendProxyTransport(mock(VotingPluginMain.class));
assertThrows(IllegalStateException.class,
() -> HttpBackendProxyTransportAccess.flushForReplacement(transport, connector, System.nanoTime()));
() -> transport.flushForReplacement(connector, System.nanoTime()));
verify(connector).start();
}
@Test
void closeNeverWaitsForSetupOnTheCallingThread() throws Exception {
HttpBackendProxyTransport transport = HttpBackendProxyTransportAccess.create(mock(VotingPluginMain.class));
HttpBackendProxyTransport transport = new HttpBackendProxyTransport(mock(VotingPluginMain.class));
CountDownLatch started = new CountDownLatch(1), release = new CountDownLatch(1);
Thread blocked = new Thread(() -> {
started.countDown();
@@ -536,7 +530,7 @@ class HttpBackendProxyTransportTest {
assertTrue(started.await(1, TimeUnit.SECONDS));
java.lang.reflect.Field worker = HttpBackendProxyTransport.class.getDeclaredField("worker");
worker.setAccessible(true);
ReflectiveAccess.set(worker, transport, blocked);
worker.set(transport, blocked);
long startedAt = System.nanoTime();
transport.close();
@@ -547,7 +541,7 @@ class HttpBackendProxyTransportTest {
@Test
void prepareForReplacementSnapshotsThePersistedCredentialGeneration() throws Exception {
HttpBackendProxyTransport transport = HttpBackendProxyTransportAccess.create(mock(VotingPluginMain.class));
HttpBackendProxyTransport transport = new HttpBackendProxyTransport(mock(VotingPluginMain.class));
Path credentials = directory.resolve("http");
HttpTlsIdentity identity = HttpTlsIdentity.loadOrCreate(directory.resolve("replacement-proxy"), "proxy.example.test");
HttpConnectionCode code = new HttpConnectionCode("lobby-1", URI.create("https://proxy.example.test:1297/"),
@@ -557,12 +551,12 @@ class HttpBackendProxyTransportTest {
HttpClientCredentialStore.snapshotActiveGeneration(credentials);
java.lang.reflect.Field directoryField = HttpBackendProxyTransport.class.getDeclaredField("configuredDirectory");
directoryField.setAccessible(true);
ReflectiveAccess.set(directoryField, transport, credentials);
directoryField.set(transport, credentials);
java.lang.reflect.Field connectorField = HttpBackendProxyTransport.class.getDeclaredField("connector");
connectorField.setAccessible(true);
HttpBackendTransportConnector connector = mock(HttpBackendTransportConnector.class);
when(connector.flushOutgoing(org.mockito.ArgumentMatchers.anyLong())).thenReturn(true);
ReflectiveAccess.set(connectorField, transport, connector);
connectorField.set(transport, connector);
assertDoesNotThrow(transport::prepareForReplacement);
java.lang.reflect.Field generationField =
@@ -591,12 +585,12 @@ class HttpBackendProxyTransportTest {
var owners = (java.util.concurrent.ConcurrentHashMap<Path, java.util.concurrent.Semaphore>) ownersField.get(null);
java.util.concurrent.Semaphore predecessor = new java.util.concurrent.Semaphore(0);
owners.put(credentials.toAbsolutePath().normalize(), predecessor);
HttpBackendProxyTransport transport = HttpBackendProxyTransportAccess.create(plugin);
HttpBackendProxyTransport transport = new HttpBackendProxyTransport(plugin);
transport.start(mock(GlobalMessageHandler.class));
java.util.concurrent.atomic.AtomicReference<Throwable> failure = new java.util.concurrent.atomic.AtomicReference<>();
CountDownLatch finished = new CountDownLatch(1);
Thread validation = new Thread(() -> {
try { HttpBackendProxyTransportAccess.validate(transport, System.nanoTime() + TimeUnit.SECONDS.toNanos(1)); }
try { transport.validate(System.nanoTime() + TimeUnit.SECONDS.toNanos(1)); }
catch (Throwable thrown) { failure.set(thrown); }
finally { finished.countDown(); }
});
@@ -617,32 +611,32 @@ class HttpBackendProxyTransportTest {
void preparedHandoffMessagesStayAheadOfNewlyPublishedSendsWhenConnectorIsFull() throws Exception {
VotingPluginMain plugin = mock(VotingPluginMain.class);
when(plugin.getLogger()).thenReturn(java.util.logging.Logger.getAnonymousLogger());
HttpBackendProxyTransport transport = HttpBackendProxyTransportAccess.create(plugin);
HttpBackendProxyTransport transport = new HttpBackendProxyTransport(plugin);
HttpBackendTransportConnector connector = mock(HttpBackendTransportConnector.class);
when(connector.send(org.mockito.ArgumentMatchers.any(JsonEnvelope.class))).thenReturn(false);
setField(transport, "connector", connector);
JsonEnvelope acceptedBeforePublication = JsonEnvelope.builder("old").build();
JsonEnvelope sentAfterPublication = JsonEnvelope.builder("new").build();
HttpBackendProxyTransportAccess.beginPreparedHandoff(transport);
transport.beginPreparedHandoff();
transport.send(sentAfterPublication);
HttpBackendProxyTransportAccess.acceptHandoffMessages(transport, List.of(acceptedBeforePublication));
transport.acceptHandoffMessages(List.of(acceptedBeforePublication));
assertEquals(List.of(acceptedBeforePublication, sentAfterPublication), HttpBackendProxyTransportAccess.handoffMessagesSnapshot(transport));
assertEquals(List.of(acceptedBeforePublication, sentAfterPublication), transport.handoffMessagesSnapshot());
transport.close();
}
@Test
@SuppressWarnings("unchecked")
void shutdownManagerRemainderStaysBehindAlreadyTransferredPrefix() throws Exception {
HttpBackendProxyTransport transport = HttpBackendProxyTransportAccess.create(mock(VotingPluginMain.class));
HttpBackendProxyTransport transport = new HttpBackendProxyTransport(mock(VotingPluginMain.class));
JsonEnvelope olderPrefix = JsonEnvelope.builder("older-prefix").build();
JsonEnvelope newerRemainder = JsonEnvelope.builder("newer-remainder").build();
((java.util.ArrayDeque<JsonEnvelope>) field(transport, "handoffQueue")).addLast(olderPrefix);
HttpBackendProxyTransportAccess.appendShutdownHandoffMessages(transport, List.of(newerRemainder));
transport.appendShutdownHandoffMessages(List.of(newerRemainder));
assertEquals(List.of(olderPrefix, newerRemainder), HttpBackendProxyTransportAccess.handoffMessagesSnapshot(transport));
assertEquals(List.of(olderPrefix, newerRemainder), transport.handoffMessagesSnapshot());
transport.close();
}
@@ -653,8 +647,8 @@ class HttpBackendProxyTransportTest {
when(plugin.getLogger()).thenReturn(java.util.logging.Logger.getAnonymousLogger());
BackendProxyTransportManager previous = new BackendProxyTransportManager(plugin);
BackendProxyTransportManager replacement = new BackendProxyTransportManager(plugin);
HttpBackendProxyTransport oldTransport = HttpBackendProxyTransportAccess.create(plugin);
HttpBackendProxyTransport newTransport = HttpBackendProxyTransportAccess.create(plugin);
HttpBackendProxyTransport oldTransport = new HttpBackendProxyTransport(plugin);
HttpBackendProxyTransport newTransport = new HttpBackendProxyTransport(plugin);
setField(previous, "preparedTransport", oldTransport);
setField(replacement, "transport", newTransport);
java.util.ArrayDeque<JsonEnvelope> oldQueue =
@@ -683,12 +677,12 @@ class HttpBackendProxyTransportTest {
assertDoesNotThrow(() -> previous.completePreparedTransportHandoff(replacement));
replacement.awaitAsyncHandoff(System.nanoTime() + TimeUnit.SECONDS.toNanos(2));
List<JsonEnvelope> queued = HttpBackendProxyTransportAccess.handoffMessagesSnapshot(newTransport);
List<JsonEnvelope> queued = newTransport.handoffMessagesSnapshot();
assertEquals(4096, queued.size());
assertEquals(oldMessages, queued.subList(0, 2048));
assertEquals(preparedMessages, queued.subList(2048, 3072));
assertEquals(replacementMessages.subList(0, 1024), queued.subList(3072, 4096));
assertEquals(0, HttpBackendProxyTransportAccess.preparedMessageCount(oldTransport));
assertEquals(0, oldTransport.preparedMessageCount());
assertTrue(((java.util.ArrayDeque<JsonEnvelope>) field(previous, "preparedSends")).isEmpty());
newTransport.close();
}
@@ -699,8 +693,8 @@ class HttpBackendProxyTransportTest {
VotingPluginMain plugin = mock(VotingPluginMain.class);
BackendProxyTransportManager previous = new BackendProxyTransportManager(plugin);
BackendProxyTransportManager replacement = new BackendProxyTransportManager(plugin);
HttpBackendProxyTransport oldTransport = HttpBackendProxyTransportAccess.create(plugin);
HttpBackendProxyTransport newTransport = HttpBackendProxyTransportAccess.create(plugin);
HttpBackendProxyTransport oldTransport = new HttpBackendProxyTransport(plugin);
HttpBackendProxyTransport newTransport = new HttpBackendProxyTransport(plugin);
setField(previous, "preparedTransport", oldTransport);
setField(replacement, "transport", newTransport);
java.util.ArrayDeque<JsonEnvelope> oldQueue =
@@ -724,8 +718,8 @@ class HttpBackendProxyTransportTest {
when(plugin.getLogger()).thenReturn(java.util.logging.Logger.getAnonymousLogger());
BackendProxyTransportManager previous = new BackendProxyTransportManager(plugin);
BackendProxyTransportManager replacement = new BackendProxyTransportManager(plugin);
HttpBackendProxyTransport oldTransport = HttpBackendProxyTransportAccess.create(plugin);
HttpBackendProxyTransport newTransport = HttpBackendProxyTransportAccess.create(plugin);
HttpBackendProxyTransport oldTransport = new HttpBackendProxyTransport(plugin);
HttpBackendProxyTransport newTransport = new HttpBackendProxyTransport(plugin);
setField(previous, "preparedTransport", oldTransport);
setField(replacement, "transport", newTransport);
java.util.ArrayDeque<JsonEnvelope> oldQueue =
@@ -745,7 +739,7 @@ class HttpBackendProxyTransportTest {
assertEquals(3072, oldQueue.size());
assertEquals(1024, ((java.util.ArrayDeque<?>) field(previous, "preparedSends")).size());
assertEquals(2, ((java.util.ArrayDeque<?>) field(replacement, "preparedSends")).size());
assertTrue(HttpBackendProxyTransportAccess.handoffMessagesSnapshot(newTransport).isEmpty());
assertTrue(newTransport.handoffMessagesSnapshot().isEmpty());
}
@Test
@@ -754,7 +748,7 @@ class HttpBackendProxyTransportTest {
VotingPluginMain plugin = mock(VotingPluginMain.class);
when(plugin.getLogger()).thenReturn(java.util.logging.Logger.getAnonymousLogger());
BackendProxyTransportManager manager = new BackendProxyTransportManager(plugin);
HttpBackendProxyTransport transport = HttpBackendProxyTransportAccess.create(plugin);
HttpBackendProxyTransport transport = new HttpBackendProxyTransport(plugin);
setField(manager, "transport", transport);
setField(transport, "managerHandoffActive", true);
java.util.ArrayDeque<JsonEnvelope> httpQueue =
@@ -778,7 +772,7 @@ class HttpBackendProxyTransportTest {
when(plugin.getLogger()).thenReturn(java.util.logging.Logger.getAnonymousLogger());
BackendProxyTransportManager previous = new BackendProxyTransportManager(plugin);
BackendProxyTransportManager replacement = new BackendProxyTransportManager(plugin);
HttpBackendProxyTransport oldTransport = HttpBackendProxyTransportAccess.create(plugin);
HttpBackendProxyTransport oldTransport = new HttpBackendProxyTransport(plugin);
HttpBackendProxyTransport newTransport = mock(HttpBackendProxyTransport.class);
JsonEnvelope envelope = JsonEnvelope.builder("accepted-once").build();
CountDownLatch sending = new CountDownLatch(1);
@@ -807,7 +801,8 @@ class HttpBackendProxyTransportTest {
closing.join(TimeUnit.SECONDS.toMillis(2));
assertFalse(closing.isAlive());
verify(newTransport).send(envelope);
HttpBackendProxyTransportAccess.acceptHandoffMessages(verify(newTransport, org.mockito.Mockito.never()), org.mockito.ArgumentMatchers.anyList());
verify(newTransport, org.mockito.Mockito.never())
.acceptHandoffMessages(org.mockito.ArgumentMatchers.anyList());
}
@Test
@@ -817,8 +812,8 @@ class HttpBackendProxyTransportTest {
when(plugin.getLogger()).thenReturn(java.util.logging.Logger.getAnonymousLogger());
BackendProxyTransportManager previous = new BackendProxyTransportManager(plugin);
BackendProxyTransportManager replacement = new BackendProxyTransportManager(plugin);
HttpBackendProxyTransport oldTransport = HttpBackendProxyTransportAccess.create(plugin);
HttpBackendProxyTransport newTransport = HttpBackendProxyTransportAccess.create(plugin);
HttpBackendProxyTransport oldTransport = new HttpBackendProxyTransport(plugin);
HttpBackendProxyTransport newTransport = new HttpBackendProxyTransport(plugin);
HttpBackendTransportConnector connector = mock(HttpBackendTransportConnector.class);
JsonEnvelope source = JsonEnvelope.builder("source").build();
JsonEnvelope adapted = JsonEnvelope.builder("adapted").build();
@@ -879,7 +874,7 @@ class HttpBackendProxyTransportTest {
VotingPluginMain plugin = mock(VotingPluginMain.class);
when(plugin.getLogger()).thenReturn(java.util.logging.Logger.getAnonymousLogger());
BackendProxyTransportManager manager = new BackendProxyTransportManager(plugin);
HttpBackendProxyTransport transport = HttpBackendProxyTransportAccess.create(plugin);
HttpBackendProxyTransport transport = new HttpBackendProxyTransport(plugin);
HttpBackendTransportConnector connector = mock(HttpBackendTransportConnector.class);
JsonEnvelope envelope = JsonEnvelope.builder("shutdown").build();
CountDownLatch sending = new CountDownLatch(1);
@@ -946,8 +941,8 @@ class HttpBackendProxyTransportTest {
VotingPluginMain plugin = mock(VotingPluginMain.class);
BackendProxyTransportManager previous = new BackendProxyTransportManager(plugin);
BackendProxyTransportManager replacement = new BackendProxyTransportManager(plugin);
HttpBackendProxyTransport oldTransport = HttpBackendProxyTransportAccess.create(plugin);
HttpBackendProxyTransport newTransport = HttpBackendProxyTransportAccess.create(plugin);
HttpBackendProxyTransport oldTransport = new HttpBackendProxyTransport(plugin);
HttpBackendProxyTransport newTransport = new HttpBackendProxyTransport(plugin);
JsonEnvelope old = JsonEnvelope.builder("old").build();
JsonEnvelope prepared = JsonEnvelope.builder("prepared").build();
setField(previous, "preparedTransport", oldTransport);
@@ -961,7 +956,7 @@ class HttpBackendProxyTransportTest {
assertThrows(IllegalStateException.class, () -> previous.completePreparedTransportHandoff(replacement));
assertEquals(List.of(old), HttpBackendProxyTransportAccess.preparedMessagesSnapshot(oldTransport));
assertEquals(List.of(old), oldTransport.preparedMessagesSnapshot());
java.util.ArrayDeque<?> retained = (java.util.ArrayDeque<?>) field(previous, "preparedSends");
assertEquals(1, retained.size());
assertSame(prepared, field(retained.peekFirst(), "source"));
@@ -971,13 +966,13 @@ class HttpBackendProxyTransportTest {
@Test
@SuppressWarnings("unchecked")
void preparedDrainPreservesStartupAndExistingHandoffMessagesInFifoOrder() throws Exception {
HttpBackendProxyTransport transport = HttpBackendProxyTransportAccess.create(mock(VotingPluginMain.class));
HttpBackendProxyTransport transport = new HttpBackendProxyTransport(mock(VotingPluginMain.class));
JsonEnvelope startup = JsonEnvelope.builder("startup").build();
JsonEnvelope handoff = JsonEnvelope.builder("handoff").build();
((java.util.ArrayDeque<JsonEnvelope>) field(transport, "startupQueue")).add(startup);
((java.util.ArrayDeque<JsonEnvelope>) field(transport, "handoffQueue")).add(handoff);
assertEquals(List.of(startup, handoff), HttpBackendProxyTransportAccess.drainPreparedMessages(transport));
assertEquals(List.of(startup, handoff), transport.drainPreparedMessages());
assertTrue(((java.util.ArrayDeque<JsonEnvelope>) field(transport, "startupQueue")).isEmpty());
assertTrue(((java.util.ArrayDeque<JsonEnvelope>) field(transport, "handoffQueue")).isEmpty());
}
@@ -987,7 +982,7 @@ class HttpBackendProxyTransportTest {
void rollbackRecreateKeepsAnOversizedCombinedQueueInTheDrainedHandoffLane() throws Exception {
VotingPluginMain plugin = mock(VotingPluginMain.class);
when(plugin.getLogger()).thenReturn(java.util.logging.Logger.getAnonymousLogger());
HttpBackendProxyTransport transport = HttpBackendProxyTransportAccess.create(plugin);
HttpBackendProxyTransport transport = new HttpBackendProxyTransport(plugin);
Path credentials = directory.resolve("http");
setField(transport, "configuredDirectory", credentials);
setField(transport, "configuredServerId", "lobby-1");
@@ -1014,7 +1009,7 @@ class HttpBackendProxyTransportTest {
HttpBackendProxyTransport restored = null;
Thread setup = null;
try {
restored = HttpBackendProxyTransportAccess.recreatePrepared(transport);
restored = transport.recreatePrepared();
assertTrue(((java.util.ArrayDeque<JsonEnvelope>) field(restored, "startupQueue")).isEmpty(),
"rollback must not synchronously overfill the connector's 1024-entry queue");
assertEquals(queued,
@@ -1036,7 +1031,7 @@ class HttpBackendProxyTransportTest {
when(plugin.getLogger()).thenReturn(java.util.logging.Logger.getAnonymousLogger());
BackendProxyTransportManager manager = new BackendProxyTransportManager(plugin);
HttpBackendProxyTransport previous = mock(HttpBackendProxyTransport.class);
HttpBackendProxyTransport restored = HttpBackendProxyTransportAccess.create(plugin);
HttpBackendProxyTransport restored = new HttpBackendProxyTransport(plugin);
java.util.ArrayDeque<JsonEnvelope> restoredQueue =
(java.util.ArrayDeque<JsonEnvelope>) field(restored, "handoffQueue");
for (int index = 0; index < 4096; index++)
@@ -1044,29 +1039,29 @@ class HttpBackendProxyTransportTest {
JsonEnvelope first = JsonEnvelope.builder("fenced-1").build();
JsonEnvelope second = JsonEnvelope.builder("fenced-2").build();
setField(manager, "preparedTransport", previous);
when(HttpBackendProxyTransportAccess.recreatePrepared(previous)).thenReturn(restored);
when(previous.recreatePrepared()).thenReturn(restored);
manager.send(first);
manager.send(second);
manager.restorePreparedTransport();
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(2);
while (HttpBackendProxyTransportAccess.handoffMessagesSnapshot(restored).size() != 4098 && System.nanoTime() < deadline)
while (restored.handoffMessagesSnapshot().size() != 4098 && System.nanoTime() < deadline)
Thread.onSpinWait();
assertEquals(4098, HttpBackendProxyTransportAccess.handoffMessagesSnapshot(restored).size());
assertSame(first, HttpBackendProxyTransportAccess.handoffMessagesSnapshot(restored).get(4096));
assertSame(second, HttpBackendProxyTransportAccess.handoffMessagesSnapshot(restored).get(4097));
assertEquals(4098, restored.handoffMessagesSnapshot().size());
assertSame(first, restored.handoffMessagesSnapshot().get(4096));
assertSame(second, restored.handoffMessagesSnapshot().get(4097));
assertTrue(((java.util.ArrayDeque<?>) field(manager, "asyncHandoffSends")).isEmpty());
manager.send(JsonEnvelope.builder("newer-rejected").build());
assertEquals(4098, HttpBackendProxyTransportAccess.handoffMessagesSnapshot(restored).size(),
assertEquals(4098, restored.handoffMessagesSnapshot().size(),
"normal sends must not expand the one-time rollback recovery allowance");
}
@Test
@SuppressWarnings("unchecked")
void shutdownCanAppendTheReservedRollbackRemainder() throws Exception {
HttpBackendProxyTransport transport = HttpBackendProxyTransportAccess.create(mock(VotingPluginMain.class));
HttpBackendProxyTransport transport = new HttpBackendProxyTransport(mock(VotingPluginMain.class));
java.util.ArrayDeque<JsonEnvelope> handoff =
(java.util.ArrayDeque<JsonEnvelope>) field(transport, "handoffQueue");
for (int index = 0; index < 4096; index++)
@@ -1074,12 +1069,12 @@ class HttpBackendProxyTransportTest {
JsonEnvelope first = JsonEnvelope.builder("fenced-1").build();
JsonEnvelope second = JsonEnvelope.builder("fenced-2").build();
HttpBackendProxyTransportAccess.activateRestoredHandoffDrain(transport, 2);
HttpBackendProxyTransportAccess.appendShutdownHandoffMessages(transport, List.of(first, second));
transport.activateRestoredHandoffDrain(2);
transport.appendShutdownHandoffMessages(List.of(first, second));
assertEquals(4098, HttpBackendProxyTransportAccess.handoffMessagesSnapshot(transport).size());
assertSame(first, HttpBackendProxyTransportAccess.handoffMessagesSnapshot(transport).get(4096));
assertSame(second, HttpBackendProxyTransportAccess.handoffMessagesSnapshot(transport).get(4097));
assertEquals(4098, transport.handoffMessagesSnapshot().size());
assertSame(first, transport.handoffMessagesSnapshot().get(4096));
assertSame(second, transport.handoffMessagesSnapshot().get(4097));
}
private static HttpConnectionCode code(String serverId, Instant expiry) {
@@ -1090,7 +1085,7 @@ class HttpBackendProxyTransportTest {
private static void setField(Object target, String name, Object value) throws Exception {
java.lang.reflect.Field field = target.getClass().getDeclaredField(name);
field.setAccessible(true);
ReflectiveAccess.set(field, target, value);
field.set(target, value);
}
private static Object field(Object target, String name) throws Exception {
@@ -1,8 +1,4 @@
package com.bencodez.votingplugin.tests.backendproxy.transport;
import com.bencodez.votingplugin.tests.support.ReflectiveAccess;
import com.bencodez.votingplugin.backendproxy.transport.MqttBackendProxyTransport;
package com.bencodez.votingplugin.backendproxy.transport;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
@@ -38,12 +34,12 @@ class MqttBackendProxyTransportTest {
GlobalMessageHandler messages = mock(GlobalMessageHandler.class);
setField(transport, "messageHandler", messages);
setField(transport, "authenticator", authenticator);
MqttBackendProxyTransportAccess.updateSecurity(transport, authenticator, encryption);
transport.updateSecurity(authenticator, encryption);
JsonEnvelope vote = JsonEnvelope.builder(VotingPluginWire.SUB_VOTE).put("player", "Alex").build();
JsonEnvelope signed = authenticator.sign(encryption.encrypt(vote), Domain.MQTT_PROXY_BACKEND, "proxy-a",
"votingplugin/servers/backend-a");
MqttBackendProxyTransportAccess.acceptAuthenticatedEnvelope(transport, signed, "votingplugin/servers/backend-a");
transport.acceptAuthenticatedEnvelope(signed, "votingplugin/servers/backend-a");
verify(messages).onMessage(org.mockito.ArgumentMatchers.argThat(received ->
VotingPluginWire.SUB_VOTE.equals(received.getSubChannel())
@@ -59,9 +55,9 @@ class MqttBackendProxyTransportTest {
setField(transport, "authenticator", authenticator);
JsonEnvelope vote = JsonEnvelope.builder(VotingPluginWire.SUB_VOTE).put("player", "Alex").build();
MqttBackendProxyTransportAccess.acceptAuthenticatedEnvelope(transport, authenticator.sign(vote, Domain.MQTT_PROXY_BACKEND, "proxy-a", "votingplugin/servers/backend-a"),
transport.acceptAuthenticatedEnvelope(authenticator.sign(vote, Domain.MQTT_PROXY_BACKEND, "proxy-a", "votingplugin/servers/backend-a"),
"votingplugin/servers/backend-a");
MqttBackendProxyTransportAccess.acceptAuthenticatedEnvelope(transport, vote, "votingplugin/servers/backend-a");
transport.acceptAuthenticatedEnvelope(vote, "votingplugin/servers/backend-a");
verify(messages).onMessage(org.mockito.ArgumentMatchers.argThat(received ->
VotingPluginWire.SUB_VOTE.equals(received.getSubChannel())
@@ -80,9 +76,9 @@ class MqttBackendProxyTransportTest {
JsonEnvelope signed = authenticator.sign(vote, Domain.MQTT_PROXY_BACKEND, "proxy-a",
"votingplugin/servers/backend-a");
MqttBackendProxyTransportAccess.acceptAuthenticatedEnvelope(transport, signed, "votingplugin/servers/backend-b");
transport.acceptAuthenticatedEnvelope(signed, "votingplugin/servers/backend-b");
org.mockito.Mockito.verifyNoInteractions(messages);
MqttBackendProxyTransportAccess.acceptAuthenticatedEnvelope(transport, signed, "votingplugin/servers/backend-a");
transport.acceptAuthenticatedEnvelope(signed, "votingplugin/servers/backend-a");
verify(messages).onMessage(org.mockito.ArgumentMatchers.any());
}
@@ -96,6 +92,6 @@ class MqttBackendProxyTransportTest {
private static void setField(Object target, String name, Object value) throws Exception {
Field field = target.getClass().getDeclaredField(name);
field.setAccessible(true);
ReflectiveAccess.set(field, target, value);
field.set(target, value);
}
}
@@ -1,10 +1,4 @@
package com.bencodez.votingplugin.tests.backendproxy.transport;
import com.bencodez.votingplugin.tests.backendproxy.cache.ProcessedVoteCacheAccess;
import com.bencodez.votingplugin.tests.support.ReflectiveAccess;
import com.bencodez.votingplugin.backendproxy.transport.BackendProxyTransportManager;
import com.bencodez.votingplugin.backendproxy.transport.RedisBackendProxyTransport;
package com.bencodez.votingplugin.backendproxy.transport;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
@@ -56,17 +50,17 @@ class RedisBackendProxyTransportTest {
SharedTransportEnvelopeAuthenticator authenticator = authenticator();
TransportEnvelopeEncryption encryption = TransportEnvelopeEncryption.load(
temporaryDirectory.resolve("secretkey.key"), TransportEnvelopeEncryption.Domain.PROXY_BACKEND, true);
RedisBackendProxyTransport transport = new RedisBackendProxyTransport(null, ProcessedVoteCacheAccess.create());
RedisBackendProxyTransport transport = new RedisBackendProxyTransport(null, new ProcessedVoteCache());
GlobalMessageHandler messages = mock(GlobalMessageHandler.class);
setField(transport, "messageHandler", messages);
setField(transport, "authenticator", authenticator);
RedisBackendProxyTransportAccess.updateSecurity(transport, authenticator, encryption);
transport.updateSecurity(authenticator, encryption);
JsonEnvelope vote = JsonEnvelope.builder(VotingPluginWire.SUB_VOTE).put("player", "Alex").build();
JsonEnvelope encrypted = VotingPluginWire.withRedisDeliveryId(encryption.encrypt(vote));
JsonEnvelope signed = authenticator.sign(encrypted, Domain.REDIS_PROXY_BACKEND, "proxy-a",
"VotingPlugin_backend-a");
RedisBackendProxyTransportAccess.acceptAuthenticatedEnvelope(transport, signed, "VotingPlugin_backend-a");
transport.acceptAuthenticatedEnvelope(signed, "VotingPlugin_backend-a");
verify(messages).onMessage(org.mockito.ArgumentMatchers.argThat(received ->
VotingPluginWire.SUB_VOTE.equals(received.getSubChannel())
@@ -76,7 +70,7 @@ class RedisBackendProxyTransportTest {
@Test
void authenticatedVoteIsAcceptedAndUnsignedPresenceIsRejectedBeforeDispatch() throws Exception {
SharedTransportEnvelopeAuthenticator authenticator = authenticator();
RedisBackendProxyTransport transport = new RedisBackendProxyTransport(null, ProcessedVoteCacheAccess.create());
RedisBackendProxyTransport transport = new RedisBackendProxyTransport(null, new ProcessedVoteCache());
GlobalMessageHandler messages = mock(GlobalMessageHandler.class);
setField(transport, "messageHandler", messages);
setField(transport, "authenticator", authenticator);
@@ -85,9 +79,9 @@ class RedisBackendProxyTransportTest {
JsonEnvelope signedVote = authenticator.sign(VotingPluginWire.withRedisDeliveryId(vote),
Domain.REDIS_PROXY_BACKEND, "proxy-a", "VotingPlugin_backend-a");
RedisBackendProxyTransportAccess.acceptAuthenticatedEnvelope(transport, signedVote, "VotingPlugin_backend-a");
RedisBackendProxyTransportAccess.acceptAuthenticatedEnvelope(transport, vote, "VotingPlugin_backend-a");
RedisBackendProxyTransportAccess.acceptAuthenticatedEnvelope(transport, VotingPluginWire.login("Alex",
transport.acceptAuthenticatedEnvelope(signedVote, "VotingPlugin_backend-a");
transport.acceptAuthenticatedEnvelope(vote, "VotingPlugin_backend-a");
transport.acceptAuthenticatedEnvelope(VotingPluginWire.login("Alex",
"00000000-0000-0000-0000-000000000001", "backend-a"), "VotingPlugin_backend-a");
verify(messages).onMessage(org.mockito.ArgumentMatchers.argThat(received ->
@@ -100,7 +94,7 @@ class RedisBackendProxyTransportTest {
@Test
void copiedRedisVoteCannotAuthenticateOnAnotherBackendChannel() throws Exception {
SharedTransportEnvelopeAuthenticator authenticator = authenticator();
RedisBackendProxyTransport transport = new RedisBackendProxyTransport(null, ProcessedVoteCacheAccess.create());
RedisBackendProxyTransport transport = new RedisBackendProxyTransport(null, new ProcessedVoteCache());
GlobalMessageHandler messages = mock(GlobalMessageHandler.class);
setField(transport, "messageHandler", messages);
setField(transport, "authenticator", authenticator);
@@ -108,31 +102,31 @@ class RedisBackendProxyTransportTest {
JsonEnvelope signed = authenticator.sign(vote, Domain.REDIS_PROXY_BACKEND, "proxy-a",
"VotingPlugin_backend-a");
RedisBackendProxyTransportAccess.acceptAuthenticatedEnvelope(transport, signed, "VotingPlugin_backend-b");
transport.acceptAuthenticatedEnvelope(signed, "VotingPlugin_backend-b");
verifyNoInteractions(messages);
RedisBackendProxyTransportAccess.acceptAuthenticatedEnvelope(transport, signed, "VotingPlugin_backend-a");
transport.acceptAuthenticatedEnvelope(signed, "VotingPlugin_backend-a");
verify(messages).onMessage(org.mockito.ArgumentMatchers.any());
}
@Test
void exactAuthenticatedRedisReplayCannotDuplicateVoteProcessing() throws Exception {
SharedTransportEnvelopeAuthenticator authenticator = authenticator();
RedisBackendProxyTransport transport = new RedisBackendProxyTransport(null, ProcessedVoteCacheAccess.create());
RedisBackendProxyTransport transport = new RedisBackendProxyTransport(null, new ProcessedVoteCache());
GlobalMessageHandler messages = mock(GlobalMessageHandler.class);
setField(transport, "messageHandler", messages);
setField(transport, "authenticator", authenticator);
JsonEnvelope signed = authenticator.sign(VotingPluginWire.withRedisDeliveryId(
JsonEnvelope.builder(VotingPluginWire.SUB_VOTE).build()), Domain.REDIS_PROXY_BACKEND, "proxy-a", "VotingPlugin_backend-a");
RedisBackendProxyTransportAccess.acceptAuthenticatedEnvelope(transport, signed, "VotingPlugin_backend-a");
RedisBackendProxyTransportAccess.acceptAuthenticatedEnvelope(transport, signed, "VotingPlugin_backend-a");
transport.acceptAuthenticatedEnvelope(signed, "VotingPlugin_backend-a");
transport.acceptAuthenticatedEnvelope(signed, "VotingPlugin_backend-a");
verify(messages, times(1)).onMessage(org.mockito.ArgumentMatchers.any());
}
@Test
void validationHonorsTlsAndHostnameVerification() {
DefaultJedisClientConfig config = RedisBackendProxyTransportAccess.buildValidationClientConfig(3, "user", "secret",
DefaultJedisClientConfig config = RedisBackendProxyTransport.buildValidationClientConfig(3, "user", "secret",
true);
assertTrue(config.isSsl());
@@ -149,20 +143,20 @@ class RedisBackendProxyTransportTest {
@Test
void validationKeepsTlsDisabledByDefault() {
assertFalse(RedisBackendProxyTransportAccess.buildValidationClientConfig(0, null, null, false).isSsl());
assertFalse(RedisBackendProxyTransport.buildValidationClientConfig(0, null, null, false).isSsl());
}
@Test
void legacyHandoffBufferDegradesAtItsFixedLimit() throws Exception {
RedisBackendProxyTransport transport = new RedisBackendProxyTransport(null, ProcessedVoteCacheAccess.create());
RedisBackendProxyTransport transport = new RedisBackendProxyTransport(null, new ProcessedVoteCache());
GlobalMessageHandler messages = mock(GlobalMessageHandler.class);
Field handler = RedisBackendProxyTransport.class.getDeclaredField("messageHandler");
handler.setAccessible(true);
ReflectiveAccess.set(handler, transport, messages);
handler.set(transport, messages);
JsonEnvelope envelope = JsonEnvelope.builder(VotingPluginWire.SUB_VOTE_UPDATE).build();
for (int index = 0; index <= RedisBackendProxyTransportAccess.MAX_LEGACY_HANDOFF_DELIVERIES; index++) {
RedisBackendProxyTransportAccess.dispatchLegacy(transport, envelope);
for (int index = 0; index <= RedisBackendProxyTransport.MAX_LEGACY_HANDOFF_DELIVERIES; index++) {
transport.dispatchLegacy(envelope);
}
verify(messages, times(1)).onMessage(envelope);
@@ -170,45 +164,45 @@ class RedisBackendProxyTransportTest {
@Test
void legacyHandoffBufferDegradesForAnOversizedEnvelope() throws Exception {
RedisBackendProxyTransport transport = new RedisBackendProxyTransport(null, ProcessedVoteCacheAccess.create());
RedisBackendProxyTransport transport = new RedisBackendProxyTransport(null, new ProcessedVoteCache());
GlobalMessageHandler messages = mock(GlobalMessageHandler.class);
Field handler = RedisBackendProxyTransport.class.getDeclaredField("messageHandler");
handler.setAccessible(true);
ReflectiveAccess.set(handler, transport, messages);
handler.set(transport, messages);
JsonEnvelope envelope = JsonEnvelope.builder(VotingPluginWire.SUB_VOTE_UPDATE)
.put("payload", "x".repeat(ProcessedVoteCache.MAX_LEGACY_REDIS_DELIVERY_BYTES + 1)).build();
RedisBackendProxyTransportAccess.dispatchLegacy(transport, envelope);
transport.dispatchLegacy(envelope);
verify(messages).onMessage(envelope);
}
@Test
void retiredListenerDropsLegacyDeliveriesAfterShutdownTimeout() throws Exception {
RedisBackendProxyTransport transport = new RedisBackendProxyTransport(null, ProcessedVoteCacheAccess.create());
RedisBackendProxyTransport transport = new RedisBackendProxyTransport(null, new ProcessedVoteCache());
GlobalMessageHandler messages = mock(GlobalMessageHandler.class);
Field handler = RedisBackendProxyTransport.class.getDeclaredField("messageHandler");
handler.setAccessible(true);
ReflectiveAccess.set(handler, transport, messages);
RedisBackendProxyTransportAccess.fenceAfterHandoff(transport);
handler.set(transport, messages);
transport.fenceAfterHandoff();
RedisBackendProxyTransportAccess.dispatchLegacy(transport, JsonEnvelope.builder(VotingPluginWire.SUB_VOTE_UPDATE).build());
transport.dispatchLegacy(JsonEnvelope.builder(VotingPluginWire.SUB_VOTE_UPDATE).build());
verifyNoInteractions(messages);
}
@Test
void retiredListenerDoesNotReserveOrDispatchDeliveryIds() throws Exception {
ProcessedVoteCache cache = ProcessedVoteCacheAccess.create();
ProcessedVoteCache cache = new ProcessedVoteCache();
RedisBackendProxyTransport transport = new RedisBackendProxyTransport(null, cache);
GlobalMessageHandler messages = mock(GlobalMessageHandler.class);
Field handler = RedisBackendProxyTransport.class.getDeclaredField("messageHandler");
handler.setAccessible(true);
ReflectiveAccess.set(handler, transport, messages);
RedisBackendProxyTransportAccess.fenceAfterHandoff(transport);
handler.set(transport, messages);
transport.fenceAfterHandoff();
String deliveryId = "00000000-0000-0000-0000-000000000001";
RedisBackendProxyTransportAccess.dispatchIdentified(transport, JsonEnvelope.builder(VotingPluginWire.SUB_VOTE_UPDATE).build(), deliveryId);
transport.dispatchIdentified(JsonEnvelope.builder(VotingPluginWire.SUB_VOTE_UPDATE).build(), deliveryId);
assertTrue(cache.reserveRedisDelivery(deliveryId), "retired listener must not consume shared deduplication state");
verifyNoInteractions(messages);
@@ -216,7 +210,7 @@ class RedisBackendProxyTransportTest {
@Test
void standbyBuffersIdentifiedDeliveriesUntilItIsPublished() throws Exception {
ProcessedVoteCache cache = ProcessedVoteCacheAccess.create();
ProcessedVoteCache cache = new ProcessedVoteCache();
cache.registerRedisSubscriber(new Object());
RedisBackendProxyTransport transport = new RedisBackendProxyTransport(null, cache);
Field identity = RedisBackendProxyTransport.class.getDeclaredField("subscriberIdentity");
@@ -228,12 +222,12 @@ class RedisBackendProxyTransportTest {
GlobalMessageHandler messages = mock(GlobalMessageHandler.class);
Field handler = RedisBackendProxyTransport.class.getDeclaredField("messageHandler");
handler.setAccessible(true);
ReflectiveAccess.set(handler, transport, messages);
handler.set(transport, messages);
String deliveryId = "00000000-0000-0000-0000-000000000002";
JsonEnvelope envelope = JsonEnvelope.builder(VotingPluginWire.SUB_VOTE_UPDATE)
.put(VotingPluginWire.K_REDIS_DELIVERY_ID, deliveryId).build();
RedisBackendProxyTransportAccess.dispatchIdentified(transport, envelope, deliveryId);
transport.dispatchIdentified(envelope, deliveryId);
verifyNoInteractions(messages);
transport.activateAfterHandoff();
@@ -258,8 +252,8 @@ class RedisBackendProxyTransportTest {
JsonEnvelope identified = JsonEnvelope.builder("identified")
.put(VotingPluginWire.K_REDIS_DELIVERY_ID, deliveryId).build();
RedisBackendProxyTransportAccess.dispatchLegacy(transport, legacy);
RedisBackendProxyTransportAccess.dispatchIdentified(transport, identified, deliveryId);
transport.dispatchLegacy(legacy);
transport.dispatchIdentified(identified, deliveryId);
transport.activateAfterHandoff();
transport.replayAfterHandoffPublication();
@@ -270,7 +264,7 @@ class RedisBackendProxyTransportTest {
@Test
void legacyCopiesDoNotExposeReliableDeliveryIdentity() throws Exception {
ProcessedVoteCache cache = ProcessedVoteCacheAccess.create();
ProcessedVoteCache cache = new ProcessedVoteCache();
RedisBackendProxyTransport transport = new RedisBackendProxyTransport(null, cache);
Field identity = RedisBackendProxyTransport.class.getDeclaredField("subscriberIdentity");
identity.setAccessible(true);
@@ -281,7 +275,7 @@ class RedisBackendProxyTransportTest {
JsonEnvelope mixed = JsonEnvelope.builder(VotingPluginWire.SUB_VOTE_UPDATE)
.put(VotingPluginWire.K_REDIS_DELIVERY_ID, deliveryId).put("payload", "legacy").build();
RedisBackendProxyTransportAccess.dispatchLegacy(transport, mixed);
transport.dispatchLegacy(mixed);
org.mockito.ArgumentCaptor<JsonEnvelope> captured = org.mockito.ArgumentCaptor.forClass(JsonEnvelope.class);
verify(messages).onMessage(captured.capture());
@@ -294,9 +288,9 @@ class RedisBackendProxyTransportTest {
RedisBackendProxyTransport transport = new RedisBackendProxyTransport(null, mock(ProcessedVoteCache.class));
setBoolean(transport, "standbySubscriber", true);
setField(transport, "messageHandler", mock(GlobalMessageHandler.class));
for (int index = 0; index <= RedisBackendProxyTransportAccess.MAX_IDENTIFIED_HANDOFF_DELIVERIES; index++) {
for (int index = 0; index <= RedisBackendProxyTransport.MAX_IDENTIFIED_HANDOFF_DELIVERIES; index++) {
String deliveryId = String.format("00000000-0000-0000-0000-%012d", index);
RedisBackendProxyTransportAccess.dispatchIdentified(transport, JsonEnvelope.builder("identified")
transport.dispatchIdentified(JsonEnvelope.builder("identified")
.put(VotingPluginWire.K_REDIS_DELIVERY_ID, deliveryId).build(), deliveryId);
}
@@ -312,7 +306,7 @@ class RedisBackendProxyTransportTest {
JsonEnvelope oversized = JsonEnvelope.builder("legacy")
.put("payload", "x".repeat(ProcessedVoteCache.MAX_LEGACY_REDIS_DELIVERY_BYTES + 1)).build();
RedisBackendProxyTransportAccess.dispatchLegacy(transport, oversized);
transport.dispatchLegacy(oversized);
verifyNoInteractions(messages);
assertThrows(IllegalStateException.class, transport::activateAfterHandoff);
@@ -325,8 +319,8 @@ class RedisBackendProxyTransportTest {
GlobalMessageHandler messages = mock(GlobalMessageHandler.class);
setField(transport, "messageHandler", messages);
for (int index = 0; index <= RedisBackendProxyTransportAccess.MAX_LEGACY_HANDOFF_DELIVERIES; index++)
RedisBackendProxyTransportAccess.dispatchLegacy(transport, JsonEnvelope.builder("legacy-" + index).build());
for (int index = 0; index <= RedisBackendProxyTransport.MAX_LEGACY_HANDOFF_DELIVERIES; index++)
transport.dispatchLegacy(JsonEnvelope.builder("legacy-" + index).build());
verifyNoInteractions(messages);
assertThrows(IllegalStateException.class, transport::activateAfterHandoff);
@@ -334,7 +328,7 @@ class RedisBackendProxyTransportTest {
@Test
void activeLegacyAccountingOverflowAbortsLaggingStandbyPublication() throws Exception {
ProcessedVoteCache cache = ProcessedVoteCacheAccess.create();
ProcessedVoteCache cache = new ProcessedVoteCache();
Object previousIdentity = new Object();
cache.registerRedisSubscriber(previousIdentity);
RedisBackendProxyTransport replacement = new RedisBackendProxyTransport(null, cache);
@@ -352,7 +346,7 @@ class RedisBackendProxyTransportTest {
@Test
void fencingWaitsForAnIdentifiedMessageHandler() throws Exception {
RedisBackendProxyTransport transport = new RedisBackendProxyTransport(null, ProcessedVoteCacheAccess.create());
RedisBackendProxyTransport transport = new RedisBackendProxyTransport(null, new ProcessedVoteCache());
CountDownLatch entered = new CountDownLatch(1);
CountDownLatch release = new CountDownLatch(1);
GlobalMessageHandler messages = mock(GlobalMessageHandler.class);
@@ -367,8 +361,8 @@ class RedisBackendProxyTransportTest {
}).when(messages).onMessage(org.mockito.ArgumentMatchers.any(JsonEnvelope.class));
Field handler = RedisBackendProxyTransport.class.getDeclaredField("messageHandler");
handler.setAccessible(true);
ReflectiveAccess.set(handler, transport, messages);
Thread delivery = new Thread(() -> RedisBackendProxyTransportAccess.dispatchIdentified(transport,
handler.set(transport, messages);
Thread delivery = new Thread(() -> transport.dispatchIdentified(
JsonEnvelope.builder(VotingPluginWire.SUB_VOTE_UPDATE).build(), "delivery"));
delivery.start();
assertTrue(entered.await(1, TimeUnit.SECONDS));
@@ -378,7 +372,7 @@ class RedisBackendProxyTransportTest {
new java.util.concurrent.atomic.AtomicReference<>();
Thread retirement = new Thread(() -> {
try {
RedisBackendProxyTransportAccess.fenceAfterHandoff(transport);
transport.fenceAfterHandoff();
} catch (Throwable failure) {
fenceFailure.set(failure);
} finally {
@@ -422,7 +416,7 @@ class RedisBackendProxyTransportTest {
}).when(messages).onMessage(org.mockito.ArgumentMatchers.any(JsonEnvelope.class));
setField(transport, "messageHandler", messages);
Thread delivery = new Thread(() -> RedisBackendProxyTransportAccess.dispatchLegacy(transport,
Thread delivery = new Thread(() -> transport.dispatchLegacy(
JsonEnvelope.builder(VotingPluginWire.SUB_VOTE_UPDATE).build()));
delivery.start();
assertTrue(callbackEntered.await(1, TimeUnit.SECONDS));
@@ -481,8 +475,8 @@ class RedisBackendProxyTransportTest {
JsonEnvelope identified = JsonEnvelope.builder("identified-overlap").build();
setBoolean(standby, "standbySubscriber", true);
setField(standby, "messageHandler", mock(GlobalMessageHandler.class));
RedisBackendProxyTransportAccess.dispatchLegacy(standby, legacy);
RedisBackendProxyTransportAccess.dispatchIdentified(standby, identified, "00000000-0000-0000-0000-000000001594");
standby.dispatchLegacy(legacy);
standby.dispatchIdentified(identified, "00000000-0000-0000-0000-000000001594");
org.mockito.Mockito.doThrow(new IllegalStateException("standby promotion rejected"))
.when(standby).activateAfterHandoff();
setField(previous, "transport", oldTransport);
@@ -539,13 +533,13 @@ class RedisBackendProxyTransportTest {
setField(replacement, "messageHandler", replacementMessages);
JsonEnvelope envelope = JsonEnvelope.builder(VotingPluginWire.SUB_VOTE_UPDATE).build();
Thread delivery = new Thread(() -> RedisBackendProxyTransportAccess.dispatchLegacy(previous, envelope));
Thread delivery = new Thread(() -> previous.dispatchLegacy(envelope));
delivery.start();
assertTrue(entered.await(1, TimeUnit.SECONDS));
RedisBackendProxyTransportAccess.dispatchLegacy(replacement, envelope);
replacement.dispatchLegacy(envelope);
CountDownLatch promoted = new CountDownLatch(1);
Thread promotion = new Thread(() -> {
RedisBackendProxyTransportAccess.fenceAfterHandoff(previous);
previous.fenceAfterHandoff();
replacement.activateAfterHandoff();
promoted.countDown();
});
@@ -574,7 +568,7 @@ class RedisBackendProxyTransportTest {
JsonEnvelope envelope = invocation.getArgument(0);
order.add(envelope);
if (envelope == replayed) {
Thread arrival = new Thread(() -> RedisBackendProxyTransportAccess.dispatchIdentified(transport, newer, "new-delivery"));
Thread arrival = new Thread(() -> transport.dispatchIdentified(newer, "new-delivery"));
arrival.start();
arrival.join(TimeUnit.SECONDS.toMillis(1));
}
@@ -582,8 +576,8 @@ class RedisBackendProxyTransportTest {
}).when(messages).onMessage(org.mockito.ArgumentMatchers.any(JsonEnvelope.class));
Field handler = RedisBackendProxyTransport.class.getDeclaredField("messageHandler");
handler.setAccessible(true);
ReflectiveAccess.set(handler, transport, messages);
RedisBackendProxyTransportAccess.dispatchLegacy(transport, replayed);
handler.set(transport, messages);
transport.dispatchLegacy(replayed);
transport.activateAfterHandoff();
transport.replayAfterHandoffPublication();
@@ -607,15 +601,15 @@ class RedisBackendProxyTransportTest {
when(cache.consumeLegacyRedisDelivery(org.mockito.ArgumentMatchers.anyString())).thenReturn(false);
RedisBackendProxyTransport transport = new RedisBackendProxyTransport(plugin, cache);
setBoolean(transport, "standbySubscriber", true);
CountDownLatch replayed = new CountDownLatch(RedisBackendProxyTransportAccess.REPLAY_BATCH_SIZE + 1);
CountDownLatch replayed = new CountDownLatch(RedisBackendProxyTransport.REPLAY_BATCH_SIZE + 1);
GlobalMessageHandler messages = mock(GlobalMessageHandler.class);
doAnswer(invocation -> {
replayed.countDown();
return null;
}).when(messages).onMessage(org.mockito.ArgumentMatchers.any(JsonEnvelope.class));
setField(transport, "messageHandler", messages);
for (int index = 0; index <= RedisBackendProxyTransportAccess.REPLAY_BATCH_SIZE; index++)
RedisBackendProxyTransportAccess.dispatchLegacy(transport, JsonEnvelope.builder("replay-" + index).build());
for (int index = 0; index <= RedisBackendProxyTransport.REPLAY_BATCH_SIZE; index++)
transport.dispatchLegacy(JsonEnvelope.builder("replay-" + index).build());
transport.activateAfterHandoff();
transport.replayAfterHandoffPublication();
@@ -636,14 +630,14 @@ class RedisBackendProxyTransportTest {
queueField.setAccessible(true);
@SuppressWarnings("unchecked")
java.util.ArrayDeque<JsonEnvelope> queue = (java.util.ArrayDeque<JsonEnvelope>) queueField.get(transport);
for (int index = 0; index < RedisBackendProxyTransportAccess.MAX_REPLAY_HANDOFF_DELIVERIES; index++)
for (int index = 0; index < RedisBackendProxyTransport.MAX_REPLAY_HANDOFF_DELIVERIES; index++)
queue.addLast(JsonEnvelope.builder("queued-" + index).build());
JsonEnvelope newer = JsonEnvelope.builder("new").build();
CountDownLatch entered = new CountDownLatch(1);
CountDownLatch returned = new CountDownLatch(1);
Thread callback = new Thread(() -> {
entered.countDown();
RedisBackendProxyTransportAccess.dispatchIdentified(transport, newer, "new-delivery");
transport.dispatchIdentified(newer, "new-delivery");
returned.countDown();
});
callback.start();
@@ -668,12 +662,12 @@ class RedisBackendProxyTransportTest {
setField(transport, "messageHandler", mock(GlobalMessageHandler.class));
setBoolean(transport, "replayingHandoff", true);
java.util.ArrayDeque<JsonEnvelope> queue = replayQueue(transport);
for (int index = 0; index < RedisBackendProxyTransportAccess.MAX_REPLAY_HANDOFF_DELIVERIES; index++)
for (int index = 0; index < RedisBackendProxyTransport.MAX_REPLAY_HANDOFF_DELIVERIES; index++)
queue.addLast(JsonEnvelope.builder("queued-" + index).build());
JsonEnvelope received = JsonEnvelope.builder("received").build();
CountDownLatch completed = new CountDownLatch(1);
Thread subscriber = new Thread(() -> {
RedisBackendProxyTransportAccess.dispatchReceivedSubscriberEnvelope(transport, received, "received-delivery");
transport.dispatchReceivedSubscriberEnvelope(received, "received-delivery");
completed.countDown();
});
subscriber.start();
@@ -706,11 +700,11 @@ class RedisBackendProxyTransportTest {
JsonEnvelope before = JsonEnvelope.builder("before").build();
JsonEnvelope during = JsonEnvelope.builder("during").build();
RedisBackendProxyTransportAccess.dispatchIdentified(replacement, before, "before-publication");
replacement.dispatchIdentified(before, "before-publication");
replacement.activateAfterHandoff();
// This is the narrow interval after worker-side promotion but before Bukkit
// opens publication/replay. It has already reserved its Redis identity.
RedisBackendProxyTransportAccess.dispatchIdentified(replacement, during, "during-publication");
replacement.dispatchIdentified(during, "during-publication");
assertEquals(java.util.List.of(before, during), replacement.detachReplayForFailedHandoff());
assertTrue(replayQueue(replacement).isEmpty());
@@ -740,7 +734,7 @@ class RedisBackendProxyTransportTest {
setField(replacement, "messageHandler", messages);
replacement.acceptReplayFromPreviousHandoff(transferred);
JsonEnvelope newer = JsonEnvelope.builder("newer").build();
RedisBackendProxyTransportAccess.dispatchIdentified(replacement, newer, "new-overlap");
replacement.dispatchIdentified(newer, "new-overlap");
replacement.activateAfterHandoff();
replacement.replayAfterHandoffPublication();
@@ -760,7 +754,7 @@ class RedisBackendProxyTransportTest {
JsonEnvelope duringFreeze = JsonEnvelope.builder("during-freeze").build();
CountDownLatch completed = new CountDownLatch(1);
Thread callback = new Thread(() -> {
RedisBackendProxyTransportAccess.dispatchIdentified(previous, duringFreeze, "during-freeze");
previous.dispatchIdentified(duringFreeze, "during-freeze");
completed.countDown();
});
callback.start();
@@ -784,7 +778,7 @@ class RedisBackendProxyTransportTest {
previous.freezeReplayForSuccessiveHandoff();
CountDownLatch callbackDone = new CountDownLatch(1);
Thread callback = new Thread(() -> {
RedisBackendProxyTransportAccess.dispatchIdentified(previous, JsonEnvelope.builder( "during-close").build(), "during-close");
previous.dispatchIdentified(JsonEnvelope.builder("during-close").build(), "during-close");
callbackDone.countDown();
});
callback.start();
@@ -829,7 +823,7 @@ class RedisBackendProxyTransportTest {
@Test
void retiredRedisCleanupDoesNotBlockManagerCloseOnPublicationThread() throws Exception {
BackendProxyTransportManager manager = new BackendProxyTransportManager(null, ProcessedVoteCacheAccess.create());
BackendProxyTransportManager manager = new BackendProxyTransportManager(null, new ProcessedVoteCache());
RedisBackendProxyTransport retired = mock(RedisBackendProxyTransport.class);
CountDownLatch closeEntered = new CountDownLatch(1);
CountDownLatch releaseClose = new CountDownLatch(1);
@@ -866,7 +860,7 @@ class RedisBackendProxyTransportTest {
RedisBackendProxyTransport transport = new RedisBackendProxyTransport(plugin, cache);
setBoolean(transport, "standbySubscriber", true);
setField(transport, "messageHandler", mock(GlobalMessageHandler.class));
RedisBackendProxyTransportAccess.dispatchLegacy(transport, JsonEnvelope.builder("replay").build());
transport.dispatchLegacy(JsonEnvelope.builder("replay").build());
transport.activateAfterHandoff();
transport.replayAfterHandoffPublication();
@@ -895,7 +889,7 @@ class RedisBackendProxyTransportTest {
RedisBackendProxyTransport transport = new RedisBackendProxyTransport(plugin, cache);
setBoolean(transport, "standbySubscriber", true);
setField(transport, "messageHandler", mock(GlobalMessageHandler.class));
RedisBackendProxyTransportAccess.dispatchLegacy(transport, JsonEnvelope.builder("replay").build());
transport.dispatchLegacy(JsonEnvelope.builder("replay").build());
transport.activateAfterHandoff();
transport.replayAfterHandoffPublication();
assertTrue(submitted.await(1, TimeUnit.SECONDS));
@@ -936,8 +930,8 @@ class RedisBackendProxyTransportTest {
return null;
}).when(messages).onMessage(org.mockito.ArgumentMatchers.any(JsonEnvelope.class));
setField(transport, "messageHandler", messages);
RedisBackendProxyTransportAccess.dispatchLegacy(transport, JsonEnvelope.builder("first").build());
RedisBackendProxyTransportAccess.dispatchLegacy(transport, JsonEnvelope.builder("second").build());
transport.dispatchLegacy(JsonEnvelope.builder("first").build());
transport.dispatchLegacy(JsonEnvelope.builder("second").build());
transport.activateAfterHandoff();
transport.replayAfterHandoffPublication();
assertTrue(entered.await(1, TimeUnit.SECONDS));
@@ -967,7 +961,7 @@ class RedisBackendProxyTransportTest {
private static void setField(Object target, String name, Object value) throws Exception {
Field field = target.getClass().getDeclaredField(name);
field.setAccessible(true);
ReflectiveAccess.set(field, target, value);
field.set(target, value);
}
private static java.util.List<JsonEnvelope> preparedSendQueue(BackendProxyTransportManager manager)
@@ -1,8 +1,4 @@
package com.bencodez.votingplugin.tests.backendproxy.transport;
import com.bencodez.votingplugin.backendproxy.transport.MqttBackendProxyTransport;
import com.bencodez.votingplugin.backendproxy.transport.RedisBackendProxyTransport;
import com.bencodez.votingplugin.tests.backendproxy.transport.SharedInboundPolicyAccess;
package com.bencodez.votingplugin.backendproxy.transport;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -28,19 +24,19 @@ class SharedInboundPolicyTest {
SharedTransportEnvelopeAuthenticator required = SharedTransportEnvelopeAuthenticator.load(keyFile, Mode.REQUIRED);
TransportEnvelopeEncryption encrypted = TransportEnvelopeEncryption.load(keyFile,
TransportEnvelopeEncryption.Domain.PROXY_BACKEND, true);
SharedInboundPolicyAccess policy = new SharedInboundPolicyAccess(RedisBackendProxyTransport.class, "vp:a", required,
SharedInboundPolicy policy = new SharedInboundPolicy(RedisBackendProxyTransport.class, "vp:a", required,
encrypted);
assertTrue(policy.hasEquivalentPolicy(new SharedInboundPolicyAccess(RedisBackendProxyTransport.class, "vp:a",
assertTrue(policy.hasEquivalentPolicy(new SharedInboundPolicy(RedisBackendProxyTransport.class, "vp:a",
SharedTransportEnvelopeAuthenticator.load(keyFile, Mode.REQUIRED), TransportEnvelopeEncryption.load(keyFile,
TransportEnvelopeEncryption.Domain.PROXY_BACKEND, true))));
assertFalse(policy.hasEquivalentPolicy(new SharedInboundPolicyAccess(RedisBackendProxyTransport.class, "vp:b",
assertFalse(policy.hasEquivalentPolicy(new SharedInboundPolicy(RedisBackendProxyTransport.class, "vp:b",
SharedTransportEnvelopeAuthenticator.load(keyFile, Mode.REQUIRED), encrypted)));
assertFalse(policy.hasEquivalentPolicy(new SharedInboundPolicyAccess(MqttBackendProxyTransport.class, "vp:a",
assertFalse(policy.hasEquivalentPolicy(new SharedInboundPolicy(MqttBackendProxyTransport.class, "vp:a",
SharedTransportEnvelopeAuthenticator.load(keyFile, Mode.REQUIRED), encrypted)));
assertFalse(policy.hasEquivalentPolicy(new SharedInboundPolicyAccess(RedisBackendProxyTransport.class, "vp:a",
assertFalse(policy.hasEquivalentPolicy(new SharedInboundPolicy(RedisBackendProxyTransport.class, "vp:a",
SharedTransportEnvelopeAuthenticator.load(keyFile, Mode.COMPATIBILITY), encrypted)));
assertFalse(policy.hasEquivalentPolicy(new SharedInboundPolicyAccess(RedisBackendProxyTransport.class, "vp:a",
assertFalse(policy.hasEquivalentPolicy(new SharedInboundPolicy(RedisBackendProxyTransport.class, "vp:a",
SharedTransportEnvelopeAuthenticator.load(keyFile, Mode.REQUIRED), TransportEnvelopeEncryption.load(keyFile,
TransportEnvelopeEncryption.Domain.PROXY_BACKEND, false))));
}
@@ -1,4 +1,4 @@
package com.bencodez.votingplugin.tests.build;
package com.bencodez.votingplugin.build;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -1,6 +1,4 @@
package com.bencodez.votingplugin.tests.commands;
import com.bencodez.votingplugin.commands.AdminAuthorization;
package com.bencodez.votingplugin.commands;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -1,7 +1,4 @@
package com.bencodez.votingplugin.tests.commands;
import com.bencodez.votingplugin.commands.AdminAuthorization;
import com.bencodez.votingplugin.commands.CommandLoader;
package com.bencodez.votingplugin.commands;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertSame;
@@ -29,12 +26,12 @@ class CommandLoaderBulkPermissionTest {
PlayerCommandHandler handler = mock(PlayerCommandHandler.class);
try {
PlayerCommandHandler.class.getMethod("withAllPermissionOverrides", String[].class);
assertSame(handler, CommandLoaderAccess.configureAllPermissionOverride(handler,
assertSame(handler, CommandLoader.configureAllPermissionOverride(handler,
AdminAuthorization.ADMIN_PERMISSION));
assertTrue(mockingDetails(handler).getInvocations().stream()
.anyMatch(invocation -> invocation.getMethod().getName().equals("withAllPermissionOverrides")));
} catch (NoSuchMethodException exception) {
assertThrows(IllegalStateException.class, () -> CommandLoaderAccess.configureAllPermissionOverride(handler,
assertThrows(IllegalStateException.class, () -> CommandLoader.configureAllPermissionOverride(handler,
AdminAuthorization.ADMIN_PERMISSION));
}
}
@@ -47,7 +44,7 @@ class CommandLoaderBulkPermissionTest {
.thenReturn(List.of("VotingPlugin.Commands.AdminVote.SetPoints.All"));
when(manager.getPermission("VotingPlugin.Commands.AdminVote.SetPoints.All")).thenReturn(null);
CommandLoaderAccess.registerAdditionalPermissions(manager, handler);
CommandLoader.registerAdditionalPermissions(manager, handler);
ArgumentCaptor<Permission> registered = ArgumentCaptor.forClass(Permission.class);
verify(manager).addPermission(registered.capture());
@@ -1,8 +1,6 @@
package com.bencodez.votingplugin.tests.commands;
package com.bencodez.votingplugin.commands;
import com.bencodez.votingplugin.commands.CommandLoader;
import com.bencodez.votingplugin.tests.util.EntityTaskResultTestCompat;
import com.bencodez.votingplugin.util.EntityTaskResultTestCompat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
@@ -22,7 +20,7 @@ import org.junit.jupiter.api.Test;
import com.bencodez.simpleapi.scheduler.BukkitScheduler;
import com.bencodez.simpleapi.folialib.FoliaLib;
import com.bencodez.simpleapi.folialib.impl.PlatformScheduler;
import com.bencodez.simpleapi.folialib.impl.ServerImplementation;
import com.bencodez.votingplugin.VotingPluginMain;
import com.bencodez.votingplugin.config.Config;
import com.bencodez.votingplugin.user.PointTransferResult;
@@ -39,7 +37,7 @@ class CommandLoaderSchedulingTest {
Player sender = mock(Player.class);
Runnable completion = () -> { };
CommandLoaderAccess.runForCommandSender(new CommandLoader(plugin), sender, completion);
new CommandLoader(plugin).runForCommandSender(sender, completion);
verify(scheduler).runTask(eq(plugin), any(Runnable.class), eq(sender));
verify(scheduler, never()).runTask(eq(plugin), any(Runnable.class));
@@ -54,7 +52,7 @@ class CommandLoaderSchedulingTest {
CommandSender sender = mock(CommandSender.class);
Runnable completion = () -> { };
CommandLoaderAccess.runForCommandSender(new CommandLoader(plugin), sender, completion);
new CommandLoader(plugin).runForCommandSender(sender, completion);
verify(scheduler).runTask(eq(plugin), any(Runnable.class));
verify(scheduler, never()).runTask(eq(plugin), any(Runnable.class), any(Player.class));
@@ -71,7 +69,7 @@ class CommandLoaderSchedulingTest {
when(user.getPlayer()).thenReturn(recipient);
Runnable completion = () -> { };
CommandLoaderAccess.runForVotingUser(new CommandLoader(plugin), user, completion);
new CommandLoader(plugin).runForVotingUser(user, completion);
verify(scheduler).runTask(eq(plugin), any(Runnable.class), eq(recipient));
verify(scheduler, never()).runTask(eq(plugin), any(Runnable.class));
@@ -85,7 +83,7 @@ class CommandLoaderSchedulingTest {
VotingPluginUser user = mock(VotingPluginUser.class);
Runnable completion = () -> { };
CommandLoaderAccess.runForVotingUser(new CommandLoader(plugin), user, completion);
new CommandLoader(plugin).runForVotingUser(user, completion);
verify(scheduler).runTask(eq(plugin), any(Runnable.class));
verify(scheduler, never()).runTask(eq(plugin), any(Runnable.class), any(Player.class));
@@ -102,11 +100,11 @@ class CommandLoaderSchedulingTest {
CommandLoader loader = new CommandLoader(plugin);
org.junit.jupiter.api.Assertions.assertEquals("insufficient",
CommandLoaderAccess.transferFailureMessage(loader, PointTransferResult.INSUFFICIENT_POINTS));
org.junit.jupiter.api.Assertions.assertEquals("retry", CommandLoaderAccess.transferFailureMessage(loader, PointTransferResult.CANCELLED));
org.junit.jupiter.api.Assertions.assertEquals("retry", CommandLoaderAccess.transferFailureMessage(loader, PointTransferResult.UNAVAILABLE));
loader.transferFailureMessage(PointTransferResult.INSUFFICIENT_POINTS));
org.junit.jupiter.api.Assertions.assertEquals("retry", loader.transferFailureMessage(PointTransferResult.CANCELLED));
org.junit.jupiter.api.Assertions.assertEquals("retry", loader.transferFailureMessage(PointTransferResult.UNAVAILABLE));
org.junit.jupiter.api.Assertions.assertEquals("pending; do not retry",
CommandLoaderAccess.transferFailureMessage(loader, PointTransferResult.PENDING_CONFIRMATION));
loader.transferFailureMessage(PointTransferResult.PENDING_CONFIRMATION));
}
@Test
@@ -137,7 +135,7 @@ class CommandLoaderSchedulingTest {
.when(storage).execute(any(Runnable.class));
AtomicBoolean storageRan = new AtomicBoolean();
CommandLoaderAccess.runBulkStorageMutation(new CommandLoader(plugin), sender, () -> storageRan.set(true), () -> { });
new CommandLoader(plugin).runBulkStorageMutation(sender, () -> storageRan.set(true), () -> { });
org.junit.jupiter.api.Assertions.assertFalse(storageRan.get());
org.junit.jupiter.api.Assertions.assertNotNull(worker.get());
@@ -161,13 +159,13 @@ class CommandLoaderSchedulingTest {
when(user.getPlayer()).thenReturn(player);
when(plugin.getUserManager().getAllUUIDs())
.thenReturn(new java.util.ArrayList<>(java.util.List.of(uuid.toString())));
when(plugin.getVotingPluginUserManager().getVotingPluginUser(uuid, true)).thenReturn(user);
when(plugin.getVotingPluginUserManager().getVotingPluginUser(uuid)).thenReturn(user);
AtomicReference<Runnable> platform = new AtomicReference<>();
org.mockito.Mockito.doAnswer(call -> { platform.set(call.getArgument(1)); return null; })
.when(scheduler).runTask(eq(plugin), any(Runnable.class));
AtomicReference<CommandLoaderAccess.BulkVotingUsers> delivered = new AtomicReference<>();
AtomicReference<CommandLoader.BulkVotingUsers> delivered = new AtomicReference<>();
CommandLoaderAccess.loadAllVotingUsersAsync(new CommandLoader(plugin), sender, delivered::set);
new CommandLoader(plugin).loadAllVotingUsersAsync(sender, delivered::set);
storageTasks.get(0).run();
verify(user, never()).getPlayer();
platform.get().run();
@@ -193,12 +191,12 @@ class CommandLoaderSchedulingTest {
java.util.List<String> uuids = new java.util.ArrayList<>();
for (int index = 0; index < 65; index++) uuids.add(UUID.randomUUID().toString());
when(plugin.getUserManager().getAllUUIDs()).thenReturn(new java.util.ArrayList<>(uuids));
when(plugin.getVotingPluginUserManager().getVotingPluginUser(any(UUID.class), eq(true))).thenReturn(user);
when(plugin.getVotingPluginUserManager().getVotingPluginUser(any(UUID.class))).thenReturn(user);
java.util.List<Runnable> platformTasks = new java.util.ArrayList<>();
org.mockito.Mockito.doAnswer(call -> { platformTasks.add(call.getArgument(1)); return null; })
.when(scheduler).runTask(eq(plugin), any(Runnable.class));
CommandLoaderAccess.loadAllVotingUsersAsync(new CommandLoader(plugin), sender, ignored -> { });
new CommandLoader(plugin).loadAllVotingUsersAsync(sender, ignored -> { });
storageTasks.get(0).run();
org.junit.jupiter.api.Assertions.assertEquals(1, platformTasks.size());
platformTasks.get(0).run();
@@ -209,53 +207,9 @@ class CommandLoaderSchedulingTest {
org.junit.jupiter.api.Assertions.assertEquals(2, storageTasks.size());
}
@Test void clearingDiscordIdRunsOnTheWorkerAndReportsOnlyAfterConfirmation() throws Exception {
VotingPluginMain plugin = mock(VotingPluginMain.class);
var discord = mock(com.bencodez.votingplugin.discord.DiscordHandler.class);
when(plugin.getDiscordHandler()).thenReturn(discord);
when(discord.clearTopVoterMessageId(com.bencodez.votingplugin.topvoter.TopVoter.Monthly)).thenReturn(true);
var worker = mock(java.util.concurrent.ScheduledExecutorService.class);
when(plugin.getTimer()).thenReturn(worker);
BukkitScheduler scheduler = mock(BukkitScheduler.class); when(plugin.getBukkitScheduler()).thenReturn(scheduler);
var queued = new AtomicReference<Runnable>(); var completion = new AtomicReference<Runnable>();
org.mockito.Mockito.doAnswer(call -> { queued.set(call.getArgument(0)); return null; })
.when(worker).execute(any(Runnable.class));
org.mockito.Mockito.doAnswer(call -> { completion.set(call.getArgument(1)); return null; })
.when(scheduler).runTask(eq(plugin),any(Runnable.class));
CommandSender sender = mock(CommandSender.class);
var method = CommandLoader.class.getDeclaredMethod("clearDiscordMessageId",CommandSender.class,
com.bencodez.votingplugin.topvoter.TopVoter.class); method.setAccessible(true);
method.invoke(new CommandLoader(plugin),sender,com.bencodez.votingplugin.topvoter.TopVoter.Monthly);
org.mockito.Mockito.verifyNoInteractions(discord,sender);
org.junit.jupiter.api.Assertions.assertNotNull(queued.get()); queued.get().run();
verify(discord).clearTopVoterMessageId(com.bencodez.votingplugin.topvoter.TopVoter.Monthly);
org.mockito.Mockito.verifyNoInteractions(sender);
org.junit.jupiter.api.Assertions.assertNotNull(completion.get()); completion.get().run();
verify(sender).sendMessage(org.mockito.ArgumentMatchers.contains("Cleared discord message ID"));
}
@Test void rejectedDiscordIdClearDoesNotTouchStorage() throws Exception {
VotingPluginMain plugin = mock(VotingPluginMain.class);
var discord = mock(com.bencodez.votingplugin.discord.DiscordHandler.class); when(plugin.getDiscordHandler()).thenReturn(discord);
var worker = mock(java.util.concurrent.ScheduledExecutorService.class); when(plugin.getTimer()).thenReturn(worker);
doThrow(new java.util.concurrent.RejectedExecutionException("synthetic")).when(worker).execute(any(Runnable.class));
BukkitScheduler scheduler = mock(BukkitScheduler.class); when(plugin.getBukkitScheduler()).thenReturn(scheduler);
var completion = new AtomicReference<Runnable>();
org.mockito.Mockito.doAnswer(call -> { completion.set(call.getArgument(1)); return null; })
.when(scheduler).runTask(eq(plugin),any(Runnable.class));
CommandSender sender = mock(CommandSender.class);
var method = CommandLoader.class.getDeclaredMethod("clearDiscordMessageId",CommandSender.class,
com.bencodez.votingplugin.topvoter.TopVoter.class); method.setAccessible(true);
method.invoke(new CommandLoader(plugin),sender,com.bencodez.votingplugin.topvoter.TopVoter.Monthly);
org.mockito.Mockito.verifyNoInteractions(discord);verify(plugin,never()).getServerData();
org.junit.jupiter.api.Assertions.assertNotNull(completion.get());completion.get().run();
verify(sender).sendMessage(org.mockito.ArgumentMatchers.contains("no changes made"));
}
private static void configureEntityScheduler(BukkitScheduler scheduler) {
FoliaLib folia = mock(FoliaLib.class);
PlatformScheduler entityScheduler = mock(PlatformScheduler.class);
ServerImplementation entityScheduler = mock(ServerImplementation.class);
when(scheduler.getFoliaLib()).thenReturn(folia);
when(folia.getImpl()).thenReturn(entityScheduler);
when(entityScheduler.runAtEntityWithFallback(any(), any(), any(Runnable.class)))
@@ -1,6 +1,4 @@
package com.bencodez.votingplugin.tests.commands;
import com.bencodez.votingplugin.commands.CommandLoader;
package com.bencodez.votingplugin.commands;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -135,25 +133,20 @@ class OfflineVoteClearCommandRegistrationTest {
}
}
private static final class TestLoader {
private final CommandLoader delegate;
private static final class TestLoader extends CommandLoader {
private final AtomicReference<java.util.function.BooleanSupplier> mutation;
TestLoader(VotingPluginMain plugin, AtomicReference<java.util.function.BooleanSupplier> mutation) {
delegate = org.mockito.Mockito.mock(CommandLoader.class, org.mockito.Mockito.withSettings()
.useConstructor(plugin).defaultAnswer(org.mockito.Mockito.CALLS_REAL_METHODS));
CommandLoaderAccess.runForCommandSender(org.mockito.Mockito.doAnswer(invocation -> {
invocation.getArgument(1, Runnable.class).run();
return null;
}).when(delegate), org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any());
CommandLoaderAccess.runConfirmedBulkStorageMutation(org.mockito.Mockito.doAnswer(invocation -> {
mutation.set(invocation.getArgument(1));
return null;
}).when(delegate), org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any(),
org.mockito.ArgumentMatchers.any());
}
TestLoader(VotingPluginMain plugin, AtomicReference<java.util.function.BooleanSupplier> mutation) {
super(plugin);
this.mutation = mutation;
}
void registerOfflineVoteClearCommands(String permission) {
CommandLoaderAccess.registerOfflineVoteClearCommands(delegate, permission);
}
}
@Override
void runForCommandSender(CommandSender sender, Runnable task) { task.run(); }
@Override
void runConfirmedBulkStorageMutation(CommandSender sender, java.util.function.BooleanSupplier work, Runnable success) {
mutation.set(work);
}
}
}
@@ -1,6 +1,4 @@
package com.bencodez.votingplugin.tests.commands.gui.admin;
import com.bencodez.votingplugin.commands.gui.admin.AdminVotePerms;
package com.bencodez.votingplugin.commands.gui.admin;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
@@ -39,14 +37,14 @@ class AdminVotePermsTest {
"VotingPlugin.Commands.AdminVote.AddPoints.All");
assertEquals(Collections.singletonList("VotingPlugin.Commands.AdminVote.SetPoints.All"),
AdminVotePermsAccess.additionalPermissions(setPoints));
AdminVotePerms.additionalPermissions(setPoints));
assertEquals(Collections.singletonList("VotingPlugin.Commands.AdminVote.AddPoints.All"),
AdminVotePermsAccess.additionalPermissions(addPoints));
AdminVotePerms.additionalPermissions(addPoints));
}
@Test
void ordinaryCommandsDoNotInventAdditionalPermissions() {
assertEquals(Collections.emptyList(), AdminVotePermsAccess.additionalPermissions(mock(CommandHandler.class)));
assertEquals(Collections.emptyList(), AdminVotePerms.additionalPermissions(mock(CommandHandler.class)));
}
@Test
@@ -127,7 +125,7 @@ class AdminVotePermsTest {
void editorPermissionStatusIncludesAdminOverride() {
CommandSender sender = mock(CommandSender.class);
when(sender.hasPermission(AdminAuthorization.ADMIN_PERMISSION)).thenReturn(true);
assertTrue(AdminVotePermsAccess.hasEffectivePermission(sender, "VotingPlugin.Commands.AdminVote.Edit.Config"));
assertTrue(AdminVotePerms.hasEffectivePermission(sender, "VotingPlugin.Commands.AdminVote.Edit.Config"));
}
@Test
@@ -217,7 +215,6 @@ class AdminVotePermsTest {
when(plugin.getVoteCommand()).thenReturn(new ArrayList<>(vote));
when(plugin.getAdminVoteCommand()).thenReturn(new ArrayList<>(admin));
when(plugin.getConfigFile()).thenReturn(config);
when(plugin.getVoteCommandPrefix()).thenReturn("/vote");
when(plugin.getOptions()).thenReturn(options);
when(options.isMultiplePermissionChecks()).thenReturn(multiplePermissions);
when(config.getFormatPageSize()).thenReturn(pageSize);
@@ -1,6 +1,4 @@
package com.bencodez.votingplugin.tests.commands.gui.player;
import com.bencodez.votingplugin.commands.gui.player.VoteGUI;
package com.bencodez.votingplugin.commands.gui.player;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
@@ -38,7 +36,7 @@ class VoteGUIPermissionTest {
assertNotEquals(player.getUniqueId().toString(), viewedUser.getUUID());
assertEquals("VotingPlugin.Commands.Vote.GUI",
VoteGUIAccess.getRequiredPermission(plugin, player, viewedUser));
VoteGUI.getRequiredPermission(plugin, player, viewedUser));
}
@Test
@@ -55,7 +53,7 @@ class VoteGUIPermissionTest {
when(viewedUser.getUUID()).thenReturn(null);
assertEquals("VotingPlugin.Commands.Vote.GUI.Other",
VoteGUIAccess.getRequiredPermission(plugin, player, viewedUser));
VoteGUI.getRequiredPermission(plugin, player, viewedUser));
}
@Test
@@ -72,10 +70,10 @@ class VoteGUIPermissionTest {
when(viewedUser.getUUID()).thenReturn("33333333-3333-3333-3333-333333333333");
assertEquals("VotingPlugin.Commands.Vote.GUI.Other",
VoteGUIAccess.getRequiredPermission(plugin, player, viewedUser));
VoteGUI.getRequiredPermission(plugin, player, viewedUser));
when(player.hasPermission("VotingPlugin.Commands.Vote.GUI.Other")).thenReturn(false, true);
assertFalse(VoteGUIAccess.isAuthorized(plugin, player, viewedUser));
assertTrue(VoteGUIAccess.isAuthorized(plugin, player, viewedUser));
assertFalse(VoteGUI.isAuthorized(plugin, player, viewedUser));
assertTrue(VoteGUI.isAuthorized(plugin, player, viewedUser));
}
@Test
@@ -91,8 +89,8 @@ class VoteGUIPermissionTest {
when(viewedUser.getUUID()).thenReturn("target");
when(player.hasPermission("VotingPlugin.Commands.Vote.GUI.Other")).thenReturn(true, false);
assertTrue(VoteGUIAccess.isAuthorized(plugin, player, viewedUser), "dialog may initially open");
assertFalse(VoteGUIAccess.isAuthorized(plugin, player, viewedUser),
assertTrue(VoteGUI.isAuthorized(plugin, player, viewedUser), "dialog may initially open");
assertFalse(VoteGUI.isAuthorized(plugin, player, viewedUser),
"dialog action must observe a permission revoked after opening");
}
}
@@ -1,6 +1,4 @@
package com.bencodez.votingplugin.tests.commands.gui.player;
import com.bencodez.votingplugin.tests.commands.gui.player.VoteShopCategoryAuthorizationAccess;
package com.bencodez.votingplugin.commands.gui.player;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -22,17 +20,17 @@ class VoteShopCategoryAuthorizationTest {
VoteShopCategoryButton button = button("restricted", "shop.category", false);
VoteShopDefinition definition = definition(button);
assertTrue(VoteShopCategoryAuthorizationAccess.mayDisplay(button, permission -> false));
assertFalse(VoteShopCategoryAuthorizationAccess.authorized(button, permission -> false));
assertFalse(VoteShopCategoryAuthorizationAccess.canOpen(definition, "restricted", permission -> false));
assertTrue(VoteShopCategoryAuthorization.mayDisplay(button, permission -> false));
assertFalse(VoteShopCategoryAuthorization.authorized(button, permission -> false));
assertFalse(VoteShopCategoryAuthorization.canOpen(definition, "restricted", permission -> false));
}
@Test
void hideFlagControlsVisibilityWithoutChangingAuthorization() {
VoteShopCategoryButton hidden = button("restricted", "shop.category", true);
assertFalse(VoteShopCategoryAuthorizationAccess.mayDisplay(hidden, permission -> false));
assertTrue(VoteShopCategoryAuthorizationAccess.mayDisplay(hidden, permission -> true));
assertFalse(VoteShopCategoryAuthorization.mayDisplay(hidden, permission -> false));
assertTrue(VoteShopCategoryAuthorization.mayDisplay(hidden, permission -> true));
}
@Test
@@ -48,11 +46,11 @@ class VoteShopCategoryAuthorizationTest {
child.setId("child");
definition.getCategories().put("child", child);
assertFalse(VoteShopCategoryAuthorizationAccess.canOpen(definition, "child",
assertFalse(VoteShopCategoryAuthorization.canOpen(definition, "child",
Set.of("shop.child")::contains));
assertFalse(VoteShopCategoryAuthorizationAccess.canOpen(definition, "child",
assertFalse(VoteShopCategoryAuthorization.canOpen(definition, "child",
Set.of("shop.parent")::contains));
assertTrue(VoteShopCategoryAuthorizationAccess.canOpen(definition, "child",
assertTrue(VoteShopCategoryAuthorization.canOpen(definition, "child",
Set.of("shop.parent", "shop.child")::contains));
}
@@ -65,14 +63,14 @@ class VoteShopCategoryAuthorizationTest {
category.getEntries().put("item", item);
AtomicBoolean permitted = new AtomicBoolean(true);
assertTrue(VoteShopCategoryAuthorizationAccess.canPurchase(definition, category, item,
assertTrue(VoteShopCategoryAuthorization.canPurchase(definition, category, item,
permission -> permitted.get()));
permitted.set(false);
assertFalse(VoteShopCategoryAuthorizationAccess.canPurchase(definition, category, item,
assertFalse(VoteShopCategoryAuthorization.canPurchase(definition, category, item,
permission -> permitted.get()));
VoteShopItem mainItem = item("main");
definition.getMainEntries().put("main", mainItem);
assertTrue(VoteShopCategoryAuthorizationAccess.canPurchase(definition, null, mainItem, permission -> false));
assertTrue(VoteShopCategoryAuthorization.canPurchase(definition, null, mainItem, permission -> false));
}
@Test
@@ -84,7 +82,7 @@ class VoteShopCategoryAuthorizationTest {
definition.getCategories().remove("restricted");
assertFalse(VoteShopCategoryAuthorizationAccess.canPurchase(definition, staleCategory, item,
assertFalse(VoteShopCategoryAuthorization.canPurchase(definition, staleCategory, item,
permission -> true));
}
@@ -99,7 +97,7 @@ class VoteShopCategoryAuthorizationTest {
replacement.getEntries().put("item", item("item"));
definition.getCategories().put("restricted", replacement);
assertFalse(VoteShopCategoryAuthorizationAccess.canPurchase(definition, staleCategory, staleItem,
assertFalse(VoteShopCategoryAuthorization.canPurchase(definition, staleCategory, staleItem,
permission -> true));
}
@@ -1,6 +1,4 @@
package com.bencodez.votingplugin.tests.commands.gui.player;
import com.bencodez.votingplugin.commands.gui.player.VoteShopConfirm;
package com.bencodez.votingplugin.commands.gui.player;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -12,7 +10,7 @@ class VoteShopConfirmTest {
void confirmationCanSubmitOnlyOnePurchase() {
VoteShopConfirm confirmation = new VoteShopConfirm(null, null, null, null, null);
assertTrue(VoteShopConfirmAccess.beginPurchase(confirmation));
assertFalse(VoteShopConfirmAccess.beginPurchase(confirmation));
assertTrue(confirmation.beginPurchase());
assertFalse(confirmation.beginPurchase());
}
}
@@ -1,6 +1,4 @@
package com.bencodez.votingplugin.tests.control;
import com.bencodez.votingplugin.control.BackendConfigurationService;
package com.bencodez.votingplugin.control;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
@@ -39,7 +37,7 @@ class BackendConfigurationServiceTest {
@Test void transientReadFailuresAreRetried() throws Exception {
AtomicInteger attempts = new AtomicInteger();
String value = BackendConfigurationServiceAccess.retryRead(() -> {
String value = BackendConfigurationService.retryRead(() -> {
if (attempts.incrementAndGet() < 3) throw new IOException("configuration is being replaced");
return "loaded";
});
@@ -49,17 +47,17 @@ class BackendConfigurationServiceTest {
}
@Test void nullYamlCommentMetadataDoesNotBreakControlReads() {
List<String> sanitized = BackendConfigurationServiceAccess.sanitizeComments(
List<String> sanitized = BackendConfigurationService.sanitizeComments(
Arrays.asList(null, "# Token: generated-secret", "# ordinary owner note"),
List.of("generated-secret"), false);
assertEquals(Arrays.asList(null, "# Token: " + BackendConfigurationService.REDACTED,
"# ordinary owner note"), sanitized);
assertEquals(List.of(), BackendConfigurationServiceAccess.sanitizeComments(null, List.of(), false));
assertEquals(List.of(), BackendConfigurationService.sanitizeComments(null, List.of(), false));
}
@Test void malformedQuickReadInputRemainsAValidationFailure() {
BackendConfigurationService service = BackendConfigurationServiceAccess.create(directory, () -> { });
BackendConfigurationService service = new BackendConfigurationService(directory, () -> { });
assertThrows(IllegalArgumentException.class, () -> service.readQuickSetup("vote-site", Map.of()));
assertThrows(IllegalArgumentException.class, () -> service.readQuickSetup("vote-site",
@@ -77,7 +75,7 @@ class BackendConfigurationServiceTest {
Path config = directory.resolve("Config.yml");
Files.writeString(config, "Database:\n Password: keep-me\nFeature: false\n");
AtomicInteger reloads = new AtomicInteger();
BackendConfigurationService service = BackendConfigurationServiceAccess.create(directory, reloads::incrementAndGet);
BackendConfigurationService service = new BackendConfigurationService(directory, reloads::incrementAndGet);
BackendConfigurationService.Document read = service.read("Config.yml");
assertFalse(read.content().contains("keep-me"));
@@ -104,7 +102,7 @@ class BackendConfigurationServiceTest {
+ " Password: keep-me # database credential\n"
+ "Feature: false # toggle from Control\n"
+ "# End of owner notes\n");
BackendConfigurationService service = BackendConfigurationServiceAccess.create(directory, () -> { });
BackendConfigurationService service = new BackendConfigurationService(directory, () -> { });
BackendConfigurationService.Document read = service.read("Config.yml");
assertFalse(read.content().contains("keep-me"));
@@ -141,7 +139,7 @@ class BackendConfigurationServiceTest {
+ "Other: true # Authorization: Bearer old-token\n"
+ "Hook: true # WebhookURL: https://example.invalid/private hook\n"
+ "Quoted: true # DatabasePassword: \"two words\"\n");
BackendConfigurationService.Document read = BackendConfigurationServiceAccess.create(directory, () -> { })
BackendConfigurationService.Document read = new BackendConfigurationService(directory, () -> { })
.read("Config.yml");
assertFalse(read.content().contains("commented-secret"));
@@ -158,7 +156,7 @@ class BackendConfigurationServiceTest {
Path config = directory.resolve("Config.yml");
Files.writeString(config, "# User: database-admin\n# DatabaseUsername=database-owner\nFeature: false\n");
BackendConfigurationService.Document read = BackendConfigurationServiceAccess.create(directory, () -> { })
BackendConfigurationService.Document read = new BackendConfigurationService(directory, () -> { })
.read("Config.yml");
assertFalse(read.content().contains("database-admin"));
@@ -169,7 +167,7 @@ class BackendConfigurationServiceTest {
@Test void redactsSecretsInCommentOnlyDocuments() throws Exception {
Files.writeString(directory.resolve("Config.yml"), "# Password: header-secret\n# owner footer\n");
BackendConfigurationService.Document read = BackendConfigurationServiceAccess.create(directory, () -> { })
BackendConfigurationService.Document read = new BackendConfigurationService(directory, () -> { })
.read("Config.yml");
assertFalse(read.content().contains("header-secret"));
assertTrue(read.content().contains(BackendConfigurationService.REDACTED));
@@ -178,7 +176,7 @@ class BackendConfigurationServiceTest {
@Test void doesNotRewriteHashTextInsideBlockScalars() throws Exception {
Path config = directory.resolve("Config.yml");
Files.writeString(config, "Message: |\n # Password: this is message text\nFeature: false\n");
BackendConfigurationService service = BackendConfigurationServiceAccess.create(directory, () -> { });
BackendConfigurationService service = new BackendConfigurationService(directory, () -> { });
BackendConfigurationService.Document read = service.read("Config.yml");
assertTrue(read.content().contains("# Password: this is message text"));
@@ -191,7 +189,7 @@ class BackendConfigurationServiceTest {
Files.writeString(config, "Password: true\n# DiscordWebhook.URL: https://dotted-secret.invalid/hook\n"
+ "DiscordWebhook:\n URL: '' # \"URL\": https://old-secret.invalid/hook\n"
+ "Feature: false # This is true when enabled\n");
BackendConfigurationService.Document read = BackendConfigurationServiceAccess.create(directory, () -> { })
BackendConfigurationService.Document read = new BackendConfigurationService(directory, () -> { })
.read("Config.yml");
assertFalse(read.content().contains("old-secret.invalid"));
@@ -204,7 +202,7 @@ class BackendConfigurationServiceTest {
Files.writeString(config, "Password: |\n alpha-secret-part\n beta-secret-part\n"
+ "# rotate alpha-secret-part soon\nFeature: false\n");
BackendConfigurationService.Document read = BackendConfigurationServiceAccess.create(directory, () -> { })
BackendConfigurationService.Document read = new BackendConfigurationService(directory, () -> { })
.read("Config.yml");
assertFalse(read.content().contains("alpha-secret-part"));
@@ -215,7 +213,7 @@ class BackendConfigurationServiceTest {
Path config = directory.resolve("Config.yml");
Files.writeString(config, "# Password:\n# real-comment-secret\nFeature: false\n");
BackendConfigurationService.Document read = BackendConfigurationServiceAccess.create(directory, () -> { })
BackendConfigurationService.Document read = new BackendConfigurationService(directory, () -> { })
.read("Config.yml");
assertFalse(read.content().contains("real-comment-secret"));
@@ -225,7 +223,7 @@ class BackendConfigurationServiceTest {
Path config = directory.resolve("Config.yml");
Files.writeString(config, "# Password: |\n# first-comment-secret\n# second-comment-secret\n#\n"
+ "# owner note\nFeature: false\n");
BackendConfigurationService service = BackendConfigurationServiceAccess.create(directory, () -> { });
BackendConfigurationService service = new BackendConfigurationService(directory, () -> { });
BackendConfigurationService.Document read = service.read("Config.yml");
assertFalse(read.content().contains("first-comment-secret"));
@@ -243,7 +241,7 @@ class BackendConfigurationServiceTest {
Files.writeString(config, "# Password: |\n# literal-comment-secret\n"
+ "# Token: >-\n# folded-comment-secret\n"
+ "# ApiKey: |2+\n# indented-comment-secret\nFeature: false\n");
BackendConfigurationService service = BackendConfigurationServiceAccess.create(directory, () -> { });
BackendConfigurationService service = new BackendConfigurationService(directory, () -> { });
BackendConfigurationService.Document read = service.read("Config.yml");
assertFalse(read.content().contains("literal-comment-secret"));
@@ -267,7 +265,7 @@ class BackendConfigurationServiceTest {
@Test void rejectsChangedRedactedCommentPlaceholders() throws Exception {
Files.writeString(directory.resolve("Config.yml"), "# Password: comment-secret\nFeature: false\n");
BackendConfigurationService service = BackendConfigurationServiceAccess.create(directory, () -> { });
BackendConfigurationService service = new BackendConfigurationService(directory, () -> { });
BackendConfigurationService.Document read = service.read("Config.yml");
String changed = read.content().replace("Password: " + BackendConfigurationService.REDACTED,
"Password changed: " + BackendConfigurationService.REDACTED);
@@ -277,7 +275,7 @@ class BackendConfigurationServiceTest {
@Test void rejectsRemovedOrReplacedRedactedCommentPlaceholders() throws Exception {
Files.writeString(directory.resolve("Config.yml"), "# Password: comment-secret\nFeature: false\n");
BackendConfigurationService service = BackendConfigurationServiceAccess.create(directory, () -> { });
BackendConfigurationService service = new BackendConfigurationService(directory, () -> { });
BackendConfigurationService.Document read = service.read("Config.yml");
String removed = read.content().lines().filter(line -> !line.contains(BackendConfigurationService.REDACTED))
.collect(java.util.stream.Collectors.joining("\n")) + "\n";
@@ -291,7 +289,7 @@ class BackendConfigurationServiceTest {
@Test void rejectsRemovingAKeyThatOwnsARedactedComment() throws Exception {
Files.writeString(directory.resolve("Config.yml"),
"Feature: false # Password: inline-comment-secret\nOther: true\n");
BackendConfigurationService service = BackendConfigurationServiceAccess.create(directory, () -> { });
BackendConfigurationService service = new BackendConfigurationService(directory, () -> { });
BackendConfigurationService.Document read = service.read("Config.yml");
assertTrue(read.content().contains(BackendConfigurationService.REDACTED));
@@ -301,7 +299,7 @@ class BackendConfigurationServiceTest {
@Test void comparesRedactedCommentOwnersRegardlessOfMappingOrder() throws Exception {
Files.writeString(directory.resolve("Config.yml"), "Alpha:\n Enabled: true # Password: alpha-secret\n"
+ "Beta:\n Enabled: true # Token: beta-secret\n");
BackendConfigurationService service = BackendConfigurationServiceAccess.create(directory, () -> { });
BackendConfigurationService service = new BackendConfigurationService(directory, () -> { });
BackendConfigurationService.Document read = service.read("Config.yml");
String proposal = "Beta:\n Enabled: false # Token: " + BackendConfigurationService.REDACTED + "\n"
@@ -323,14 +321,14 @@ class BackendConfigurationServiceTest {
< BackendConfigurationService.MAX_CONTENT_BYTES);
Files.writeString(directory.resolve("Config.yml"), raw);
BackendConfigurationService service = BackendConfigurationServiceAccess.create(directory, () -> { });
BackendConfigurationService service = new BackendConfigurationService(directory, () -> { });
assertThrows(IOException.class, () -> service.read("Config.yml"));
}
@Test void reportsCommentOnlyChangesInPreview() throws Exception {
Files.writeString(directory.resolve("Config.yml"), "# original owner note\nFeature: false # old inline note\n");
BackendConfigurationService service = BackendConfigurationServiceAccess.create(directory, () -> { });
BackendConfigurationService service = new BackendConfigurationService(directory, () -> { });
BackendConfigurationService.Document read = service.read("Config.yml");
BackendConfigurationService.Preview preview = service.preview("Config.yml", read.content()
@@ -344,7 +342,7 @@ class BackendConfigurationServiceTest {
Path config = directory.resolve("Config.yml");
Files.writeString(config, "# \"Password\": quoted-comment-secret\nFeature: false\n");
BackendConfigurationService.Document read = BackendConfigurationServiceAccess.create(directory, () -> { })
BackendConfigurationService.Document read = new BackendConfigurationService(directory, () -> { })
.read("Config.yml");
assertFalse(read.content().contains("quoted-comment-secret"));
@@ -352,7 +350,7 @@ class BackendConfigurationServiceTest {
@Test void rejectsStaleInvalidAndUnmanagedWrites() throws Exception {
Files.writeString(directory.resolve("Config.yml"), "Feature: false\n");
BackendConfigurationService service = BackendConfigurationServiceAccess.create(directory, () -> { });
BackendConfigurationService service = new BackendConfigurationService(directory, () -> { });
String revision = service.read("Config.yml").revision();
Files.writeString(directory.resolve("Config.yml"), "Feature: manual\n");
assertThrows(BackendConfigurationService.StaleRevisionException.class,
@@ -367,7 +365,7 @@ class BackendConfigurationServiceTest {
Path externalConfig = outside.resolve("Config.yml");
Files.writeString(externalConfig, "Feature: external\n");
Files.createSymbolicLink(root.resolve("Config.yml"), externalConfig);
BackendConfigurationService service = BackendConfigurationServiceAccess.create(root, () -> { });
BackendConfigurationService service = new BackendConfigurationService(root, () -> { });
assertThrows(java.io.IOException.class, () -> service.read("Config.yml"));
Files.createDirectory(outside.resolve("sites"));
@@ -382,9 +380,9 @@ class BackendConfigurationServiceTest {
Path rewards = Files.createDirectories(directory.resolve("Rewards"));
Files.writeString(rewards.resolve("Daily.yml"), "Commands: []\n");
Files.writeString(rewards.resolve("Standard.yml"), "Messages: {}\n");
BackendConfigurationService service = BackendConfigurationServiceAccess.create(directory, () -> { });
BackendConfigurationService service = new BackendConfigurationService(directory, () -> { });
assertEquals(List.of("Daily.yml", "Standard.yml"), BackendConfigurationServiceAccess.rewardFileInventory(directory));
assertEquals(List.of("Daily.yml", "Standard.yml"), BackendConfigurationService.rewardFileInventory(directory));
assertDoesNotThrow(() -> service.read("Rewards/Daily.yml"));
assertThrows(IllegalArgumentException.class, () -> service.read("Rewards/../Config.yml"));
assertThrows(IllegalArgumentException.class, () -> service.read("Rewards/%2e%2e%2fConfig.yml"));
@@ -396,38 +394,38 @@ class BackendConfigurationServiceTest {
}
@Test void onlyAnAbsentRewardsDirectoryProducesAnEmptyInventory() throws Exception {
assertEquals(List.of(), BackendConfigurationServiceAccess.rewardFileInventory(directory));
assertThrows(IOException.class, () -> BackendConfigurationServiceAccess.rewardFileInventory(directory.resolve("missing")));
assertEquals(List.of(), BackendConfigurationService.rewardFileInventory(directory));
assertThrows(IOException.class, () -> BackendConfigurationService.rewardFileInventory(directory.resolve("missing")));
Files.createDirectory(directory.resolve("Rewards"));
assertThrows(java.nio.file.NoSuchFileException.class,
() -> BackendConfigurationServiceAccess.rewardFileInventory(directory,
() -> BackendConfigurationService.rewardFileInventory(directory,
ignored -> { throw new java.nio.file.NoSuchFileException("disappeared-entry.yml"); }));
}
@Test void namedRewardCapabilityRequiresSecureDirectoryAndPrivateFileSupport() throws Exception {
assertTrue(BackendConfigurationServiceAccess.supportsNamedRewardFiles(directory));
assertTrue(BackendConfigurationService.supportsNamedRewardFiles(directory));
try (var entries = Files.list(directory)) {
assertFalse(entries.anyMatch(path -> path.getFileName().toString().startsWith(".control-capability-")));
}
assertFalse(BackendConfigurationServiceAccess.supportsNamedRewardFiles(directory,
assertFalse(BackendConfigurationService.supportsNamedRewardFiles(directory,
ignored -> { throw new IOException("directory forcing is unavailable"); }));
Path outside = Files.createDirectory(directory.resolve("outside"));
Files.createSymbolicLink(directory.resolve("Rewards"), outside);
assertFalse(BackendConfigurationServiceAccess.supportsNamedRewardFiles(directory));
assertFalse(BackendConfigurationService.supportsNamedRewardFiles(directory));
Files.delete(directory.resolve("Rewards"));
Files.createDirectory(directory.resolve("Rewards"));
assertTrue(BackendConfigurationServiceAccess.supportsNamedRewardFiles(directory));
assertTrue(BackendConfigurationService.supportsNamedRewardFiles(directory));
AtomicInteger checkedRewardDirectory = new AtomicInteger();
assertFalse(BackendConfigurationServiceAccess.supportsNamedRewardFiles(directory,
assertFalse(BackendConfigurationService.supportsNamedRewardFiles(directory,
channel -> channel.force(true), ignored -> {
checkedRewardDirectory.incrementAndGet();
return false;
}));
assertEquals(1, checkedRewardDirectory.get());
assertFalse(BackendConfigurationServiceAccess.supportsNamedRewardFiles(directory,
assertFalse(BackendConfigurationService.supportsNamedRewardFiles(directory,
channel -> channel.force(true),
ignored -> { throw new java.nio.file.NoSuchFileException("vanished-reward-entry"); }));
assertFalse(BackendConfigurationServiceAccess.supportsNamedRewardFiles(directory,
assertFalse(BackendConfigurationService.supportsNamedRewardFiles(directory,
channel -> channel.force(true), pinned -> {
assertTrue(pinned.getFileAttributeView(PosixFileAttributeView.class) != null);
throw new UnsupportedOperationException("private staging creation is unavailable");
@@ -438,21 +436,21 @@ class BackendConfigurationServiceTest {
Path archive = directory.resolve("unsupported.zip");
try (var zip = FileSystems.newFileSystem(URI.create("jar:" + archive.toUri()), Map.of("create", "true"))) {
Path plugin = Files.createDirectory(zip.getPath("/plugin"));
assertFalse(BackendConfigurationServiceAccess.supportsNamedRewardFiles(plugin));
assertFalse(BackendConfigurationService.supportsNamedRewardFiles(plugin));
}
}
@Test void namedRewardCapabilityReprobesAfterTransientStagingFailure() throws Exception {
Files.createDirectory(directory.resolve("Rewards"));
BackendConfigurationService service = BackendConfigurationServiceAccess.create(directory, () -> { });
BackendConfigurationService service = new BackendConfigurationService(directory, () -> { });
AtomicInteger attempts = new AtomicInteger();
BackendConfigurationServiceAccess.DirectoryStagingSupport probe = ignored -> {
BackendConfigurationService.DirectoryStagingSupport probe = ignored -> {
if (attempts.incrementAndGet() == 1) throw new IOException("temporary staging failure");
return true;
};
assertFalse(BackendConfigurationServiceAccess.supportsNamedRewardFiles(service, probe));
assertTrue(BackendConfigurationServiceAccess.supportsNamedRewardFiles(service, probe));
assertTrue(BackendConfigurationServiceAccess.supportsNamedRewardFiles(service, probe));
assertFalse(service.supportsNamedRewardFiles(probe));
assertTrue(service.supportsNamedRewardFiles(probe));
assertTrue(service.supportsNamedRewardFiles(probe));
assertEquals(2, attempts.get(), "only a successful probe may be cached for this directory");
}
@@ -461,7 +459,7 @@ class BackendConfigurationServiceTest {
Path rewards = Files.createDirectories(directory.resolve("Rewards"));
Path file = rewards.resolve("Daily.yml");
Files.writeString(file, "Money: 1\n");
BackendConfigurationService service = BackendConfigurationServiceAccess.create(directory, () -> { });
BackendConfigurationService service = new BackendConfigurationService(directory, () -> { });
String revision = service.read("Rewards/Daily.yml").revision();
service.apply("Rewards/Daily.yml", "Money: 2\n", revision);
@@ -490,7 +488,7 @@ class BackendConfigurationServiceTest {
});
try {
worker.submit(() -> assertThrows(IOException.class,
() -> BackendConfigurationServiceAccess.readRaw(pinned, "Daily.yml", false)))
() -> BackendConfigurationService.readRaw(pinned, "Daily.yml", false)))
.get(2, TimeUnit.SECONDS);
} finally {
worker.shutdownNow();
@@ -516,7 +514,7 @@ class BackendConfigurationServiceTest {
assertEquals("Money: 1\n", expectedContent);
}
};
BackendConfigurationService service = BackendConfigurationServiceAccess.create(directory, reload);
BackendConfigurationService service = new BackendConfigurationService(directory, reload);
String revision = service.read("Rewards/Daily.yml").revision();
BackendConfigurationService.ApplyFailureException failure = assertThrows(
BackendConfigurationService.ApplyFailureException.class,
@@ -531,13 +529,13 @@ class BackendConfigurationServiceTest {
Path outside = directory.resolve("outside.yml");
Files.writeString(outside, "outside: true\n");
Files.createSymbolicLink(rewards.resolve("External.yml"), outside);
assertThrows(IOException.class, () -> BackendConfigurationServiceAccess.rewardFileInventory(directory));
assertThrows(IOException.class, () -> BackendConfigurationService.rewardFileInventory(directory));
Files.delete(rewards.resolve("External.yml"));
Files.writeString(rewards.resolve("Daily.yml"), "one: true\n");
BackendConfigurationService service = BackendConfigurationServiceAccess.create(directory, () -> { });
BackendConfigurationService service = new BackendConfigurationService(directory, () -> { });
String revision = service.read("Rewards/Daily.yml").revision();
Files.writeString(rewards.resolve("daily.yml"), "two: true\n");
assertThrows(IOException.class, () -> BackendConfigurationServiceAccess.rewardFileInventory(directory));
assertThrows(IOException.class, () -> BackendConfigurationService.rewardFileInventory(directory));
assertThrows(IOException.class, () -> service.read("Rewards/Daily.yml"));
assertThrows(IOException.class, () -> service.preview("Rewards/Daily.yml", "one: false\n"));
assertThrows(IOException.class, () -> service.apply("Rewards/Daily.yml", "one: false\n", revision));
@@ -546,22 +544,22 @@ class BackendConfigurationServiceTest {
for (int index = 0; index <= BackendConfigurationService.MAX_REWARD_FILES; index++) {
Files.writeString(rewards.resolve("Reward" + index + ".yml"), "value: true\n");
}
assertThrows(IOException.class, () -> BackendConfigurationServiceAccess.rewardFileInventory(directory));
assertThrows(IOException.class, () -> BackendConfigurationService.rewardFileInventory(directory));
}
@Test void rewardInventoryBoundsIgnoredEntriesBeforeReadPreviewOrApply() throws Exception {
Path rewards = Files.createDirectories(directory.resolve("Rewards"));
Path daily = rewards.resolve("Daily.yml");
Files.writeString(daily, "Money: 1\n");
BackendConfigurationService service = BackendConfigurationServiceAccess.create(directory, () -> { });
BackendConfigurationService service = new BackendConfigurationService(directory, () -> { });
String revision = service.read("Rewards/Daily.yml").revision();
for (int index = 0; index < BackendConfigurationServiceAccess.MAX_REWARD_DIRECTORY_ENTRIES - 1; index++) {
for (int index = 0; index < BackendConfigurationService.MAX_REWARD_DIRECTORY_ENTRIES - 1; index++) {
Files.createDirectory(rewards.resolve("Ignored" + index));
}
assertEquals(List.of("Daily.yml"), BackendConfigurationServiceAccess.rewardFileInventory(directory));
assertEquals(List.of("Daily.yml"), BackendConfigurationService.rewardFileInventory(directory));
assertEquals(revision, service.read("Rewards/Daily.yml").revision());
Files.createDirectory(rewards.resolve("Overflow"));
assertThrows(IOException.class, () -> BackendConfigurationServiceAccess.rewardFileInventory(directory));
assertThrows(IOException.class, () -> BackendConfigurationService.rewardFileInventory(directory));
assertThrows(IOException.class, () -> service.read("Rewards/Daily.yml"));
assertThrows(IOException.class, () -> service.preview("Rewards/Daily.yml", "Money: 2\n"));
assertThrows(IOException.class, () -> service.apply("Rewards/Daily.yml", "Money: 2\n", revision));
@@ -575,7 +573,7 @@ class BackendConfigurationServiceTest {
Files.writeString(rewards.resolve("Daily.yml"), "Money: 1\n");
Files.writeString(outside.resolve("Daily.yml"), "Money: 999\n");
AtomicInteger reloads = new AtomicInteger();
BackendConfigurationService service = BackendConfigurationServiceAccess.create(plugin,
BackendConfigurationService service = new BackendConfigurationService(plugin,
(BackendConfigurationService.ApplyAction) ignored -> {
if (reloads.incrementAndGet() == 1) {
Files.move(rewards, plugin.resolve("Rewards-original"));
@@ -600,7 +598,7 @@ class BackendConfigurationServiceTest {
Files.writeString(rewards.resolve("Daily.yml"), "Money: 1\n");
Files.writeString(replacement.resolve("Daily.yml"), "Money: 999\n");
AtomicInteger reloads = new AtomicInteger();
BackendConfigurationService service = BackendConfigurationServiceAccess.create(plugin,
BackendConfigurationService service = new BackendConfigurationService(plugin,
(BackendConfigurationService.ApplyAction) ignored -> {
if (reloads.incrementAndGet() == 1) {
Files.move(rewards, plugin.resolve("Rewards-original"));
@@ -644,7 +642,7 @@ class BackendConfigurationServiceTest {
assertEquals("Money: 1\n", expectedContent);
}
};
BackendConfigurationService service = BackendConfigurationServiceAccess.create(plugin, reload);
BackendConfigurationService service = new BackendConfigurationService(plugin, reload);
String revision = service.read("Rewards/Daily.yml").revision();
BackendConfigurationService.ApplyFailureException failure = assertThrows(
BackendConfigurationService.ApplyFailureException.class,
@@ -675,7 +673,7 @@ class BackendConfigurationServiceTest {
reloads.incrementAndGet();
}
};
BackendConfigurationService service = BackendConfigurationServiceAccess.create(plugin, action);
BackendConfigurationService service = new BackendConfigurationService(plugin, action);
String revision = service.read("Rewards/Daily.yml").revision();
BackendConfigurationService.ApplyFailureException failure = assertThrows(
BackendConfigurationService.ApplyFailureException.class,
@@ -692,7 +690,7 @@ class BackendConfigurationServiceTest {
Files.writeString(file, "Money: 1\n");
CountDownLatch firstReload = new CountDownLatch(1);
CountDownLatch allowReload = new CountDownLatch(1);
BackendConfigurationService service = BackendConfigurationServiceAccess.create(directory,
BackendConfigurationService service = new BackendConfigurationService(directory,
(BackendConfigurationService.ApplyAction) ignored -> {
firstReload.countDown();
if (!allowReload.await(5, TimeUnit.SECONDS)) throw new IOException("test reload timed out");
@@ -720,7 +718,7 @@ class BackendConfigurationServiceTest {
Files.writeString(config, "Feature: false\n");
Files.writeString(external, "external: preserved\n");
Files.createSymbolicLink(directory.resolve("Config.yml.control-backup"), external);
BackendConfigurationService service = BackendConfigurationServiceAccess.create(directory, () -> { });
BackendConfigurationService service = new BackendConfigurationService(directory, () -> { });
String revision = service.read("Config.yml").revision();
assertThrows(java.io.IOException.class,
@@ -733,7 +731,7 @@ class BackendConfigurationServiceTest {
Path settings = directory.resolve("BungeeSettings.yml");
Files.writeString(settings, "UseBungeecord: false\nBungeeMethod: PLUGINMESSAGING\n");
AtomicInteger reloads = new AtomicInteger();
BackendConfigurationService service = BackendConfigurationServiceAccess.create(directory,
BackendConfigurationService service = new BackendConfigurationService(directory,
(BackendConfigurationService.ApplyAction) fileName -> {
assertEquals("BungeeSettings.yml", fileName);
if (reloads.incrementAndGet() == 1) throw new IllegalStateException("transport unavailable");
@@ -754,7 +752,7 @@ class BackendConfigurationServiceTest {
Files.writeString(config, "Feature: before\n");
AtomicInteger reloads = new AtomicInteger();
AtomicInteger moves = new AtomicInteger();
BackendConfigurationService service = BackendConfigurationServiceAccess.create(directory,
BackendConfigurationService service = new BackendConfigurationService(directory,
(BackendConfigurationService.ApplyAction) fileName -> {
if (reloads.incrementAndGet() == 1) throw new IOException("reload failed");
}, (source, target) -> {
@@ -780,7 +778,7 @@ class BackendConfigurationServiceTest {
Path config = directory.resolve("Config.yml");
Files.writeString(config, "Feature: before\n");
AtomicInteger reloads = new AtomicInteger();
BackendConfigurationService service = BackendConfigurationServiceAccess.create(directory,
BackendConfigurationService service = new BackendConfigurationService(directory,
(BackendConfigurationService.ApplyAction) fileName -> {
reloads.incrementAndGet();
Files.writeString(config, "Feature: manual\n");
@@ -801,7 +799,7 @@ class BackendConfigurationServiceTest {
Path config = directory.resolve("Config.yml");
Files.writeString(config, "Feature: before\n");
AtomicInteger reloads = new AtomicInteger();
BackendConfigurationService service = BackendConfigurationServiceAccess.create(directory,
BackendConfigurationService service = new BackendConfigurationService(directory,
(BackendConfigurationService.ApplyAction) fileName -> {
if (reloads.incrementAndGet() == 1) Files.writeString(config, "Feature: manual\n");
});
@@ -817,7 +815,7 @@ class BackendConfigurationServiceTest {
Path config = directory.resolve("Config.yml");
Files.writeString(config, "Feature: before\n");
AtomicInteger reloads = new AtomicInteger();
BackendConfigurationService service = BackendConfigurationServiceAccess.create(directory,
BackendConfigurationService service = new BackendConfigurationService(directory,
(BackendConfigurationService.ApplyAction) fileName -> {
int reload = reloads.incrementAndGet();
if (reload <= 2) Files.writeString(config, "Feature: manual-" + reload + "\n");
@@ -833,7 +831,7 @@ class BackendConfigurationServiceTest {
@Test void quickSetupsProduceReviewableBackendAndVoteSiteChanges() throws Exception {
Files.writeString(directory.resolve("BungeeSettings.yml"), "UseBungeecord: false\nServer: PleaseSet\n");
Files.writeString(directory.resolve("VoteSites.yml"), "VoteSites: {}\n");
BackendConfigurationService service = BackendConfigurationServiceAccess.create(directory, () -> { });
BackendConfigurationService service = new BackendConfigurationService(directory, () -> { });
BackendConfigurationService.QuickPreview proxy = service.previewQuickSetup("proxy-backend",
Map.of("server", "lobby", "method", "PLUGINMESSAGING"));
@@ -885,7 +883,7 @@ class BackendConfigurationServiceTest {
Files.writeString(directory.resolve("SpecialRewards.yml"), "VoteParty:\n Enabled: true\n"
+ " VotesRequired: 35\n GiveAllPlayers: true\n GiveOnlinePlayersOnly: false\n"
+ " Broadcast: Party!\n Rewards:\n Commands: [say one, say two]\n");
BackendConfigurationService service = BackendConfigurationServiceAccess.create(directory, () -> { });
BackendConfigurationService service = new BackendConfigurationService(directory, () -> { });
assertEquals("lobby", service.readQuickSetup("proxy-backend", Map.of()).options().get("server"));
assertEquals("REDIS", service.readQuickSetup("proxy-backend", Map.of()).options().get("method"));
@@ -903,7 +901,7 @@ class BackendConfigurationServiceTest {
Path rewards = directory.resolve("SpecialRewards.yml");
Files.writeString(rewards, "VoteParty:\n Enabled: false\n VotesRequired: 20\n"
+ " GiveAllPlayers: false\n GiveOnlinePlayersOnly: true\n Broadcast: Keep\n");
BackendConfigurationService service = BackendConfigurationServiceAccess.create(directory, () -> { });
BackendConfigurationService service = new BackendConfigurationService(directory, () -> { });
BackendConfigurationService.QuickState disabled = service.readQuickSetup("vote-party", Map.of());
assertEquals("false", disabled.options().get("enabled"));
@@ -911,21 +909,21 @@ class BackendConfigurationServiceTest {
"enabled", disabled.options().get("enabled"), "votesRequired", "25", "command", "",
"broadcast", "Keep", "giveAllPlayers", "false", "onlineOnly", "true"));
assertTrue(unrelated.proposal().content().contains("Enabled: false"));
BackendConfigurationServiceAccess.applyQuickSetup(service, "vote-party", Map.of("enabled", "false", "votesRequired", "25", "command", "",
service.applyQuickSetup("vote-party", Map.of("enabled", "false", "votesRequired", "25", "command", "",
"broadcast", "Keep", "giveAllPlayers", "false", "onlineOnly", "true"), unrelated.revision());
assertEquals("false", service.readQuickSetup("vote-party", Map.of()).options().get("enabled"));
BackendConfigurationService.QuickPreview enable = service.previewQuickSetup("vote-party", Map.of(
"enabled", "true", "votesRequired", "25", "command", "", "broadcast", "Keep",
"giveAllPlayers", "false", "onlineOnly", "true"));
BackendConfigurationServiceAccess.applyQuickSetup(service, "vote-party", Map.of("enabled", "true", "votesRequired", "25", "command", "",
service.applyQuickSetup("vote-party", Map.of("enabled", "true", "votesRequired", "25", "command", "",
"broadcast", "Keep", "giveAllPlayers", "false", "onlineOnly", "true"), enable.revision());
assertEquals("true", service.readQuickSetup("vote-party", Map.of()).options().get("enabled"));
}
@Test void legacyVotePartyQuickSetupPreservesEnabledWhenOmitted() throws Exception {
Files.writeString(directory.resolve("SpecialRewards.yml"), "VoteParty:\n Enabled: false\n");
BackendConfigurationService service = BackendConfigurationServiceAccess.create(directory, () -> { });
BackendConfigurationService service = new BackendConfigurationService(directory, () -> { });
BackendConfigurationService.QuickPreview preview = service.previewQuickSetup("vote-party", Map.of(
"votesRequired", "25", "command", "", "broadcast", "", "giveAllPlayers", "false",
@@ -937,7 +935,7 @@ class BackendConfigurationServiceTest {
@Test void oversizedInstalledGuidedValuesFailInsteadOfWedgingResultSubmission() throws Exception {
Files.writeString(directory.resolve("SpecialRewards.yml"),
"VoteParty:\n Broadcast: '" + "é".repeat(251) + "'\n");
BackendConfigurationService service = BackendConfigurationServiceAccess.create(directory, () -> { });
BackendConfigurationService service = new BackendConfigurationService(directory, () -> { });
assertThrows(IOException.class, () -> service.readQuickSetup("vote-party", Map.of()));
}
@@ -946,7 +944,7 @@ class BackendConfigurationServiceTest {
Path config = directory.resolve("Config.yml");
Files.writeString(config, "AutoCreateVoteSites: true\nProcessRewards: false\nOtherSetting: keep\n");
AtomicInteger reloads = new AtomicInteger();
BackendConfigurationService service = BackendConfigurationServiceAccess.create(directory, reloads::incrementAndGet);
BackendConfigurationService service = new BackendConfigurationService(directory, reloads::incrementAndGet);
BackendConfigurationService.QuickState state = service.readQuickSetup("auto-create-vote-sites", Map.of());
assertEquals("true", state.options().get("enabled"));
@@ -954,7 +952,7 @@ class BackendConfigurationServiceTest {
Map.of("enabled", "false"));
assertEquals(List.of("changed AutoCreateVoteSites"), preview.changes());
BackendConfigurationServiceAccess.applyQuickSetup(service, "auto-create-vote-sites", Map.of("enabled", "false"), state.revision());
service.applyQuickSetup("auto-create-vote-sites", Map.of("enabled", "false"), state.revision());
YamlConfiguration applied = YamlConfiguration.loadConfiguration(config.toFile());
assertFalse(applied.getBoolean("AutoCreateVoteSites"));
assertFalse(applied.getBoolean("ProcessRewards"));
@@ -968,7 +966,7 @@ class BackendConfigurationServiceTest {
Path config = directory.resolve("Config.yml");
Files.writeString(config, "VoteLogging:\n Enabled: false\n PurgeDays: 30\n UseMainMySQL: true\n"
+ " Host: private-db\n Password: keep-secret\nProcessRewards: false\n");
BackendConfigurationService service = BackendConfigurationServiceAccess.create(directory, () -> { });
BackendConfigurationService service = new BackendConfigurationService(directory, () -> { });
BackendConfigurationService.QuickState state = service.readQuickSetup("vote-logging", Map.of());
assertEquals(Map.of("enabled", "false", "purgeDays", "30", "useMainMySQL", "true"),
@@ -977,7 +975,7 @@ class BackendConfigurationServiceTest {
"enabled", "true", "purgeDays", "90", "useMainMySQL", "false"));
assertEquals(List.of("changed VoteLogging.Enabled", "changed VoteLogging.PurgeDays",
"changed VoteLogging.UseMainMySQL"), preview.changes());
BackendConfigurationServiceAccess.applyQuickSetup(service, "vote-logging", Map.of("enabled", "true", "purgeDays", "-1",
service.applyQuickSetup("vote-logging", Map.of("enabled", "true", "purgeDays", "-1",
"useMainMySQL", "false"), state.revision());
YamlConfiguration applied = YamlConfiguration.loadConfiguration(config.toFile());
@@ -1002,7 +1000,7 @@ class BackendConfigurationServiceTest {
+ " Commands: [existing]\n Messages:\n Player: Existing message\n");
Files.writeString(directory.resolve("SpecialRewards.yml"), "VoteParty:\n Enabled: true\n"
+ " Rewards:\n Commands: [existing party]\n");
BackendConfigurationService service = BackendConfigurationServiceAccess.create(directory, () -> { });
BackendConfigurationService service = new BackendConfigurationService(directory, () -> { });
BackendConfigurationService.QuickPreview reward = service.previewQuickSetup("easy-reward", Map.of(
"scope", "site", "name", "PMC", "command", "new reward", "message", "New message"));
@@ -1024,7 +1022,7 @@ class BackendConfigurationServiceTest {
+ " Commands: [old command]\n Other:\n Rewards:\n Commands: [keep other]\n"
+ "EverySiteReward:\n Commands: [keep every]\n");
AtomicInteger reloads = new AtomicInteger();
BackendConfigurationService service = BackendConfigurationServiceAccess.create(directory, reloads::incrementAndGet);
BackendConfigurationService service = new BackendConfigurationService(directory, reloads::incrementAndGet);
String encoded = """
{"scope":"site","site":"PMC","commands":["eco give %player% 100"],
"playerMessages":["Thanks"],"broadcastMessages":["%player% voted"],
@@ -1035,7 +1033,7 @@ class BackendConfigurationServiceTest {
BackendConfigurationService.QuickPreview preview = service.previewQuickSetup("reward-builder", options);
assertEquals("VoteSites.yml", preview.proposal().fileName());
assertEquals(preview.revision(), BackendConfigurationServiceAccess.currentQuickSetupRevision(service, "reward-builder",
assertEquals(preview.revision(), service.currentQuickSetupRevision("reward-builder",
Map.of("targetFile", "VoteSites.yml")));
YamlConfiguration proposed = new YamlConfiguration();
proposed.loadFromString(preview.proposal().content());
@@ -1056,11 +1054,11 @@ class BackendConfigurationServiceTest {
assertTrue(preview.proposal().content().contains("keep other"));
assertTrue(preview.proposal().content().contains("keep every"));
BackendConfigurationService.ApplyResult applied = BackendConfigurationServiceAccess.applyQuickSetup(service, "reward-builder", options,
BackendConfigurationService.ApplyResult applied = service.applyQuickSetup("reward-builder", options,
preview.revision());
assertEquals(1, reloads.get());
assertTrue(Files.readString(voteSites).contains("eco give %player% 100"));
assertEquals(applied.document().revision(), BackendConfigurationServiceAccess.currentQuickSetupRevision(service, "reward-builder",
assertEquals(applied.document().revision(), service.currentQuickSetupRevision("reward-builder",
Map.of("targetFile", "VoteSites.yml")));
}
@@ -1068,7 +1066,7 @@ class BackendConfigurationServiceTest {
Files.writeString(directory.resolve("VoteSites.yml"), "VoteSites: {}\nEverySiteReward:\n Commands: [old]\n");
Files.writeString(directory.resolve("SpecialRewards.yml"), "VoteParty:\n Enabled: false\n"
+ " VotesRequired: 40\n Rewards:\n Commands: [old party]\nOtherReward: keep\n");
BackendConfigurationService service = BackendConfigurationServiceAccess.create(directory, () -> { });
BackendConfigurationService service = new BackendConfigurationService(directory, () -> { });
BackendConfigurationService.QuickPreview every = service.previewQuickSetup("reward-builder", Map.of(
"proposal", "{\"scope\":\"every-site\",\"commands\":[\"say every\"]}"));
@@ -1089,7 +1087,7 @@ class BackendConfigurationServiceTest {
@Test void rewardBuilderRejectsUnknownOptionsMalformedPlansAndMissingSites() throws Exception {
Files.writeString(directory.resolve("VoteSites.yml"), "VoteSites: {}\n");
BackendConfigurationService service = BackendConfigurationServiceAccess.create(directory, () -> { });
BackendConfigurationService service = new BackendConfigurationService(directory, () -> { });
assertThrows(IllegalArgumentException.class, () -> service.readQuickSetup("reward-builder", Map.of()));
assertThrows(IllegalArgumentException.class, () -> service.previewQuickSetup("reward-builder",
@@ -1101,14 +1099,14 @@ class BackendConfigurationServiceTest {
String oversized = "{\"scope\":\"every-site\",\"commands\":[\"" + "x".repeat(64 * 1024) + "\"]}";
assertThrows(IllegalArgumentException.class, () -> service.previewQuickSetup("reward-builder",
Map.of("proposal", oversized)));
assertThrows(IllegalArgumentException.class, () -> BackendConfigurationServiceAccess.currentQuickSetupRevision(service, "reward-builder",
assertThrows(IllegalArgumentException.class, () -> service.currentQuickSetupRevision("reward-builder",
Map.of("targetFile", "Config.yml")));
}
@Test void proxyBackendQuickSetupRejectsUnknownTransportMethods() throws Exception {
Files.writeString(directory.resolve("BungeeSettings.yml"),
"UseBungeecord: false\nServer: PleaseSet\nBungeeMethod: PLUGINMESSAGING\n");
BackendConfigurationService service = BackendConfigurationServiceAccess.create(directory, () -> { });
BackendConfigurationService service = new BackendConfigurationService(directory, () -> { });
assertThrows(IllegalArgumentException.class, () -> service.previewQuickSetup("proxy-backend",
Map.of("server", "lobby", "method", "NOT_A_TRANSPORT")));
@@ -1123,7 +1121,7 @@ class BackendConfigurationServiceTest {
@Test void httpConnectionCodeIsRedactedFromManagedConfiguration() throws Exception {
Files.writeString(directory.resolve("BungeeSettings.yml"),
"HTTP:\n ConnectionCode: VPH1-sensitive-enrollment-code\n");
BackendConfigurationService service = BackendConfigurationServiceAccess.create(directory, () -> { });
BackendConfigurationService service = new BackendConfigurationService(directory, () -> { });
BackendConfigurationService.Document read = service.read("BungeeSettings.yml");
assertFalse(read.content().contains("VPH1-sensitive-enrollment-code"));
@@ -1142,7 +1140,7 @@ class BackendConfigurationServiceTest {
com.bencodez.simpleapi.servercomm.http.HttpClientCredentialStore.saveEnrolled(directory.resolve("http"), code,
identity.issueClientCertificate("lobby-1"));
BackendConfigurationService service = BackendConfigurationServiceAccess.create(directory, () -> { });
BackendConfigurationService service = new BackendConfigurationService(directory, () -> { });
assertDoesNotThrow(() -> service.previewQuickSetup("proxy-method", Map.of("method", "HTTP")));
}
@@ -1150,7 +1148,7 @@ class BackendConfigurationServiceTest {
Path settings = directory.resolve("BungeeSettings.yml");
Files.writeString(settings, "UseBungeecord: true\nServer: lobby-1\nBungeeMethod: PLUGINMESSAGING\n"
+ "PluginMessageChannel: vp:vp\nHTTP:\n ConnectionCode: malformed\n");
BackendConfigurationService service = BackendConfigurationServiceAccess.create(directory, () -> { });
BackendConfigurationService service = new BackendConfigurationService(directory, () -> { });
assertThrows(IllegalArgumentException.class,
() -> service.previewQuickSetup("proxy-method", Map.of("method", "HTTP")));
@@ -1180,7 +1178,7 @@ class BackendConfigurationServiceTest {
+ "MQTT:\n ClientID: lobby\n BrokerURL: bad\nBungeeServer:\n Host: ''\n Port: 1297\n");
Files.writeString(directory.resolve("Config.yml"),
"DataStorage: SQLITE\nDatabase:\n Host: ''\n Database: ''\n");
BackendConfigurationService service = BackendConfigurationServiceAccess.create(directory, () -> { });
BackendConfigurationService service = new BackendConfigurationService(directory, () -> { });
assertThrows(IllegalArgumentException.class,
() -> service.previewQuickSetup("proxy-method", Map.of("method", "REDIS")));
@@ -1201,7 +1199,7 @@ class BackendConfigurationServiceTest {
@Test void pluginMessagingMethodRequiresBackendIdentityForDiagnostics() throws Exception {
Files.writeString(directory.resolve("BungeeSettings.yml"),
"UseBungeecord: true\nServer: PleaseSet\nBungeeMethod: REDIS\n");
BackendConfigurationService service = BackendConfigurationServiceAccess.create(directory, () -> { });
BackendConfigurationService service = new BackendConfigurationService(directory, () -> { });
assertThrows(IllegalArgumentException.class, () -> service.previewQuickSetup("proxy-method",
Map.of("method", "PLUGINMESSAGING")));
@@ -1212,11 +1210,11 @@ class BackendConfigurationServiceTest {
Files.writeString(settings, "# Proxy settings\n#\n# Method selection\n"
+ "UseBungeecord: true\nServer: server\nBungeeMethod: PLUGINMESSAGING\n"
+ "PluginMessageChannel: vp:vp\nRedis:\n Host: localhost\n Port: 6379\n");
BackendConfigurationService service = BackendConfigurationServiceAccess.create(directory, () -> { });
BackendConfigurationService service = new BackendConfigurationService(directory, () -> { });
BackendConfigurationService.QuickPreview preview = service.previewQuickSetup("proxy-method",
Map.of("method", "REDIS"));
BackendConfigurationService.ApplyResult applied = BackendConfigurationServiceAccess.applyQuickSetup(service, "proxy-method",
BackendConfigurationService.ApplyResult applied = service.applyQuickSetup("proxy-method",
Map.of("method", "REDIS"), preview.revision(), ignored -> { });
assertFalse(applied.rolledBack());
@@ -1231,11 +1229,11 @@ class BackendConfigurationServiceTest {
+ "PluginMessageChannel: vp:vp\nRedis:\n Host: localhost\n Port: 6379\n");
AtomicInteger fullReloads = new AtomicInteger();
AtomicInteger transportSwitches = new AtomicInteger();
BackendConfigurationService service = BackendConfigurationServiceAccess.create(directory, fullReloads::incrementAndGet);
BackendConfigurationService service = new BackendConfigurationService(directory, fullReloads::incrementAndGet);
BackendConfigurationService.QuickPreview preview = service.previewQuickSetup("proxy-method",
Map.of("method", "REDIS"));
BackendConfigurationServiceAccess.applyQuickSetup(service, "proxy-method", Map.of("method", "REDIS"), preview.revision(),
service.applyQuickSetup("proxy-method", Map.of("method", "REDIS"), preview.revision(),
ignored -> transportSwitches.incrementAndGet());
assertEquals(0, fullReloads.get());
@@ -1249,13 +1247,13 @@ class BackendConfigurationServiceTest {
+ "PluginMessageChannel: vp:vp\nRedis:\n Host: localhost\n Port: 6379\n";
Files.writeString(settings, original);
AtomicInteger targeted = new AtomicInteger();
BackendConfigurationService service = BackendConfigurationServiceAccess.create(directory, () -> { });
BackendConfigurationService service = new BackendConfigurationService(directory, () -> { });
BackendConfigurationService.QuickPreview preview = service.previewQuickSetup("proxy-method",
Map.of("method", "REDIS"));
BackendConfigurationService.ApplyFailureException failure = assertThrows(
BackendConfigurationService.ApplyFailureException.class,
() -> BackendConfigurationServiceAccess.applyQuickSetup(service, "proxy-method", Map.of("method", "REDIS"), preview.revision(), ignored -> {
() -> service.applyQuickSetup("proxy-method", Map.of("method", "REDIS"), preview.revision(), ignored -> {
if (targeted.incrementAndGet() == 1) throw new IOException("transport activation failed");
}));
@@ -1298,12 +1296,12 @@ class BackendConfigurationServiceTest {
+ " Commands: ['source new reward']\n"
+ "EverySiteReward:\n"
+ " Commands: ['source every-site reward']\n";
BackendConfigurationService service = BackendConfigurationServiceAccess.create(directory, () -> { });
BackendConfigurationService service = new BackendConfigurationService(directory, () -> { });
BackendConfigurationService.Document before = service.read("VoteSites.yml");
BackendConfigurationService.QuickPreview preview = service.previewQuickSetup("sync-vote-sites",
Map.of("sourceContent", source));
String recoveryRevision = BackendConfigurationServiceAccess.proposedQuickSetupRevision(service, "sync-vote-sites", preview);
String recoveryRevision = service.proposedQuickSetupRevision("sync-vote-sites", preview);
YamlConfiguration proposal = new YamlConfiguration();
proposal.options().parseComments(true);
proposal.loadFromString(preview.proposal().content());
@@ -1320,7 +1318,7 @@ class BackendConfigurationServiceTest {
assertTrue(preview.proposal().content().contains("# synchronized field"));
assertTrue(preview.changes().stream().noneMatch(change -> change.toLowerCase().contains("reward")));
BackendConfigurationService.ApplyResult result = BackendConfigurationServiceAccess.applyQuickSetup(service, "sync-vote-sites",
BackendConfigurationService.ApplyResult result = service.applyQuickSetup("sync-vote-sites",
Map.of("sourceContent", source), preview.revision());
assertEquals(recoveryRevision, result.document().revision());
String applied = Files.readString(voteSites);
@@ -1334,7 +1332,7 @@ class BackendConfigurationServiceTest {
@Test void voteSitesSyncMatchesRootSitesAndFieldsCaseInsensitively() throws Exception {
Files.writeString(directory.resolve("Config.yml"), "CaseInsensitiveYMLFiles: true\n");
Files.writeString(directory.resolve("VoteSites.yml"), "votesites:\n pmc:\n name: Target\n Rewards:\n Commands: ['keep']\n");
BackendConfigurationService service = BackendConfigurationServiceAccess.create(directory, () -> { });
BackendConfigurationService service = new BackendConfigurationService(directory, () -> { });
BackendConfigurationService.QuickPreview preview = service.previewQuickSetup("sync-vote-sites", Map.of(
"sourceContent", "VOTESITES:\n PMC:\n Name: Source\n VoteURL: https://example.invalid/vote\n"));
@@ -1352,22 +1350,22 @@ class BackendConfigurationServiceTest {
Path config = directory.resolve("Config.yml");
Files.writeString(config, "CaseInsensitiveYMLFiles: true\nMessage: before\n");
Files.writeString(directory.resolve("VoteSites.yml"), "VoteSites:\n PMC:\n Name: Target\n");
BackendConfigurationService service = BackendConfigurationServiceAccess.create(directory, () -> { });
BackendConfigurationService service = new BackendConfigurationService(directory, () -> { });
Map<String, String> source = Map.of("sourceContent", "VoteSites:\n PMC:\n Name: Source\n");
BackendConfigurationService.QuickPreview preview = service.previewQuickSetup("sync-vote-sites", source);
Files.writeString(config, "CaseInsensitiveYMLFiles: true\nMessage: independently edited\n");
assertDoesNotThrow(() -> BackendConfigurationServiceAccess.applyQuickSetup(service, "sync-vote-sites", source, preview.revision()));
assertDoesNotThrow(() -> service.applyQuickSetup("sync-vote-sites", source, preview.revision()));
BackendConfigurationService.QuickPreview policyPreview = service.previewQuickSetup("sync-vote-sites", source);
Files.writeString(config, "CaseInsensitiveYMLFiles: false\nMessage: independently edited\n");
assertThrows(BackendConfigurationService.StaleRevisionException.class,
() -> BackendConfigurationServiceAccess.applyQuickSetup(service, "sync-vote-sites", source, policyPreview.revision()));
() -> service.applyQuickSetup("sync-vote-sites", source, policyPreview.revision()));
}
@Test void voteSitesSyncDropsUnrestorableSourceCredentialComments() throws Exception {
Files.writeString(directory.resolve("VoteSites.yml"), "VoteSites:\n PMC:\n Name: Target\n");
BackendConfigurationService service = BackendConfigurationServiceAccess.create(directory, () -> { });
BackendConfigurationService service = new BackendConfigurationService(directory, () -> { });
String source = "VoteSites:\n # Password: " + BackendConfigurationService.REDACTED + "\n"
+ " # public source note\n PMC:\n Name: Source # Token: "
+ BackendConfigurationService.REDACTED + "\n";
@@ -1377,7 +1375,7 @@ class BackendConfigurationServiceTest {
assertFalse(preview.proposal().content().contains(BackendConfigurationService.REDACTED));
assertTrue(preview.proposal().content().contains("public source note"));
BackendConfigurationService.ApplyResult applied = BackendConfigurationServiceAccess.applyQuickSetup(service, "sync-vote-sites",
BackendConfigurationService.ApplyResult applied = service.applyQuickSetup("sync-vote-sites",
Map.of("sourceContent", source), preview.revision());
YamlConfiguration installed = new YamlConfiguration();
installed.loadFromString(applied.document().content());
@@ -1388,7 +1386,7 @@ class BackendConfigurationServiceTest {
Path voteSites = directory.resolve("VoteSites.yml");
Files.writeString(voteSites, "VoteSites:\n PMC:\n"
+ " Name: Target # Password: target-comment-secret\n");
BackendConfigurationService service = BackendConfigurationServiceAccess.create(directory, () -> { });
BackendConfigurationService service = new BackendConfigurationService(directory, () -> { });
String source = "VoteSites:\n PMC:\n Name: Source # public source comment\n";
BackendConfigurationService.QuickPreview preview = service.previewQuickSetup("sync-vote-sites",
@@ -1399,7 +1397,7 @@ class BackendConfigurationServiceTest {
assertThrows(IllegalArgumentException.class, () -> service.apply("VoteSites.yml",
preview.proposal().content(), editorSnapshot.revision()));
BackendConfigurationServiceAccess.applyQuickSetup(service, "sync-vote-sites", Map.of("sourceContent", source), preview.revision());
service.applyQuickSetup("sync-vote-sites", Map.of("sourceContent", source), preview.revision());
String applied = Files.readString(voteSites);
assertTrue(applied.contains("Name: Source"));
assertTrue(applied.contains("target-comment-secret"));
@@ -1409,7 +1407,7 @@ class BackendConfigurationServiceTest {
Files.writeString(directory.resolve("Config.yml"), "caseinsensitiveymlfiles: false\n");
Files.writeString(directory.resolve("VoteSites.yml"), "VoteSites:\n PMC:\n Name: Upper target\n"
+ " pmc:\n Name: Lower target\n");
BackendConfigurationService service = BackendConfigurationServiceAccess.create(directory, () -> { });
BackendConfigurationService service = new BackendConfigurationService(directory, () -> { });
BackendConfigurationService.QuickPreview preview = service.previewQuickSetup("sync-vote-sites", Map.of(
"sourceContent", "votesites:\n PMC:\n name: Updated upper\n"));
@@ -1424,7 +1422,7 @@ class BackendConfigurationServiceTest {
Files.writeString(directory.resolve("Config.yml"), "Message: no casing policy configured\n");
Files.writeString(directory.resolve("VoteSites.yml"), "VoteSites:\n PMC:\n Name: Upper target\n"
+ " pmc:\n Name: Lower target\n");
BackendConfigurationService service = BackendConfigurationServiceAccess.create(directory, () -> { });
BackendConfigurationService service = new BackendConfigurationService(directory, () -> { });
BackendConfigurationService.QuickPreview preview = service.previewQuickSetup("sync-vote-sites", Map.of(
"sourceContent", "VoteSites:\n PMC:\n Name: Updated upper\n"));
@@ -1437,7 +1435,7 @@ class BackendConfigurationServiceTest {
@Test void voteSitesSyncRejectsMalformedOrMissingSourceSections() throws Exception {
Files.writeString(directory.resolve("VoteSites.yml"), "VoteSites: {}\n");
BackendConfigurationService service = BackendConfigurationServiceAccess.create(directory, () -> { });
BackendConfigurationService service = new BackendConfigurationService(directory, () -> { });
assertThrows(IllegalArgumentException.class, () -> service.previewQuickSetup("sync-vote-sites",
Map.of("sourceContent", "not: [yaml")));
@@ -1449,7 +1447,7 @@ class BackendConfigurationServiceTest {
@Test void voteSitesSyncSkipsRewardOnlySites() throws Exception {
Files.writeString(directory.resolve("VoteSites.yml"), "VoteSites:\n Existing:\n Name: Existing\n");
BackendConfigurationService service = BackendConfigurationServiceAccess.create(directory, () -> { });
BackendConfigurationService service = new BackendConfigurationService(directory, () -> { });
BackendConfigurationService.QuickPreview preview = service.previewQuickSetup("sync-vote-sites", Map.of(
"sourceContent", "VoteSites:\n RewardOnly:\n Rewards:\n Commands: ['say ignored']\n"));
@@ -1462,7 +1460,7 @@ class BackendConfigurationServiceTest {
@Test void voteSitesSyncPreservesTargetsBelowRewardOnlyWrappers() throws Exception {
Files.writeString(directory.resolve("VoteSites.yml"),
"VoteSites:\n Example:\n Name: Target\n Metadata: keep\n");
BackendConfigurationService service = BackendConfigurationServiceAccess.create(directory, () -> { });
BackendConfigurationService service = new BackendConfigurationService(directory, () -> { });
BackendConfigurationService.QuickPreview preview = service.previewQuickSetup("sync-vote-sites", Map.of(
"sourceContent", "VoteSites:\n Example:\n Name: Source\n Metadata:\n"
@@ -1477,7 +1475,7 @@ class BackendConfigurationServiceTest {
@Test void voteSitesSyncDoesNotReplaceTargetSectionsContainingRewardDescendants() throws Exception {
Files.writeString(directory.resolve("VoteSites.yml"), "VoteSites:\n Example:\n Name: Target\n"
+ " Metadata:\n Owner: keep\n Rewards:\n Commands: ['target reward']\n");
BackendConfigurationService service = BackendConfigurationServiceAccess.create(directory, () -> { });
BackendConfigurationService service = new BackendConfigurationService(directory, () -> { });
BackendConfigurationService.QuickPreview preview = service.previewQuickSetup("sync-vote-sites", Map.of(
"sourceContent", "VoteSites:\n Example:\n Name: Source\n Metadata: source scalar\n"));
@@ -1493,7 +1491,7 @@ class BackendConfigurationServiceTest {
@Test void fullBungeeSettingsRejectsUnknownTransportMethods() throws Exception {
Files.writeString(directory.resolve("BungeeSettings.yml"),
"UseBungeecord: true\nServer: lobby\nBungeeMethod: PLUGINMESSAGING\n");
BackendConfigurationService service = BackendConfigurationServiceAccess.create(directory, () -> { });
BackendConfigurationService service = new BackendConfigurationService(directory, () -> { });
assertThrows(IllegalArgumentException.class, () -> service.preview("BungeeSettings.yml",
"UseBungeecord: true\nServer: lobby\nBungeeMethod: NOT_A_TRANSPORT\n"));
@@ -1,7 +1,4 @@
package com.bencodez.votingplugin.tests.control;
import com.bencodez.votingplugin.control.BackendControlAutoEnrollment;
import com.bencodez.votingplugin.control.ControlEnrollmentAuthenticator;
package com.bencodez.votingplugin.control;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
@@ -123,7 +120,7 @@ class BackendControlAutoEnrollmentTest {
"backend-a", requestId, false, challenge, resultProof));
verify(plugin).startBackendControlConnectorForEnrollment(enrollment);
org.mockito.Mockito.clearInvocations(messages);
BackendControlAutoEnrollmentAccess.send(enrollment);
enrollment.send();
ArgumentCaptor<JsonEnvelope> provedRequest = ArgumentCaptor.forClass(JsonEnvelope.class);
verify(messages).sendMessage(provedRequest.capture());
@@ -145,7 +142,7 @@ class BackendControlAutoEnrollmentTest {
"backend-a", requestId, false, challenge, resultProof));
verify(plugin, times(2)).startBackendControlConnectorForEnrollment(enrollment);
org.mockito.Mockito.clearInvocations(messages);
BackendControlAutoEnrollmentAccess.send(enrollment);
enrollment.send();
ArgumentCaptor<JsonEnvelope> retriedRequest = ArgumentCaptor.forClass(JsonEnvelope.class);
verify(messages).sendMessage(retriedRequest.capture());
VotingPluginWire.ControlEnrollmentRequest retried =
@@ -1,10 +1,4 @@
package com.bencodez.votingplugin.tests.control;
import com.bencodez.votingplugin.control.BackendConfigurationService;
import com.bencodez.votingplugin.control.BackendControlConnector;
import com.bencodez.votingplugin.tests.control.BackendControlResultStoreAccess;
import com.bencodez.votingplugin.control.ControlInspectionService;
import com.bencodez.votingplugin.control.PluginDeploymentService;
package com.bencodez.votingplugin.control;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -29,7 +23,7 @@ import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import com.bencodez.votingplugin.tests.control.BackendControlResultStoreAccess.StoredResult;
import com.bencodez.votingplugin.control.BackendControlResultStore.StoredResult;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
@@ -65,7 +59,7 @@ class BackendControlConnectorProtocolTest {
field.setAccessible(true);
assertNull(field.get(connector));
JsonObject body = new JsonObject();
BackendControlConnectorAccess.addCapabilities(body, false, field.get(connector) != null);
BackendControlConnector.addCapabilities(body, false, field.get(connector) != null);
assertFalse(body.getAsJsonArray("capabilities").asList().stream()
.anyMatch(value -> PluginDeploymentService.CAPABILITY.equals(value.getAsString())));
org.mockito.Mockito.verify(plugin, org.mockito.Mockito.never()).getServer();
@@ -74,21 +68,21 @@ class BackendControlConnectorProtocolTest {
}
@Test void onlyTheLeaseExpiryConflictRequestsAResultReclaim() {
assertTrue(BackendControlConnectorAccess.taskLeaseExpired(new BackendControlConnectorAccess.Response(409,
assertTrue(BackendControlConnector.taskLeaseExpired(new BackendControlConnector.Response(409,
"{\"error\":{\"code\":\"TASK_LEASE_EXPIRED\"}}")));
assertFalse(BackendControlConnectorAccess.taskLeaseExpired(new BackendControlConnectorAccess.Response(409,
assertFalse(BackendControlConnector.taskLeaseExpired(new BackendControlConnector.Response(409,
"{\"error\":{\"code\":\"SESSION_MISMATCH\"}}")));
assertFalse(BackendControlConnectorAccess.taskLeaseExpired(new BackendControlConnectorAccess.Response(500, "not-json")));
assertTrue(BackendControlConnectorAccess.operationNotFound(new BackendControlConnectorAccess.Response(404,
assertFalse(BackendControlConnector.taskLeaseExpired(new BackendControlConnector.Response(500, "not-json")));
assertTrue(BackendControlConnector.operationNotFound(new BackendControlConnector.Response(404,
"{\"error\":{\"code\":\"OPERATION_NOT_FOUND\"}}")));
assertFalse(BackendControlConnectorAccess.operationNotFound(new BackendControlConnectorAccess.Response(404,
assertFalse(BackendControlConnector.operationNotFound(new BackendControlConnector.Response(404,
"{\"error\":{\"code\":\"NODE_NOT_FOUND\"}}")));
}
@Test void deploymentTaskRejectsUnknownV1Fields() {
JsonObject task = deploymentTask();
task.addProperty("unexpected", "value");
assertThrows(IllegalArgumentException.class, () -> BackendControlConnectorAccess.deploymentTask(task));
assertThrows(IllegalArgumentException.class, () -> BackendControlConnector.deploymentTask(task));
}
private static JsonObject deploymentTask() {
@@ -105,7 +99,7 @@ class BackendControlConnectorProtocolTest {
JsonObject anticipated = new JsonObject();
anticipated.addProperty("attemptId", "00000000-0000-0000-0000-000000000199");
StoredResult recovered = BackendControlConnectorAccess.abortedIntent(
StoredResult recovered = BackendControlConnector.abortedIntent(
new StoredResult(anticipated, true, false, false));
assertTrue(recovered.committed());
@@ -116,7 +110,7 @@ class BackendControlConnectorProtocolTest {
@Test void installedFileIntentRecoveryRebuildsMaskedContent() throws Exception {
Files.writeString(directory.resolve("Config.yml"), "Database:\n Password: keep-me\nDebug: true\n");
BackendConfigurationService configurations = BackendConfigurationServiceAccess.create(directory, () -> { });
BackendConfigurationService configurations = new BackendConfigurationService(directory, () -> { });
BackendConfigurationService.Document installed = configurations.read("Config.yml");
JsonObject configuration = new JsonObject();
configuration.addProperty("domain", "file");
@@ -124,7 +118,7 @@ class BackendControlConnectorProtocolTest {
JsonObject intent = new JsonObject();
intent.addProperty("revision", installed.revision());
intent.add("configuration", configuration);
StoredResult recovered = BackendControlConnectorAccess.committedInstalledForAttempt(configurations,
StoredResult recovered = BackendControlConnector.committedInstalledForAttempt(configurations,
new StoredResult(intent, false, false, false), "00000000-0000-0000-0000-000000000198");
assertTrue(recovered.committed());
@@ -135,7 +129,7 @@ class BackendControlConnectorProtocolTest {
}
@Test void changedMalformedFilesAbortPendingRecoveryBeforeYamlParsing() throws Exception {
BackendConfigurationService configurations = BackendConfigurationServiceAccess.create(directory, () -> { });
BackendConfigurationService configurations = new BackendConfigurationService(directory, () -> { });
for (String fileName : List.of("Config.yml", "Rewards/Daily.yml")) {
Path file = directory.resolve(fileName);
Files.createDirectories(file.getParent());
@@ -151,10 +145,10 @@ class BackendControlConnectorProtocolTest {
StoredResult pending = new StoredResult(intent, false, false, false);
Files.writeString(file, "Money: [\n");
assertThrows(IOException.class, () -> configurations.read(fileName));
assertNull(BackendControlConnectorAccess.committedInstalledForAttempt(configurations, pending, "attempt"));
assertTrue(BackendControlConnectorAccess.abortedIntent(pending).committed());
assertNull(BackendControlConnector.committedInstalledForAttempt(configurations, pending, "attempt"));
assertTrue(BackendControlConnector.abortedIntent(pending).committed());
Files.writeString(file, "Money: 1\n");
assertEquals(revision, BackendControlConnectorAccess.committedInstalledForAttempt(configurations,
assertEquals(revision, BackendControlConnector.committedInstalledForAttempt(configurations,
pending, "attempt").result().get("revision").getAsString());
}
}
@@ -163,7 +157,7 @@ class BackendControlConnectorProtocolTest {
Path rewards = Files.createDirectory(directory.resolve("Rewards"));
Path daily = rewards.resolve("Daily.yml");
Files.writeString(daily, "Money: 1\n");
BackendConfigurationService configurations = BackendConfigurationServiceAccess.create(directory, () -> { });
BackendConfigurationService configurations = new BackendConfigurationService(directory, () -> { });
String revision = configurations.read("Rewards/Daily.yml").revision();
JsonObject configuration = new JsonObject();
configuration.addProperty("domain", "file");
@@ -174,25 +168,25 @@ class BackendControlConnectorProtocolTest {
intent.add("configuration", configuration);
StoredResult pending = new StoredResult(intent, false, false, false);
Files.delete(daily);
assertNull(BackendControlConnectorAccess.committedInstalledForAttempt(configurations, pending, "attempt"));
assertTrue(BackendControlConnectorAccess.abortedIntent(pending).committed());
assertNull(BackendControlConnector.committedInstalledForAttempt(configurations, pending, "attempt"));
assertTrue(BackendControlConnector.abortedIntent(pending).committed());
Files.delete(rewards);
assertNull(BackendControlConnectorAccess.committedInstalledForAttempt(configurations, pending, "attempt"));
assertNull(BackendControlConnector.committedInstalledForAttempt(configurations, pending, "attempt"));
Files.createDirectory(rewards);
Files.createSymbolicLink(daily, directory.resolve("not-a-reward.yml"));
assertNull(BackendControlConnectorAccess.committedInstalledForAttempt(configurations, pending, "attempt"));
assertNull(BackendControlConnector.committedInstalledForAttempt(configurations, pending, "attempt"));
Files.delete(daily);
Files.createDirectory(daily);
assertNull(BackendControlConnectorAccess.committedInstalledForAttempt(configurations, pending, "attempt"));
assertNull(BackendControlConnector.committedInstalledForAttempt(configurations, pending, "attempt"));
Files.delete(daily);
Files.writeString(daily, "x".repeat(BackendConfigurationService.MAX_CONTENT_BYTES + 1));
assertNull(BackendControlConnectorAccess.committedInstalledForAttempt(configurations, pending, "attempt"));
assertNull(BackendControlConnector.committedInstalledForAttempt(configurations, pending, "attempt"));
Files.write(daily, new byte[] {(byte) 0xC3, (byte) 0x28});
assertNull(BackendControlConnectorAccess.committedInstalledForAttempt(configurations, pending, "attempt"));
assertNull(BackendControlConnector.committedInstalledForAttempt(configurations, pending, "attempt"));
Files.writeString(daily, "Money: 1\n");
assertEquals(revision, BackendControlConnectorAccess.committedInstalledForAttempt(configurations,
assertEquals(revision, BackendControlConnector.committedInstalledForAttempt(configurations,
pending, "attempt").result().get("revision").getAsString());
assertFalse(BackendConfigurationServiceAccess.namedRewardCannotBeConfirmed(new IOException("transient read failure")));
assertFalse(BackendConfigurationService.namedRewardCannotBeConfirmed(new IOException("transient read failure")));
}
@Test void fifoNamedRewardIntentTerminatesWithoutOpeningItsBody() throws Exception {
@@ -201,7 +195,7 @@ class BackendControlConnectorProtocolTest {
Path rewards = Files.createDirectory(directory.resolve("Rewards"));
Path daily = rewards.resolve("Daily.yml");
Files.writeString(daily, "Money: 1\n");
BackendConfigurationService configurations = BackendConfigurationServiceAccess.create(directory, () -> { });
BackendConfigurationService configurations = new BackendConfigurationService(directory, () -> { });
String revision = configurations.read("Rewards/Daily.yml").revision();
JsonObject configuration = new JsonObject();
configuration.addProperty("domain", "file");
@@ -213,14 +207,14 @@ class BackendControlConnectorProtocolTest {
Process create = new ProcessBuilder("/usr/bin/mkfifo", daily.toString()).start();
assertTrue(create.waitFor(5, TimeUnit.SECONDS));
assertEquals(0, create.exitValue());
assertNull(BackendControlConnectorAccess.committedInstalledForAttempt(configurations,
assertNull(BackendControlConnector.committedInstalledForAttempt(configurations,
new StoredResult(intent, false, false, false), "attempt"));
}
@Test void namedRewardRecoveryIgnoresUnrelatedInvalidInventoryEntries() throws Exception {
Path rewards = Files.createDirectory(directory.resolve("Rewards"));
Files.writeString(rewards.resolve("Daily.yml"), "Money: 1\n");
BackendConfigurationService configurations = BackendConfigurationServiceAccess.create(directory, () -> { });
BackendConfigurationService configurations = new BackendConfigurationService(directory, () -> { });
String revision = configurations.read("Rewards/Daily.yml").revision();
JsonObject configuration = new JsonObject();
configuration.addProperty("domain", "file");
@@ -234,21 +228,21 @@ class BackendControlConnectorProtocolTest {
Path unsafe = rewards.resolve("Unrelated.yml");
Files.createSymbolicLink(unsafe, directory.resolve("outside.yml"));
assertThrows(IOException.class, () -> configurations.read("Rewards/Daily.yml"));
assertEquals(revision, BackendControlConnectorAccess.committedInstalledForAttempt(configurations,
assertEquals(revision, BackendControlConnector.committedInstalledForAttempt(configurations,
pending, "attempt").result().get("revision").getAsString());
Files.delete(unsafe);
Path ambiguous = rewards.resolve("daily.yml");
Files.writeString(ambiguous, "Money: 2\n");
assertThrows(IOException.class, () -> configurations.read("Rewards/Daily.yml"));
assertNull(BackendControlConnectorAccess.committedInstalledForAttempt(configurations, pending, "attempt"));
assertTrue(BackendControlConnectorAccess.abortedIntent(pending).committed());
assertNull(BackendControlConnector.committedInstalledForAttempt(configurations, pending, "attempt"));
assertTrue(BackendControlConnector.abortedIntent(pending).committed());
Files.delete(ambiguous);
Path oversized = rewards.resolve("Oversized.yml");
Files.writeString(oversized, "x".repeat(BackendConfigurationService.MAX_CONTENT_BYTES + 1));
assertThrows(IOException.class, () -> configurations.read("Rewards/Daily.yml"));
assertEquals(revision, BackendControlConnectorAccess.committedInstalledForAttempt(configurations,
assertEquals(revision, BackendControlConnector.committedInstalledForAttempt(configurations,
pending, "attempt").result().get("revision").getAsString());
Files.delete(oversized);
@@ -256,18 +250,18 @@ class BackendControlConnectorProtocolTest {
Files.writeString(rewards.resolve("Extra" + index + ".yml"), "Money: 0\n");
}
assertThrows(IOException.class, () -> configurations.read("Rewards/Daily.yml"));
assertEquals(revision, BackendControlConnectorAccess.committedInstalledForAttempt(configurations,
assertEquals(revision, BackendControlConnector.committedInstalledForAttempt(configurations,
pending, "attempt").result().get("revision").getAsString());
}
@Test void registrationRequiresFileControlButAllowsQuickSetupToRemainOptional() {
assertThrows(RuntimeException.class, () -> BackendControlConnectorAccess.requireFileCapability(false));
assertDoesNotThrow(() -> BackendControlConnectorAccess.requireFileCapability(true));
assertThrows(RuntimeException.class, () -> BackendControlConnector.requireFileCapability(false));
assertDoesNotThrow(() -> BackendControlConnector.requireFileCapability(true));
}
@Test void registrationAdvertisesCommentPreservingFilesAsAnOptionalCapability() {
JsonObject registration = new JsonObject();
BackendControlConnectorAccess.addCapabilities(registration, true, false);
BackendControlConnector.addCapabilities(registration, true, false);
JsonArray advertised = registration.getAsJsonArray("capabilities");
assertTrue(advertised.asList().stream()
@@ -293,12 +287,12 @@ class BackendControlConnectorProtocolTest {
@Test void deploymentCapabilityIsOnlyAddedWhenStagingWasPrepared() {
JsonObject unavailable = new JsonObject();
BackendControlConnectorAccess.addCapabilities(unavailable, true, false);
BackendControlConnector.addCapabilities(unavailable, true, false);
assertFalse(unavailable.getAsJsonArray("capabilities").asList().stream()
.anyMatch(value -> PluginDeploymentService.CAPABILITY.equals(value.getAsString())));
JsonObject ready = new JsonObject();
BackendControlConnectorAccess.addCapabilities(ready, true, true);
BackendControlConnector.addCapabilities(ready, true, true);
assertTrue(ready.getAsJsonArray("capabilities").asList().stream()
.anyMatch(value -> PluginDeploymentService.CAPABILITY.equals(value.getAsString())));
assertTrue(ready.getAsJsonArray("capabilities").asList().stream()
@@ -307,7 +301,7 @@ class BackendControlConnectorProtocolTest {
@Test void unsupportedFilesystemDoesNotAdvertiseNamedRewards() {
JsonObject registration = new JsonObject();
BackendControlConnectorAccess.addCapabilities(registration, false, true);
BackendControlConnector.addCapabilities(registration, false, true);
assertFalse(registration.getAsJsonArray("capabilities").asList().stream()
.anyMatch(value -> "config.reward-files.v1".equals(value.getAsString())));
assertTrue(registration.getAsJsonArray("capabilities").asList().stream()
@@ -318,36 +312,36 @@ class BackendControlConnectorProtocolTest {
@Test void heartbeatRetainsOmittedCapabilitiesAndHonorsExplicitReplacement() {
JsonObject omitted = new JsonObject();
assertTrue(BackendControlConnectorAccess.negotiatedCapability(omitted, "config.files.v1", true));
assertTrue(BackendControlConnector.negotiatedCapability(omitted, "config.files.v1", true));
JsonObject explicit = new JsonObject();
JsonArray accepted = new JsonArray();
accepted.add("config.quick-setup.v1");
explicit.add("acceptedCapabilities", accepted);
assertFalse(BackendControlConnectorAccess.negotiatedCapability(explicit, "config.files.v1", true));
assertTrue(BackendControlConnectorAccess.negotiatedCapability(explicit, "config.quick-setup.v1", false));
assertFalse(BackendControlConnector.negotiatedCapability(explicit, "config.files.v1", true));
assertTrue(BackendControlConnector.negotiatedCapability(explicit, "config.quick-setup.v1", false));
}
@Test void repeatedInspectionFailuresUseBoundedExponentialBackoff() {
assertEquals(0, BackendControlConnectorAccess.inspectionRetryDelayMillis(0));
assertEquals(1000, BackendControlConnectorAccess.inspectionRetryDelayMillis(1));
assertEquals(2000, BackendControlConnectorAccess.inspectionRetryDelayMillis(2));
assertEquals(256000, BackendControlConnectorAccess.inspectionRetryDelayMillis(9));
assertEquals(300000, BackendControlConnectorAccess.inspectionRetryDelayMillis(10));
assertEquals(300000, BackendControlConnectorAccess.inspectionRetryDelayMillis(30));
assertEquals(0, BackendControlConnector.inspectionRetryDelayMillis(0));
assertEquals(1000, BackendControlConnector.inspectionRetryDelayMillis(1));
assertEquals(2000, BackendControlConnector.inspectionRetryDelayMillis(2));
assertEquals(256000, BackendControlConnector.inspectionRetryDelayMillis(9));
assertEquals(300000, BackendControlConnector.inspectionRetryDelayMillis(10));
assertEquals(300000, BackendControlConnector.inspectionRetryDelayMillis(30));
}
@Test void voteSitesSyncRequiresBothNegotiatedCapabilities() {
assertFalse(BackendControlConnectorAccess.quickSetupCapabilityAccepted("sync-vote-sites", true, false, false));
assertFalse(BackendControlConnectorAccess.quickSetupCapabilityAccepted("sync-vote-sites", false, false, true));
assertTrue(BackendControlConnectorAccess.quickSetupCapabilityAccepted("sync-vote-sites", true, false, true));
assertTrue(BackendControlConnectorAccess.quickSetupCapabilityAccepted("common-settings", true, false, false));
assertFalse(BackendControlConnector.quickSetupCapabilityAccepted("sync-vote-sites", true, false, false));
assertFalse(BackendControlConnector.quickSetupCapabilityAccepted("sync-vote-sites", false, false, true));
assertTrue(BackendControlConnector.quickSetupCapabilityAccepted("sync-vote-sites", true, false, true));
assertTrue(BackendControlConnector.quickSetupCapabilityAccepted("common-settings", true, false, false));
}
@Test void httpProxyMethodApplyRequiresNegotiatedV2Capability() {
assertFalse(BackendControlConnectorAccess.proxyMethodApplyCapabilityAccepted("HTTP", false));
assertTrue(BackendControlConnectorAccess.proxyMethodApplyCapabilityAccepted("HTTP", true));
assertTrue(BackendControlConnectorAccess.proxyMethodApplyCapabilityAccepted("PLUGINMESSAGING", false));
assertFalse(BackendControlConnector.proxyMethodApplyCapabilityAccepted("HTTP", false));
assertTrue(BackendControlConnector.proxyMethodApplyCapabilityAccepted("HTTP", true));
assertTrue(BackendControlConnector.proxyMethodApplyCapabilityAccepted("PLUGINMESSAGING", false));
}
@Test void httpQuickRequestsRejectMissingV2BeforeTouchingConfiguration() throws Exception {
@@ -374,30 +368,30 @@ class BackendControlConnectorProtocolTest {
}
@Test void votePartyRequiresItsVersionedCapability() {
assertFalse(BackendControlConnectorAccess.quickSetupCapabilityAccepted("vote-party", true, false, false));
assertFalse(BackendControlConnectorAccess.quickSetupCapabilityAccepted("vote-party", false, true, false));
assertTrue(BackendControlConnectorAccess.quickSetupCapabilityAccepted("vote-party", true, true, false));
assertFalse(BackendControlConnector.quickSetupCapabilityAccepted("vote-party", true, false, false));
assertFalse(BackendControlConnector.quickSetupCapabilityAccepted("vote-party", false, true, false));
assertTrue(BackendControlConnector.quickSetupCapabilityAccepted("vote-party", true, true, false));
}
@Test void legacyVotePartyOptionsUseV1ButEnabledRequiresV2() {
assertTrue(BackendControlConnectorAccess.quickSetupCapabilityAccepted("vote-party", true, false, false,
assertTrue(BackendControlConnector.quickSetupCapabilityAccepted("vote-party", true, false, false,
Map.of("threshold", "10")));
assertFalse(BackendControlConnectorAccess.quickSetupCapabilityAccepted("vote-party", true, false, false,
assertFalse(BackendControlConnector.quickSetupCapabilityAccepted("vote-party", true, false, false,
Map.of("enabled", "true")));
assertFalse(BackendControlConnectorAccess.quickSetupCapabilityAccepted("vote-party", false, true, false,
assertFalse(BackendControlConnector.quickSetupCapabilityAccepted("vote-party", false, true, false,
Map.of("enabled", "true")));
assertTrue(BackendControlConnectorAccess.quickSetupCapabilityAccepted("vote-party", true, true, false,
assertTrue(BackendControlConnector.quickSetupCapabilityAccepted("vote-party", true, true, false,
Map.of("enabled", "true")));
Map<String, String> state = Map.of("enabled", "false", "votesRequired", "20");
assertEquals(Map.of("votesRequired", "20"),
BackendControlConnectorAccess.resultQuickReadOptions("vote-party", state, Map.of()));
assertEquals(state, BackendControlConnectorAccess.resultQuickReadOptions("vote-party", state,
BackendControlConnector.resultQuickReadOptions("vote-party", state, Map.of()));
assertEquals(state, BackendControlConnector.resultQuickReadOptions("vote-party", state,
Map.of("enabled", "false")));
}
@Test void rewardBuilderResultsKeepOnlyTheSafeRecoveryTarget() {
String proposal = "{\"scope\":\"site\",\"site\":\"PMC\",\"commands\":[\"secret command\"]}";
Map<String, String> result = BackendControlConnectorAccess.resultQuickOptions("reward-builder",
Map<String, String> result = BackendControlConnector.resultQuickOptions("reward-builder",
Map.of("proposal", proposal));
assertEquals(Map.of("targetFile", "VoteSites.yml"), result);
@@ -409,40 +403,40 @@ class BackendControlConnectorProtocolTest {
"/srv/private/VoteSites.yml jdbc:mysql://database.internal user=secret");
assertEquals("Configuration file is unavailable or unreadable",
BackendControlConnectorAccess.operationFailureMessage("READ", failure));
BackendControlConnector.operationFailureMessage("READ", failure));
assertEquals("The backend could not prepare a configuration preview",
BackendControlConnectorAccess.operationFailureMessage("PREVIEW", failure));
BackendControlConnector.operationFailureMessage("PREVIEW", failure));
assertEquals("The backend could not apply the managed configuration",
BackendControlConnectorAccess.operationFailureMessage("APPLY", failure));
assertFalse(BackendControlConnectorAccess.operationFailureMessage("READ", failure).contains("/srv"));
assertEquals("CONFIGURATION_MISSING", BackendControlConnectorAccess.operationFailureCode("READ",
BackendControlConnector.operationFailureMessage("APPLY", failure));
assertFalse(BackendControlConnector.operationFailureMessage("READ", failure).contains("/srv"));
assertEquals("CONFIGURATION_MISSING", BackendControlConnector.operationFailureCode("READ",
new java.nio.file.NoSuchFileException("/srv/private/Config.yml")));
assertEquals("CONFIGURATION_UNREADABLE", BackendControlConnectorAccess.operationFailureCode("READ",
assertEquals("CONFIGURATION_UNREADABLE", BackendControlConnector.operationFailureCode("READ",
new java.nio.file.AccessDeniedException("/srv/private/Config.yml")));
}
@Test void unavailableConfigurationReadsPreserveV1CodeAndUseASafeReason() {
// Existing config.files.v1 peers retain the negotiated code while the
// message gives a useful reason without exposing sensitive paths.
assertEquals("READ_FAILED", BackendControlConnectorAccess.operationFailureCode("READ",
assertEquals("READ_FAILED", BackendControlConnector.operationFailureCode("READ",
new IOException("/srv/private/Config.yml")));
assertEquals("Configuration file is unavailable or unreadable",
BackendControlConnectorAccess.operationFailureMessage("READ", new IOException("/srv/private/Config.yml")));
BackendControlConnector.operationFailureMessage("READ", new IOException("/srv/private/Config.yml")));
}
@Test void networkHealthRequiresItsExplicitCapability() {
BackendControlConnector connector = org.mockito.Mockito.mock(BackendControlConnector.class, org.mockito.Mockito.CALLS_REAL_METHODS);
assertEquals("UNAVAILABLE", BackendControlConnectorAccess.executeInspection(connector, JsonParser.parseString("{\"kind\":\"network-health\",\"filters\":{}}").getAsJsonObject()).code());
assertEquals("UNAVAILABLE", connector.executeInspection(JsonParser.parseString("{\"kind\":\"network-health\",\"filters\":{}}").getAsJsonObject()).code());
}
@Test void namedRewardInventoryRequiresItsExplicitCapability() {
assertTrue(ControlInspectionServiceAccess.rewardFileInventoryQuery(JsonParser.parseString(
assertTrue(ControlInspectionService.rewardFileInventoryQuery(JsonParser.parseString(
"{\"kind\":\"reward-file-inventory\"}").getAsJsonObject()));
assertFalse(ControlInspectionServiceAccess.rewardFileInventoryQuery(JsonParser.parseString(
assertFalse(ControlInspectionService.rewardFileInventoryQuery(JsonParser.parseString(
"{\"kind\":\"overview\"}").getAsJsonObject()));
BackendControlConnector connector = org.mockito.Mockito.mock(BackendControlConnector.class,
org.mockito.Mockito.CALLS_REAL_METHODS);
assertEquals("UNAVAILABLE", BackendControlConnectorAccess.executeInspection(connector, JsonParser.parseString(
assertEquals("UNAVAILABLE", connector.executeInspection(JsonParser.parseString(
"{\"kind\":\"reward-file-inventory\"}").getAsJsonObject()).code());
}
@@ -451,15 +445,15 @@ class BackendControlConnectorProtocolTest {
org.mockito.Mockito.CALLS_REAL_METHODS);
var inspections = BackendControlConnector.class.getDeclaredField("inspections");
inspections.setAccessible(true);
inspections.set(connector, ControlInspectionServiceAccess.create());
inspections.set(connector, new ControlInspectionService());
for (String kind : List.of("null", "{}", "[]")) {
JsonObject query = JsonParser.parseString("{\"kind\":" + kind + ",\"filters\":{}}").getAsJsonObject();
assertEquals("VALIDATION_ERROR", BackendControlConnectorAccess.executeInspection(connector, query).code(), kind);
assertEquals("VALIDATION_ERROR", connector.executeInspection(query).code(), kind);
}
}
@Test void unexpectedInspectionFailureMessagesNeverExposeTheCause() {
String message = BackendControlConnectorAccess.inspectionFailureMessage(new IllegalStateException(
String message = BackendControlConnector.inspectionFailureMessage(new IllegalStateException(
"jdbc:mysql://database.internal/votes user=secret path=/srv/private"));
assertEquals("Inspection failed; see the backend log", message);
@@ -469,7 +463,7 @@ class BackendControlConnectorProtocolTest {
}
@Test void failureMessagesAreSingleLineAndBoundedBeforeSubmission() {
String message = BackendControlConnectorAccess.boundedResultMessage(
String message = BackendControlConnector.boundedResultMessage(
"unsupported field " + "x".repeat(1000) + "\r\nnext line");
assertTrue(message.length() <= 240);
@@ -477,7 +471,7 @@ class BackendControlConnectorProtocolTest {
assertFalse(message.contains("\n"));
assertTrue(message.endsWith("..."));
var changes = BackendControlConnectorAccess.boundedResultChanges(java.util.stream.IntStream.range(0, 25)
var changes = BackendControlConnector.boundedResultChanges(java.util.stream.IntStream.range(0, 25)
.mapToObj(index -> "change-" + index + "-" + "y".repeat(1000)).toList());
assertEquals(20, changes.size());
assertTrue(changes.stream().allMatch(change -> change.length() <= 240));
@@ -485,16 +479,16 @@ class BackendControlConnectorProtocolTest {
}
@Test void operationFailureCodesMatchTheRequestedAction() {
assertEquals("READ_FAILED", BackendControlConnectorAccess.operationFailureCode("READ"));
assertEquals("PREVIEW_FAILED", BackendControlConnectorAccess.operationFailureCode("PREVIEW"));
assertEquals("APPLY_FAILED", BackendControlConnectorAccess.operationFailureCode("APPLY"));
assertEquals("READ_FAILED", BackendControlConnector.operationFailureCode("READ"));
assertEquals("PREVIEW_FAILED", BackendControlConnector.operationFailureCode("PREVIEW"));
assertEquals("APPLY_FAILED", BackendControlConnector.operationFailureCode("APPLY"));
}
@Test void shutdownWaitsForTheClaimedBackendOperation() throws Exception {
var executor = Executors.newSingleThreadScheduledExecutor();
CompletableFuture<Void> operation = new CompletableFuture<>();
CompletableFuture<Void> closing = CompletableFuture.runAsync(
() -> BackendControlConnectorAccess.awaitShutdown(executor, operation));
() -> BackendControlConnector.awaitShutdown(executor, operation));
assertThrows(java.util.concurrent.TimeoutException.class, () -> closing.get(100, TimeUnit.MILLISECONDS));
operation.complete(null);
@@ -517,19 +511,19 @@ class BackendControlConnectorProtocolTest {
});
assertTrue(started.await(1, TimeUnit.SECONDS));
assertTrue(BackendControlConnectorAccess.awaitInspectionShutdown(executor));
assertTrue(BackendControlConnector.awaitInspectionShutdown(executor));
assertTrue(interrupted.get());
assertTrue(executor.isTerminated());
}
@Test void failedResultAcknowledgementDoesNotTriggerConnectorHandoff() throws Exception {
AtomicBoolean handedOff = new AtomicBoolean();
assertThrows(IOException.class, () -> BackendControlConnectorAccess.afterResultAcknowledged(
assertThrows(IOException.class, () -> BackendControlConnector.afterResultAcknowledged(
() -> { throw new IOException("Control result was not acknowledged"); },
() -> handedOff.set(true)));
assertFalse(handedOff.get());
BackendControlConnectorAccess.afterResultAcknowledged(() -> { }, () -> handedOff.set(true));
BackendControlConnector.afterResultAcknowledged(() -> { }, () -> handedOff.set(true));
assertTrue(handedOff.get());
}
}
@@ -1,7 +1,4 @@
package com.bencodez.votingplugin.tests.control;
import com.bencodez.votingplugin.control.BackendConfigurationService;
import com.bencodez.votingplugin.tests.control.BackendControlResultStoreAccess;
package com.bencodez.votingplugin.control;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
@@ -18,8 +15,8 @@ import java.util.UUID;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import com.bencodez.votingplugin.tests.control.BackendControlResultStoreAccess.Route;
import com.bencodez.votingplugin.tests.control.BackendControlResultStoreAccess.StoredResult;
import com.bencodez.votingplugin.control.BackendControlResultStore.Route;
import com.bencodez.votingplugin.control.BackendControlResultStore.StoredResult;
import com.bencodez.votingplugin.proxy.control.HostedControlManager.HostConfiguration;
import com.google.gson.JsonObject;
@@ -38,14 +35,14 @@ class BackendControlResultStoreTest {
Map<UUID, StoredResult> pending = new LinkedHashMap<>();
pending.put(operationId, new StoredResult(result, true, true, false));
BackendControlResultStoreAccess.save(directory, route, hosted, pending);
BackendControlResultStoreAccess.State recovered = BackendControlResultStoreAccess.load(directory);
BackendControlResultStore.save(directory, route, hosted, pending);
BackendControlResultStore.State recovered = BackendControlResultStore.load(directory);
assertEquals(route, recovered.route());
assertEquals(hosted, recovered.hostedConfiguration());
assertEquals("applied-revision", recovered.results().get(operationId).result().get("revision").getAsString());
assertTrue(recovered.results().get(operationId).committed());
BackendControlResultStoreAccess.save(directory, route, hosted, Map.of());
BackendControlResultStore.save(directory, route, hosted, Map.of());
assertFalse(Files.exists(directory.resolve(".control-pending-results.json")));
}
@@ -56,10 +53,10 @@ class BackendControlResultStoreTest {
JsonObject result = new JsonObject();
result.addProperty("revision", "anticipated-revision");
BackendControlResultStoreAccess.save(directory, route, hosted,
BackendControlResultStore.save(directory, route, hosted,
Map.of(operationId, new StoredResult(result, false, false, false)));
StoredResult recovered = BackendControlResultStoreAccess.load(directory).results().get(operationId);
StoredResult recovered = BackendControlResultStore.load(directory).results().get(operationId);
assertFalse(recovered.committed());
assertFalse(recovered.claimRequired());
}
@@ -88,7 +85,7 @@ class BackendControlResultStoreTest {
root.add("results", results);
Files.writeString(directory.resolve(".control-pending-results.json"), root.toString());
BackendControlResultStoreAccess.State recovered = BackendControlResultStoreAccess.load(directory);
BackendControlResultStore.State recovered = BackendControlResultStore.load(directory);
assertEquals(URI.create("https://control.example:8443"), recovered.route().endpoint());
assertFalse(recovered.hostedConfiguration().enabled());
@@ -100,7 +97,7 @@ class BackendControlResultStoreTest {
Files.writeString(external, "{}");
Files.createSymbolicLink(directory.resolve(".control-pending-results.json"), external);
assertThrows(java.io.IOException.class, () -> BackendControlResultStoreAccess.load(directory));
assertThrows(java.io.IOException.class, () -> BackendControlResultStore.load(directory));
}
@Test void maximumEscapeHeavyConfigurationFitsTheEncodedJournal() throws Exception {
@@ -114,12 +111,12 @@ class BackendControlResultStoreTest {
result.addProperty("success", true);
result.add("configuration", configuration);
BackendControlResultStoreAccess.save(directory, route, hosted,
BackendControlResultStore.save(directory, route, hosted,
Map.of(UUID.fromString("00000000-0000-0000-0000-000000000099"),
new StoredResult(result, false, true, false)));
assertEquals(BackendConfigurationService.MAX_CONTENT_BYTES,
BackendControlResultStoreAccess.load(directory).results().values().iterator().next().result()
BackendControlResultStore.load(directory).results().values().iterator().next().result()
.getAsJsonObject("configuration").get("content").getAsString().length());
}
}
@@ -1,6 +1,4 @@
package com.bencodez.votingplugin.tests.control;
import com.bencodez.votingplugin.control.ControlInspectionService;
package com.bencodez.votingplugin.control;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
@@ -53,7 +51,7 @@ class ControlInspectionServiceTest {
when(plugin.getStorageType()).thenReturn(UserStorage.SQLITE);
when(plugin.getBackendProxyHandler()).thenReturn(null);
when(plugin.getServer().getPluginManager().getPlugins()).thenReturn(new org.bukkit.plugin.Plugin[0]);
JsonObject result = ControlInspectionServiceAccess.create(plugin).inspect(JsonParser.parseString("{\"kind\":\"network-health\",\"filters\":{}}").getAsJsonObject()).getAsJsonObject("result");
JsonObject result = new ControlInspectionService(plugin).inspect(JsonParser.parseString("{\"kind\":\"network-health\",\"filters\":{}}").getAsJsonObject()).getAsJsonObject("result");
assertEquals("REQUIRED", result.get("sharedAuthentication").getAsString());
String fixtureDir = System.getProperty("network.health.fixture.dir");
if (fixtureDir != null) {
@@ -71,13 +69,13 @@ class ControlInspectionServiceTest {
VotingPluginMain plugin = mock(VotingPluginMain.class, RETURNS_DEEP_STUBS);
when(plugin.getDataFolder()).thenReturn(directory.toFile());
JsonObject result = ControlInspectionServiceAccess.create(plugin).inspect(JsonParser.parseString(
JsonObject result = new ControlInspectionService(plugin).inspect(JsonParser.parseString(
"{\"kind\":\"reward-file-inventory\",\"filters\":{}}")
.getAsJsonObject()).getAsJsonObject("result");
assertEquals(List.of("Daily.yml"), result.getAsJsonArray("files").asList().stream()
.map(element -> element.getAsString()).toList());
assertTrue(ControlInspectionServiceAccess.rewardFileInventoryQuery(JsonParser.parseString(
assertTrue(ControlInspectionService.rewardFileInventoryQuery(JsonParser.parseString(
"{\"kind\":\"reward-file-inventory\"}").getAsJsonObject()));
}
@@ -92,21 +90,21 @@ class ControlInspectionServiceTest {
.mapToObj(index -> mock(org.bukkit.plugin.Plugin.class, RETURNS_DEEP_STUBS)).toArray(org.bukkit.plugin.Plugin[]::new));
org.bukkit.plugin.Plugin[] plugins = plugin.getServer().getPluginManager().getPlugins();
for (int index = 0; index < plugins.length; index++) when(plugins[index].getName()).thenReturn("Plugin" + index);
JsonObject result = ControlInspectionServiceAccess.create(plugin).inspect(JsonParser.parseString(
JsonObject result = new ControlInspectionService(plugin).inspect(JsonParser.parseString(
"{\"kind\":\"network-health\",\"filters\":{}}").getAsJsonObject()).getAsJsonObject("result");
assertFalse(result.has("detectedPlugins"));
org.bukkit.plugin.Plugin[] complete = new org.bukkit.plugin.Plugin[ControlInspectionServiceAccess.MAX_ROWS];
org.bukkit.plugin.Plugin[] complete = new org.bukkit.plugin.Plugin[ControlInspectionService.MAX_ROWS];
for (int index = 0; index < complete.length; index++) {
complete[index] = mock(org.bukkit.plugin.Plugin.class, RETURNS_DEEP_STUBS);
when(complete[index].getName()).thenReturn("Complete" + index);
}
when(plugin.getServer().getPluginManager().getPlugins()).thenReturn(complete);
result = ControlInspectionServiceAccess.create(plugin).inspect(JsonParser.parseString(
result = new ControlInspectionService(plugin).inspect(JsonParser.parseString(
"{\"kind\":\"network-health\",\"filters\":{}}").getAsJsonObject()).getAsJsonObject("result");
assertEquals(ControlInspectionServiceAccess.MAX_ROWS, result.getAsJsonArray("detectedPlugins").size());
complete[ControlInspectionServiceAccess.MAX_ROWS - 1] = mock(org.bukkit.plugin.Plugin.class, RETURNS_DEEP_STUBS);
when(complete[ControlInspectionServiceAccess.MAX_ROWS - 1].getName()).thenReturn("bad\nname");
result = ControlInspectionServiceAccess.create(plugin).inspect(JsonParser.parseString(
assertEquals(ControlInspectionService.MAX_ROWS, result.getAsJsonArray("detectedPlugins").size());
complete[ControlInspectionService.MAX_ROWS - 1] = mock(org.bukkit.plugin.Plugin.class, RETURNS_DEEP_STUBS);
when(complete[ControlInspectionService.MAX_ROWS - 1].getName()).thenReturn("bad\nname");
result = new ControlInspectionService(plugin).inspect(JsonParser.parseString(
"{\"kind\":\"network-health\",\"filters\":{}}").getAsJsonObject()).getAsJsonObject("result");
assertFalse(result.has("detectedPlugins"));
}
@@ -119,7 +117,7 @@ class ControlInspectionServiceTest {
when(plugin.getConfigVoteSites().getData()).thenReturn(voteSites);
when(plugin.getVoteSiteManager().getVoteSites()).thenReturn(new ArrayList<>());
when(plugin.getVoteLogMysqlTable()).thenReturn(null);
ControlInspectionService service = ControlInspectionServiceAccess.create(plugin);
ControlInspectionService service = new ControlInspectionService(plugin);
JsonObject result = service.inspect(JsonParser.parseString(
"{\"kind\":\"overview\",\"filters\":{}}")
@@ -130,7 +128,7 @@ class ControlInspectionServiceTest {
}
@Test void rewardSimulationNormalizesButNeverExecutesTypedActions() {
ControlInspectionService service = ControlInspectionServiceAccess.create();
ControlInspectionService service = new ControlInspectionService();
JsonObject proposal = JsonParser.parseString("""
{"scope":"site","site":"PMC","commands":["eco give %player% 100"],
"playerMessages":["Thanks"],"items":[{"material":"diamond","amount":2}],
@@ -155,7 +153,7 @@ class ControlInspectionServiceTest {
}
@Test void inspectionContractRejectsUnknownKindsFieldsAndUnboundedSearches() {
ControlInspectionService service = ControlInspectionServiceAccess.create();
ControlInspectionService service = new ControlInspectionService();
assertThrows(IllegalArgumentException.class,
() -> service.inspect(JsonParser.parseString("{\"kind\":\"raw-sql\"}").getAsJsonObject()));
@@ -194,7 +192,7 @@ class ControlInspectionServiceTest {
}
@Test void rewardProposalRejectsUnknownActionsAndEmptyPlans() {
ControlInspectionService service = ControlInspectionServiceAccess.create();
ControlInspectionService service = new ControlInspectionService();
assertThrows(IllegalArgumentException.class, () -> service.inspect(rewardQuery(JsonParser.parseString(
"{\"scope\":\"site\",\"site\":\"PMC\",\"shell\":\"rm\"}").getAsJsonObject())));
assertThrows(IllegalArgumentException.class, () -> service.inspect(rewardQuery(JsonParser.parseString(
@@ -211,7 +209,7 @@ class ControlInspectionServiceTest {
VotingPluginMain plugin = mock(VotingPluginMain.class, RETURNS_DEEP_STUBS);
when(plugin.getConfigVoteSites().getData())
.thenReturn(new org.bukkit.configuration.file.YamlConfiguration());
ControlInspectionService service = ControlInspectionServiceAccess.create(plugin);
ControlInspectionService service = new ControlInspectionService(plugin);
assertThrows(IllegalArgumentException.class, () -> service.inspect(rewardQuery(JsonParser.parseString(
"{\"scope\":\"site\",\"site\":\"Missing\",\"commands\":[\"say test\"]}"
@@ -222,7 +220,7 @@ class ControlInspectionServiceTest {
VotingPluginMain plugin = mock(VotingPluginMain.class, RETURNS_DEEP_STUBS);
VoteLogMysqlTable staleTable = mock(VoteLogMysqlTable.class);
when(plugin.getVoteLogMysqlTable()).thenReturn(staleTable);
ControlInspectionService service = ControlInspectionServiceAccess.create(plugin);
ControlInspectionService service = new ControlInspectionService(plugin);
JsonObject query = JsonParser.parseString(
"{\"kind\":\"vote-log-summary\",\"filters\":{\"days\":\"30\"}}")
.getAsJsonObject();
@@ -238,7 +236,7 @@ class ControlInspectionServiceTest {
when(plugin.getConfigFile().isVoteLoggingEnabled()).thenReturn(true);
when(plugin.getVoteLogMysqlTable()).thenReturn(table);
when(table.isReadable()).thenReturn(false);
ControlInspectionService service = ControlInspectionServiceAccess.create(plugin);
ControlInspectionService service = new ControlInspectionService(plugin);
JsonObject query = JsonParser.parseString(
"{\"kind\":\"vote-log-summary\",\"filters\":{\"days\":\"30\"}}")
.getAsJsonObject();
@@ -260,7 +258,7 @@ class ControlInspectionServiceTest {
new ServiceCount("Zulu", 3), new ServiceCount("alpha", 3), new ServiceCount("Middle", 6)));
when(table.getTopServers(30, 20)).thenReturn(List.of(
new ServerCount("survival", 2), new ServerCount("Creative", 2), new ServerCount("hub", 8)));
ControlInspectionService service = ControlInspectionServiceAccess.create(plugin);
ControlInspectionService service = new ControlInspectionService(plugin);
JsonObject result = service.inspect(JsonParser.parseString(
"{\"kind\":\"vote-log-summary\",\"filters\":{\"days\":\"30\"}}")
@@ -283,7 +281,7 @@ class ControlInspectionServiceTest {
@Test void exactPlayerMissDoesNotLoadOrEnumerateUsers() {
VotingPluginMain plugin = mock(VotingPluginMain.class, RETURNS_DEEP_STUBS);
when(plugin.getUserManager().userExist("ExactName")).thenReturn(false);
ControlInspectionService service = ControlInspectionServiceAccess.create(plugin);
ControlInspectionService service = new ControlInspectionService(plugin);
JsonObject query = JsonParser.parseString(
"{\"kind\":\"player\",\"filters\":{\"name\":\"ExactName\"}}")
.getAsJsonObject();
@@ -308,7 +306,7 @@ class ControlInspectionServiceTest {
lastVotes.put(earlier, 100L);
when(user.getLastVotes()).thenReturn(lastVotes);
when(user.getLastVoteTime()).thenReturn(200L);
ControlInspectionService service = ControlInspectionServiceAccess.create(plugin);
ControlInspectionService service = new ControlInspectionService(plugin);
JsonObject result = service.inspect(JsonParser.parseString(
"{\"kind\":\"player\",\"filters\":{\"name\":\"ExactName\"}}")
@@ -350,7 +348,7 @@ class ControlInspectionServiceTest {
stored.put("MonthTotal-SMARCH-2025", new DataValueInt(95));
stored.put("MonthTotal-FEBRUARY-2025", new DataValueString("wrong type"));
when(user.getUserData().getValues()).thenReturn(stored);
ControlInspectionService service = ControlInspectionServiceAccess.create(plugin);
ControlInspectionService service = new ControlInspectionService(plugin);
JsonObject result = service.inspect(JsonParser.parseString(
"{\"kind\":\"player\",\"filters\":{\"name\":\"ExactName\"}}")
@@ -386,20 +384,20 @@ class ControlInspectionServiceTest {
when(user.getLastVotes()).thenReturn(new HashMap<>());
HashMap<String, DataValue> stored = new HashMap<>();
List<String> expected = new ArrayList<>();
for (int index = 0; index <= ControlInspectionServiceAccess.MAX_ROWS; index++) {
for (int index = 0; index <= ControlInspectionService.MAX_ROWS; index++) {
String name = "MonthTotal-" + java.time.Month.of(index % 12 + 1).name() + "-" + (2000 + index / 12);
stored.put(name, new DataValueInt(index));
expected.add(name);
}
expected.sort(String.CASE_INSENSITIVE_ORDER.thenComparing(java.util.Comparator.naturalOrder()));
when(user.getUserData().getValues()).thenReturn(stored);
ControlInspectionService service = ControlInspectionServiceAccess.create(plugin);
ControlInspectionService service = new ControlInspectionService(plugin);
JsonObject result = service.inspect(JsonParser.parseString(
"{\"kind\":\"player\",\"filters\":{\"name\":\"ExactName\"}}")
.getAsJsonObject()).getAsJsonObject("result");
assertEquals(expected.subList(0, ControlInspectionServiceAccess.MAX_ROWS),
assertEquals(expected.subList(0, ControlInspectionService.MAX_ROWS),
result.getAsJsonArray("columns").asList().stream()
.map(value -> value.getAsJsonObject().get("name").getAsString()).toList());
assertTrue(result.get("columnsTruncated").getAsBoolean());
@@ -416,17 +414,17 @@ class ControlInspectionServiceTest {
when(user.getOfflineVotes()).thenReturn(new ArrayList<>());
when(user.getLastVotes()).thenReturn(new HashMap<>());
HashMap<String, DataValue> stored = new HashMap<>();
for (int index = 0; index <= ControlInspectionServiceAccess.MAX_ROWS; index++) {
for (int index = 0; index <= ControlInspectionService.MAX_ROWS; index++) {
stored.put(String.format("VoteShopLimit%03d", index), new DataValueInt(index));
}
when(user.getUserData().getValues()).thenReturn(stored);
ControlInspectionService service = ControlInspectionServiceAccess.create(plugin);
ControlInspectionService service = new ControlInspectionService(plugin);
JsonObject result = service.inspect(JsonParser.parseString(
"{\"kind\":\"player\",\"filters\":{\"name\":\"ExactName\"}}")
.getAsJsonObject()).getAsJsonObject("result");
assertEquals(ControlInspectionServiceAccess.MAX_ROWS, result.getAsJsonArray("columns").size());
assertEquals(ControlInspectionService.MAX_ROWS, result.getAsJsonArray("columns").size());
assertEquals("VoteShopLimit000", result.getAsJsonArray("columns").get(0).getAsJsonObject()
.get("name").getAsString());
assertEquals("VoteShopLimit099", result.getAsJsonArray("columns").get(99).getAsJsonObject()
@@ -442,7 +440,7 @@ class ControlInspectionServiceTest {
when(plugin.getConfigVoteSites().getData()).thenReturn(voteSites);
when(plugin.getVoteSiteManager().getVoteSites()).thenReturn(new ArrayList<>());
when(plugin.getVoteLogMysqlTable()).thenReturn(null);
org.bukkit.plugin.Plugin[] installed = new org.bukkit.plugin.Plugin[ControlInspectionServiceAccess.MAX_ROWS + 1];
org.bukkit.plugin.Plugin[] installed = new org.bukkit.plugin.Plugin[ControlInspectionService.MAX_ROWS + 1];
for (int index = 0; index < installed.length; index++) {
installed[index] = mock(org.bukkit.plugin.Plugin.class, RETURNS_DEEP_STUBS);
when(installed[index].getDescription().getName()).thenReturn(String.format("Plugin%03d", index));
@@ -450,13 +448,13 @@ class ControlInspectionServiceTest {
when(installed[99].getDescription().getName()).thenReturn("plugina");
when(installed[100].getDescription().getName()).thenReturn("PluginA");
when(plugin.getServer().getPluginManager().getPlugins()).thenReturn(installed);
ControlInspectionService service = ControlInspectionServiceAccess.create(plugin);
ControlInspectionService service = new ControlInspectionService(plugin);
JsonObject result = service.inspect(JsonParser.parseString(
"{\"kind\":\"diagnostics\",\"filters\":{}}")
.getAsJsonObject()).getAsJsonObject("result");
assertEquals(ControlInspectionServiceAccess.MAX_ROWS, result.getAsJsonArray("detectedPlugins").size());
assertEquals(ControlInspectionService.MAX_ROWS, result.getAsJsonArray("detectedPlugins").size());
assertEquals("Plugin000", result.getAsJsonArray("detectedPlugins").get(0).getAsString());
assertEquals("PluginA", result.getAsJsonArray("detectedPlugins").get(99).getAsString());
assertTrue(result.get("detectedPluginsTruncated").getAsBoolean());
@@ -470,7 +468,7 @@ class ControlInspectionServiceTest {
when(plugin.getVoteLogMysqlTable()).thenReturn(null);
when(plugin.getServerData().getServiceSitesReadOnly()).thenReturn(java.util.List.of(
"NEW.example", "new.EXAMPLE", "configured.example"));
ControlInspectionService service = ControlInspectionServiceAccess.create(plugin);
ControlInspectionService service = new ControlInspectionService(plugin);
JsonObject result = service.inspect(JsonParser.parseString(
"{\"kind\":\"vote-site-health\",\"filters\":{\"days\":\"30\"}}")
@@ -495,7 +493,7 @@ class ControlInspectionServiceTest {
when(plugin.getVoteLogMysqlTable()).thenReturn(table);
when(table.isReadable()).thenReturn(false);
when(plugin.getServerData().getServiceSitesReadOnly()).thenReturn(java.util.List.of());
ControlInspectionService service = ControlInspectionServiceAccess.create(plugin);
ControlInspectionService service = new ControlInspectionService(plugin);
JsonObject result = service.inspect(JsonParser.parseString(
"{\"kind\":\"vote-site-health\",\"filters\":{\"days\":\"30\"}}")
@@ -525,7 +523,7 @@ class ControlInspectionServiceTest {
when(table.getServiceHealthForServices(30, List.of("configured.example"))).thenReturn(List.of(
new ServiceHealth("configured.example", 7, 500, 6, 1)));
when(plugin.getServerData().getServiceSitesReadOnly()).thenReturn(List.of());
ControlInspectionService service = ControlInspectionServiceAccess.create(plugin);
ControlInspectionService service = new ControlInspectionService(plugin);
JsonObject result = service.inspect(JsonParser.parseString(
"{\"kind\":\"vote-site-health\",\"filters\":{\"days\":\"30\"}}")
@@ -553,7 +551,7 @@ class ControlInspectionServiceTest {
new ServiceHealth(fullService.toUpperCase(Locale.ROOT), 5, 900, 4, 1)));
when(plugin.getServerData().getServiceSitesReadOnly()).thenReturn(List.of(
fullService.toUpperCase(Locale.ROOT)));
ControlInspectionService service = ControlInspectionServiceAccess.create(plugin);
ControlInspectionService service = new ControlInspectionService(plugin);
JsonObject result = service.inspect(JsonParser.parseString(
"{\"kind\":\"vote-site-health\",\"filters\":{\"days\":\"30\"}}")
@@ -585,7 +583,7 @@ class ControlInspectionServiceTest {
new ServiceHealth("configured-100.example", 3, 800, 3, 0)));
when(table.getServiceHealthForServices(30, displayed)).thenReturn(List.of());
when(plugin.getServerData().getServiceSitesReadOnly()).thenReturn(List.of());
ControlInspectionService service = ControlInspectionServiceAccess.create(plugin);
ControlInspectionService service = new ControlInspectionService(plugin);
JsonObject result = service.inspect(JsonParser.parseString(
"{\"kind\":\"vote-site-health\",\"filters\":{\"days\":\"30\"}}")
@@ -610,7 +608,7 @@ class ControlInspectionServiceTest {
new ServiceHealth("example.COM", 4, 900, 3, 1)));
when(table.getServiceHealthForServices(30, List.of("example.com"))).thenReturn(List.of());
when(plugin.getServerData().getServiceSitesReadOnly()).thenReturn(List.of());
ControlInspectionService service = ControlInspectionServiceAccess.create(plugin);
ControlInspectionService service = new ControlInspectionService(plugin);
JsonObject result = service.inspect(JsonParser.parseString(
"{\"kind\":\"vote-site-health\",\"filters\":{\"days\":\"30\"}}")
@@ -631,7 +629,7 @@ class ControlInspectionServiceTest {
.thenReturn(null);
when(plugin.getVoteSiteManager().resolveVoteSite("new.example", true)).thenReturn(null);
when(plugin.getConfigFile().isAutoCreateVoteSites()).thenReturn(true);
ControlInspectionService service = ControlInspectionServiceAccess.create(plugin);
ControlInspectionService service = new ControlInspectionService(plugin);
JsonObject result = service.inspect(JsonParser.parseString(
"{\"kind\":\"vote-site-resolution\",\"filters\":{\"serviceSite\":\"new.example\"}}")
@@ -656,7 +654,7 @@ class ControlInspectionServiceTest {
when(plugin.getVoteSiteManager().resolveVoteSite("PMC", true)).thenReturn(site);
when(plugin.getVoteSiteManager().hasVoteSite("PMC")).thenReturn(true);
when(plugin.getConfigFile().isAutoCreateVoteSites()).thenReturn(true);
ControlInspectionService service = ControlInspectionServiceAccess.create(plugin);
ControlInspectionService service = new ControlInspectionService(plugin);
JsonObject result = service.inspect(JsonParser.parseString(
"{\"kind\":\"vote-site-resolution\",\"filters\":{\"serviceSite\":\"planetminecraft.com\"}}")
@@ -1,6 +1,4 @@
package com.bencodez.votingplugin.tests.control;
import com.bencodez.votingplugin.tests.control.NetworkHealthConfigFactsAccess;
package com.bencodez.votingplugin.control;
import static org.junit.jupiter.api.Assertions.*;
@@ -17,7 +15,7 @@ class NetworkHealthConfigFactsTest {
yaml.set("Database.Password", "secret");
yaml.set("BedrockPlayerPrefix", "x".repeat(81));
JsonObject out = new JsonObject();
NetworkHealthConfigFactsAccess.addBackend(out, yaml);
NetworkHealthConfigFacts.addBackend(out, yaml);
assertTrue(out.get("onlineMode").getAsBoolean());
assertFalse(out.has("maxVotesPerDay"));
assertFalse(out.has("Database.Password"));
@@ -34,8 +32,8 @@ class NetworkHealthConfigFactsTest {
special.set("VoteParty.VotesRequired", 12);
special.set("ResetMilestonesMonthly", false);
JsonObject out = new JsonObject();
NetworkHealthConfigFactsAccess.addBackend(out, main);
NetworkHealthConfigFactsAccess.addSpecialRewards(out, special);
NetworkHealthConfigFacts.addBackend(out, main);
NetworkHealthConfigFacts.addSpecialRewards(out, special);
assertFalse(out.get("votePartyEnabled").getAsBoolean());
assertEquals(12, out.get("votePartyVotesRequired").getAsInt());
assertFalse(out.get("resetMilestonesMonthly").getAsBoolean());
@@ -46,7 +44,7 @@ class NetworkHealthConfigFactsTest {
yaml.set("GlobalData.Prefix", "p".repeat(81));
yaml.set("GlobalData.UseMainMySQL", "yes");
JsonObject out = new JsonObject();
NetworkHealthConfigFactsAccess.addGlobal(out, yaml);
NetworkHealthConfigFacts.addGlobal(out, yaml);
assertFalse(out.has("globalDataPrefix"));
assertFalse(out.has("globalDataUseMainMysql"));
}
@@ -55,10 +53,10 @@ class NetworkHealthConfigFactsTest {
YamlConfiguration yaml = new YamlConfiguration();
yaml.set("TimeHourOffSet", Integer.MAX_VALUE);
JsonObject out = new JsonObject();
NetworkHealthConfigFactsAccess.addBackend(out, yaml);
NetworkHealthConfigFacts.addBackend(out, yaml);
assertFalse(out.has("timeHourOffset"));
yaml.set("TimeHourOffSet", -3);
NetworkHealthConfigFactsAccess.addBackend(out, yaml);
NetworkHealthConfigFacts.addBackend(out, yaml);
assertEquals(-3, out.get("timeHourOffset").getAsInt());
}
@@ -68,7 +66,7 @@ class NetworkHealthConfigFactsTest {
special.set("VoteParty.VotesRequired", "many");
special.set("ResetMilestonesMonthly", 1);
JsonObject out = new JsonObject();
NetworkHealthConfigFactsAccess.addSpecialRewards(out, special);
NetworkHealthConfigFacts.addSpecialRewards(out, special);
assertFalse(out.has("votePartyEnabled"));
assertFalse(out.has("votePartyVotesRequired"));
assertFalse(out.has("resetMilestonesMonthly"));
@@ -80,31 +78,31 @@ class NetworkHealthConfigFactsTest {
YamlConfiguration yaml = new YamlConfiguration();
yaml.set("TimeHourOffSet", Long.MIN_VALUE);
JsonObject out = new JsonObject();
NetworkHealthConfigFactsAccess.addBackend(out, yaml);
NetworkHealthConfigFacts.addBackend(out, yaml);
assertFalse(out.has("timeHourOffset"));
}
@Test void delayParserEmptyResultCannotProveMalformedTextValid() {
for (String text : java.util.List.of("abc", "-5h", "")) {
JsonObject out = new JsonObject();
NetworkHealthConfigFactsAccess.addDelay(out, text, null, com.bencodez.simpleapi.time.ParsedDuration.parse(text, java.util.concurrent.TimeUnit.HOURS));
NetworkHealthConfigFacts.addDelay(out, text, null, com.bencodez.simpleapi.time.ParsedDuration.parse(text, java.util.concurrent.TimeUnit.HOURS));
assertFalse(out.get("delayValid").getAsBoolean());
}
JsonObject halfHour = new JsonObject();
NetworkHealthConfigFactsAccess.addDelay(halfHour, "30m", null, com.bencodez.simpleapi.time.ParsedDuration.parse("30m"));
NetworkHealthConfigFacts.addDelay(halfHour, "30m", null, com.bencodez.simpleapi.time.ParsedDuration.parse("30m"));
assertTrue(halfHour.get("delayValid").getAsBoolean()); assertEquals(1, halfHour.get("delayHours").getAsInt());
JsonObject zero = new JsonObject();
NetworkHealthConfigFactsAccess.addDelay(zero, "0", null, com.bencodez.simpleapi.time.ParsedDuration.empty());
NetworkHealthConfigFacts.addDelay(zero, "0", null, com.bencodez.simpleapi.time.ParsedDuration.empty());
assertTrue(zero.get("delayValid").getAsBoolean()); assertEquals(0, zero.get("delayHours").getAsInt());
}
@Test void incompleteServiceObservationsAreOmittedInsteadOfEmpty() {
JsonObject invalid = new JsonObject();
NetworkHealthConfigFactsAccess.addObservedServices(invalid, java.util.List.of("unmatched", "s".repeat(81)));
NetworkHealthConfigFacts.addObservedServices(invalid, java.util.List.of("unmatched", "s".repeat(81)));
assertFalse(invalid.has("detectedServices"));
JsonObject large = new JsonObject();
NetworkHealthConfigFactsAccess.addObservedServices(large, java.util.stream.IntStream.range(0, 101).mapToObj(i -> "site" + i).toList());
NetworkHealthConfigFacts.addObservedServices(large, java.util.stream.IntStream.range(0, 101).mapToObj(i -> "site" + i).toList());
assertFalse(large.has("detectedServices"));
JsonObject valid = new JsonObject();
NetworkHealthConfigFactsAccess.addObservedServices(valid, java.util.List.of("site", "SITE", "other"));
NetworkHealthConfigFacts.addObservedServices(valid, java.util.List.of("site", "SITE", "other"));
assertEquals(2, valid.getAsJsonArray("detectedServices").size());
}
@@ -1,8 +1,4 @@
package com.bencodez.votingplugin.tests.control;
import com.bencodez.votingplugin.tests.support.ReflectiveAccess;
import com.bencodez.votingplugin.control.OptionalVotifierDiagnostics;
package com.bencodez.votingplugin.control;
import com.google.gson.JsonObject;
import java.lang.reflect.*;
@@ -51,7 +47,7 @@ class NuVotifierJarDiagnosticsTest {
String packageName = platform.substring(0, platform.indexOf('.'));
Object pm = mock(Class.forName("com.vexsoftware.votifier." + packageName + "." + sourceName, false, loader));
Class<?> base = pm.getClass().getSuperclass();
Field owner = base.getDeclaredField("plugin"); owner.setAccessible(true); ReflectiveAccess.set(owner, pm, provider);
Field owner = base.getDeclaredField("plugin"); owner.setAccessible(true); owner.set(pm, provider);
Field filter = base.getDeclaredField("serverFilter"); filter.setAccessible(true);
Class<?> backendApi = Class.forName("com.vexsoftware.votifier.platform.BackendServer", false, loader);
Object backend = mock(backendApi);
@@ -61,31 +57,31 @@ class NuVotifierJarDiagnosticsTest {
Constructor<?> filterCtor = Class.forName("com.vexsoftware.votifier.support.forwarding.ServerFilter", false, loader)
.getConstructor(Collection.class, boolean.class);
setSource(provider, pm);
ReflectiveAccess.set(filter, pm, ReflectiveAccess.newInstance(filterCtor, new Object[]{List.of("backend-a"), true}));
filter.set(pm, filterCtor.newInstance(List.of("backend-a"), true));
assertTrue(facts(provider).get("votifierForwardingEnabled").getAsBoolean());
assertEquals("backend-a", facts(provider).getAsJsonArray("forwardingDestinations").get(0).getAsString());
ReflectiveAccess.set(filter, pm, ReflectiveAccess.newInstance(filterCtor, new Object[]{List.of(), true}));
filter.set(pm, filterCtor.newInstance(List.of(), true));
assertFalse(facts(provider).get("votifierForwardingEnabled").getAsBoolean());
ReflectiveAccess.set(filter, pm, ReflectiveAccess.newInstance(filterCtor, new Object[]{List.of("backend-a"), false}));
filter.set(pm, filterCtor.newInstance(List.of("backend-a"), false));
assertFalse(facts(provider).get("votifierForwardingEnabled").getAsBoolean());
if (sourceName.startsWith("OnlineForward")) {
Field fallback = pm.getClass().getDeclaredField("fallbackServer"); fallback.setAccessible(true);
when(proxyApi.getMethod("getServer", String.class).invoke(provider, "backend-a"))
.thenReturn(Optional.of(backend));
ReflectiveAccess.set(fallback, pm, "backend-a");
fallback.set(pm, "backend-a");
// Both an empty whitelist and a rejecting blacklist still allow the fallback.
for (boolean whitelist : List.of(true, false)) {
ReflectiveAccess.set(filter, pm, ReflectiveAccess.newInstance(filterCtor, new Object[]{whitelist ? List.of() : List.of("backend-a"), whitelist}));
filter.set(pm, filterCtor.newInstance(whitelist ? List.of() : List.of("backend-a"), whitelist));
assertTrue(facts(provider).get("votifierForwardingEnabled").getAsBoolean());
assertEquals("backend-a", facts(provider).getAsJsonArray("forwardingDestinations").get(0).getAsString());
}
when(proxyApi.getMethod("getServer", String.class).invoke(provider, "backend-a"))
.thenReturn(Optional.empty());
assertFalse(facts(provider).get("votifierForwardingEnabled").getAsBoolean());
ReflectiveAccess.set(fallback, pm, "bad\nname"); assertUnknown(provider);
ReflectiveAccess.set(fallback, pm, null);
fallback.set(pm, "bad\nname"); assertUnknown(provider);
fallback.set(pm, null);
}
ReflectiveAccess.set(filter, pm, null); assertUnknown(provider);
filter.set(pm, null); assertUnknown(provider);
}
}
}
@@ -96,12 +92,13 @@ class NuVotifierJarDiagnosticsTest {
Constructor<?> backend = Class.forName(source.getName() + "$BackendServer", false, loader)
.getConstructor(String.class, InetSocketAddress.class, java.security.Key.class);
List<Object> targets = new ArrayList<>();
for (String name : names) targets.add(ReflectiveAccess.newInstance(backend, new Object[]{name, InetSocketAddress.createUnresolved("not-exported.invalid", 8192), null}));
for (String name : names) targets.add(backend.newInstance(name,
InetSocketAddress.createUnresolved("not-exported.invalid", 8192), null));
Constructor<?> ctor = Arrays.stream(source.getConstructors()).filter(c -> c.getParameterCount() == 4).findFirst().orElseThrow();
return ReflectiveAccess.newInstance(ctor, new Object[]{null, null, targets, null}); // stores fields; no start/forward call
return ctor.newInstance(null, null, targets, null); // stores fields; no start/forward call
}
private static void setSource(Object provider, Object source) throws Exception {
Field field = provider.getClass().getDeclaredField("forwardingMethod"); field.setAccessible(true); ReflectiveAccess.set(field, provider, source);
Field field = provider.getClass().getDeclaredField("forwardingMethod"); field.setAccessible(true); field.set(provider, source);
}
private static JsonObject facts(Object provider) { return facts(List.of(provider)); }
private static JsonObject facts(List<?> providers) {
@@ -1,6 +1,4 @@
package com.bencodez.votingplugin.tests.control;
import com.bencodez.votingplugin.control.OptionalVotifierDiagnostics;
package com.bencodez.votingplugin.control;
import com.google.gson.JsonObject;
import java.util.*;
import org.junit.jupiter.api.Test;
@@ -1,6 +1,4 @@
package com.bencodez.votingplugin.tests.control;
import com.bencodez.votingplugin.control.PluginDeploymentService;
package com.bencodez.votingplugin.control;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
@@ -45,7 +43,7 @@ class PluginDeploymentServiceTest {
java.util.Map.of("create", "true"))) {
Path destination = zip.getPath("/VotingPlugin.jar");
assertThrows(AtomicMoveNotSupportedException.class,
() -> PluginDeploymentServiceAccess.move(source, destination));
() -> PluginDeploymentService.move(source, destination));
assertArrayEquals(original, Files.readAllBytes(source));
assertFalse(Files.exists(destination));
}
@@ -56,12 +54,12 @@ class PluginDeploymentServiceTest {
PluginDeploymentService service = PluginDeploymentService.backend(directory.resolve("update"), Path.of("VotingPlugin.jar"));
PluginDeploymentService.Task task = task(artifact);
PluginDeploymentService.Result staged = PluginDeploymentServiceAccess.stage(service, task, new ByteArrayInputStream(artifact), () -> true);
PluginDeploymentService.Result staged = service.stage(task, new ByteArrayInputStream(artifact), () -> true);
assertTrue(staged.success());
assertEquals("RESTART_REQUIRED", staged.code());
assertEquals(artifact.length, Files.size(directory.resolve("update/VotingPlugin.jar")));
assertTrue(PluginDeploymentServiceAccess.stage(service, task, new ByteArrayInputStream(new byte[0]), () -> true).success());
assertTrue(service.stage(task, new ByteArrayInputStream(new byte[0]), () -> true).success());
}
@Test void backendStagesUsingTheInstalledPluginJarFileName() throws Exception {
@@ -70,7 +68,7 @@ class PluginDeploymentServiceTest {
PluginDeploymentService service = PluginDeploymentService.backend(update,
directory.resolve("plugins/VotingPlugin-7.1.2.jar"));
assertEquals("RESTART_REQUIRED", PluginDeploymentServiceAccess.stage(service, task(artifact), new ByteArrayInputStream(artifact), () -> true).code());
assertEquals("RESTART_REQUIRED", service.stage(task(artifact), new ByteArrayInputStream(artifact), () -> true).code());
assertArrayEquals(artifact, Files.readAllBytes(update.resolve("VotingPlugin-7.1.2.jar")));
assertFalse(Files.exists(update.resolve("VotingPlugin.jar")));
}
@@ -88,11 +86,11 @@ class PluginDeploymentServiceTest {
PluginDeploymentService service = PluginDeploymentService.backend(update, installed);
PluginDeploymentService.Task task = task(artifact);
assertTrue(PluginDeploymentServiceAccess.stage(service, task, new ByteArrayInputStream(artifact), () -> true).success());
assertTrue(service.stage(task, new ByteArrayInputStream(artifact), () -> true).success());
Files.write(installed, artifact);
Files.delete(update.resolve("VotingPlugin.jar"));
assertTrue(PluginDeploymentServiceAccess.stage(service, task, new ByteArrayInputStream(new byte[0]), () -> true).success());
assertTrue(service.stage(task, new ByteArrayInputStream(new byte[0]), () -> true).success());
assertFalse(Files.exists(update.resolve("VotingPlugin.jar")),
"a lost acknowledgement after restart must recognize the artifact Bukkit already consumed");
}
@@ -105,17 +103,17 @@ class PluginDeploymentServiceTest {
PluginDeploymentService service = PluginDeploymentService.backend(update, installed);
PluginDeploymentService.Task original = task(artifact);
PluginDeploymentService.Task retry = task(artifact);
assertTrue(PluginDeploymentServiceAccess.stage(service, original, new ByteArrayInputStream(artifact), () -> true).success());
assertTrue(service.stage(original, new ByteArrayInputStream(artifact), () -> true).success());
assertFalse(original.deploymentId().equals(retry.deploymentId()));
assertEquals("RESTART_REQUIRED",
PluginDeploymentServiceAccess.stage(service, retry, new ByteArrayInputStream(new byte[0]), () -> true).code());
service.stage(retry, new ByteArrayInputStream(new byte[0]), () -> true).code());
assertArrayEquals(artifact, Files.readAllBytes(update.resolve("VotingPlugin.jar")));
Files.write(installed, artifact);
Files.delete(update.resolve("VotingPlugin.jar"));
assertEquals("RESTART_REQUIRED",
PluginDeploymentServiceAccess.stage(service, retry, new ByteArrayInputStream(new byte[0]), () -> true).code());
service.stage(retry, new ByteArrayInputStream(new byte[0]), () -> true).code());
assertFalse(Files.exists(update.resolve("VotingPlugin.jar")));
}
@@ -127,10 +125,10 @@ class PluginDeploymentServiceTest {
PluginDeploymentService service = PluginDeploymentService.backend(update, installed);
PluginDeploymentService.Task task = task(artifact);
assertTrue(PluginDeploymentServiceAccess.stage(service, task, new ByteArrayInputStream(artifact), () -> true).success());
assertTrue(service.stage(task, new ByteArrayInputStream(artifact), () -> true).success());
Files.delete(update.resolve("VotingPlugin.jar"));
assertTrue(PluginDeploymentServiceAccess.stage(service, task, new ByteArrayInputStream(artifact), () -> true).success());
assertTrue(service.stage(task, new ByteArrayInputStream(artifact), () -> true).success());
assertArrayEquals(artifact, Files.readAllBytes(update.resolve("VotingPlugin.jar")),
"a deleted or quarantined update must be staged again before restart");
}
@@ -203,7 +201,7 @@ class PluginDeploymentServiceTest {
PluginDeploymentService service = PluginDeploymentService.backend(directory.resolve("update"), Path.of("VotingPlugin.jar"));
PluginDeploymentService.Task task = task(artifact);
PluginDeploymentServiceAccess.stage(service, task, new ByteArrayInputStream(artifact), () -> true);
service.stage(task, new ByteArrayInputStream(artifact), () -> true);
assertArrayEquals(artifact, Files.readAllBytes(directory.resolve("update/VotingPlugin.jar")));
byte[] corrupted = new byte[artifact.length];
@@ -211,14 +209,14 @@ class PluginDeploymentServiceTest {
Files.write(directory.resolve("update/VotingPlugin.jar"), corrupted);
assertArrayEquals(corrupted, Files.readAllBytes(directory.resolve("update/VotingPlugin.jar")));
assertTrue(PluginDeploymentServiceAccess.stage(service, task, new ByteArrayInputStream(artifact), () -> true).success());
assertTrue(service.stage(task, new ByteArrayInputStream(artifact), () -> true).success());
assertArrayEquals(artifact, Files.readAllBytes(directory.resolve("update/VotingPlugin.jar")));
}
@Test void invalidPluginIdentityAndDigestNeverReachTheUpdateFolder() throws Exception {
byte[] wrongPlugin = jar("name: NotVotingPlugin\n");
PluginDeploymentService service = PluginDeploymentService.backend(directory.resolve("update"), Path.of("VotingPlugin.jar"));
PluginDeploymentService.Result invalid = PluginDeploymentServiceAccess.stage(service, task(wrongPlugin), new ByteArrayInputStream(wrongPlugin), () -> true);
PluginDeploymentService.Result invalid = service.stage(task(wrongPlugin), new ByteArrayInputStream(wrongPlugin), () -> true);
assertFalse(invalid.success());
assertEquals("INVALID_ARTIFACT", invalid.code());
assertFalse(Files.exists(directory.resolve("update/VotingPlugin.jar")));
@@ -226,7 +224,7 @@ class PluginDeploymentServiceTest {
byte[] good = jar("name: VotingPlugin\n");
PluginDeploymentService.Task mismatch = new PluginDeploymentService.Task(UUID.randomUUID(), "vp.jar",
"0".repeat(64), good.length, UUID.randomUUID());
assertEquals("HASH_MISMATCH", PluginDeploymentServiceAccess.stage(service, mismatch, new ByteArrayInputStream(good), () -> true).code());
assertEquals("HASH_MISMATCH", service.stage(mismatch, new ByteArrayInputStream(good), () -> true).code());
}
@Test void proxyKeepsTheCurrentJarAsABackupBeforeReplacement() throws Exception {
@@ -237,8 +235,8 @@ class PluginDeploymentServiceTest {
Files.write(current, original);
PluginDeploymentService service = PluginDeploymentService.proxy(current);
assertEquals("RESTART_REQUIRED", PluginDeploymentServiceAccess.stage(service, task(first), new ByteArrayInputStream(first), () -> true).code());
assertEquals("RESTART_REQUIRED", PluginDeploymentServiceAccess.stage(service, task(second), new ByteArrayInputStream(second), () -> true).code());
assertEquals("RESTART_REQUIRED", service.stage(task(first), new ByteArrayInputStream(first), () -> true).code());
assertEquals("RESTART_REQUIRED", service.stage(task(second), new ByteArrayInputStream(second), () -> true).code());
assertArrayEquals(first, Files.readAllBytes(directory.resolve("VotingPlugin.jar.control-backup")));
assertArrayEquals(second, Files.readAllBytes(current));
}
@@ -255,11 +253,11 @@ class PluginDeploymentServiceTest {
PluginDeploymentService service = PluginDeploymentService.proxy(current);
assertEquals("SIZE_MISMATCH",
PluginDeploymentServiceAccess.stage(service, task, new ByteArrayInputStream(new byte[0]), () -> true).code());
service.stage(task, new ByteArrayInputStream(new byte[0]), () -> true).code());
assertFalse(Files.exists(marker));
assertArrayEquals(original, Files.readAllBytes(backup));
assertEquals("RESTART_REQUIRED",
PluginDeploymentServiceAccess.stage(service, task, new ByteArrayInputStream(candidate), () -> true).code());
service.stage(task, new ByteArrayInputStream(candidate), () -> true).code());
assertArrayEquals(candidate, Files.readAllBytes(current));
assertArrayEquals(candidate, Files.readAllBytes(backup));
@@ -277,10 +275,10 @@ class PluginDeploymentServiceTest {
Files.write(current, original);
PluginDeploymentService service = PluginDeploymentService.proxy(current);
PluginDeploymentService.Task task = task(candidate);
assertEquals("RESTART_REQUIRED", PluginDeploymentServiceAccess.stage(service, task, new ByteArrayInputStream(candidate), () -> true).code());
assertEquals("RESTART_REQUIRED", service.stage(task, new ByteArrayInputStream(candidate), () -> true).code());
Files.delete(backup);
assertEquals("SIZE_MISMATCH", PluginDeploymentServiceAccess.stage(service, task, new ByteArrayInputStream(new byte[0]), () -> true).code());
assertEquals("RESTART_REQUIRED", PluginDeploymentServiceAccess.stage(service, task, new ByteArrayInputStream(candidate), () -> true).code());
assertEquals("SIZE_MISMATCH", service.stage(task, new ByteArrayInputStream(new byte[0]), () -> true).code());
assertEquals("RESTART_REQUIRED", service.stage(task, new ByteArrayInputStream(candidate), () -> true).code());
assertTrue(Files.isRegularFile(backup));
}
@@ -289,7 +287,7 @@ class PluginDeploymentServiceTest {
PluginDeploymentService service = PluginDeploymentService.backend(directory.resolve("update"), Path.of("VotingPlugin.jar"));
PluginDeploymentService.Task task = task(artifact);
assertEquals("RESTART_REQUIRED", PluginDeploymentServiceAccess.stage(service, task, new ByteArrayInputStream(artifact), () -> true).code());
assertEquals("RESTART_REQUIRED", service.stage(task, new ByteArrayInputStream(artifact), () -> true).code());
String markerBefore = Files.readString(directory.resolve("update/VotingPlugin.jar.control-deployment"));
byte[] targetBefore = Files.readAllBytes(directory.resolve("update/VotingPlugin.jar"));
@@ -297,7 +295,7 @@ class PluginDeploymentServiceTest {
byte[] replacementArtifact = jar("name: VotingPlugin\nversion: replacement\n");
InputStream body = new CancellingInputStream(new ByteArrayInputStream(replacementArtifact), active);
PluginDeploymentService.Task replacement = task(replacementArtifact);
assertEquals("CANCELLED", PluginDeploymentServiceAccess.stage(service, replacement, body, active::get).code());
assertEquals("CANCELLED", service.stage(replacement, body, active::get).code());
assertEquals(markerBefore, Files.readString(directory.resolve("update/VotingPlugin.jar.control-deployment")));
assertArrayEquals(targetBefore, Files.readAllBytes(directory.resolve("update/VotingPlugin.jar")));
@@ -316,7 +314,7 @@ class PluginDeploymentServiceTest {
Files.writeString(marker.resolve("keep"), "marker publication must fail");
PluginDeploymentService service = PluginDeploymentService.backend(update, Path.of("VotingPlugin.jar"));
assertThrows(IOException.class, () -> PluginDeploymentServiceAccess.stage(service, task(candidate), new ByteArrayInputStream(candidate), () -> true));
assertThrows(IOException.class, () -> service.stage(task(candidate), new ByteArrayInputStream(candidate), () -> true));
assertArrayEquals(original, Files.readAllBytes(target));
}
@@ -331,7 +329,7 @@ class PluginDeploymentServiceTest {
Files.writeString(marker.resolve("keep"), "marker publication must fail");
PluginDeploymentService service = PluginDeploymentService.proxy(target);
assertThrows(IOException.class, () -> PluginDeploymentServiceAccess.stage(service, task(candidate), new ByteArrayInputStream(candidate), () -> true));
assertThrows(IOException.class, () -> service.stage(task(candidate), new ByteArrayInputStream(candidate), () -> true));
assertArrayEquals(original, Files.readAllBytes(target));
assertArrayEquals(original, Files.readAllBytes(directory.resolve("VotingPlugin.jar.control-backup")));
@@ -343,7 +341,7 @@ class PluginDeploymentServiceTest {
BlockingInputStream stalled = new BlockingInputStream(active);
ExecutorService executor = Executors.newSingleThreadExecutor();
try {
Future<PluginDeploymentService.Result> result = executor.submit(() -> PluginDeploymentServiceAccess.stage(service,
Future<PluginDeploymentService.Result> result = executor.submit(() -> service.stage(
task(new byte[] { 1 }), stalled, active::get));
assertTrue(stalled.awaitRead());
service.cancel();
@@ -1,4 +1,4 @@
package com.bencodez.votingplugin.tests.core;
package com.bencodez.votingplugin.core;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -1,6 +1,4 @@
package com.bencodez.votingplugin.tests.core.maintenance;
import com.bencodez.votingplugin.core.maintenance.MaintenanceConfirmation;
package com.bencodez.votingplugin.core.maintenance;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.concurrent.atomic.AtomicLong;
@@ -1,6 +1,4 @@
package com.bencodez.votingplugin.tests.core.vote;
import com.bencodez.votingplugin.core.vote.SharedVoteDelivery;
package com.bencodez.votingplugin.core.vote;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
@@ -1,7 +1,4 @@
package com.bencodez.votingplugin.tests.core.vote;
import com.bencodez.votingplugin.core.vote.SharedVotePolicy;
import com.bencodez.votingplugin.core.vote.SharedVoteProcessor;
package com.bencodez.votingplugin.core.vote;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
@@ -1,6 +1,4 @@
package com.bencodez.votingplugin.tests.events;
import com.bencodez.votingplugin.events.PlayerVoteEvent;
package com.bencodez.votingplugin.events;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -1,6 +1,4 @@
package com.bencodez.votingplugin.tests.events;
import com.bencodez.votingplugin.events.VoteShopPurchaseEvent;
package com.bencodez.votingplugin.events;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -1,6 +1,4 @@
package com.bencodez.votingplugin.tests.listeners;
import com.bencodez.votingplugin.listeners.PlayerJoinEvent;
package com.bencodez.votingplugin.listeners;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -1,6 +1,4 @@
package com.bencodez.votingplugin.tests.listeners;
import com.bencodez.votingplugin.listeners.PlayerJoinEvent;
package com.bencodez.votingplugin.listeners;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -281,7 +279,6 @@ class PlayerJoinEventReplayCompletionTest {
}).when(proxyHandler).playerOnline("Player", uuid.toString());
when(plugin.isMySQLOkay()).thenReturn(true);
when(plugin.getPlaceholderPlayerPresence()).thenReturn(presence);
presence.playerOnline(uuid, player);
when(plugin.getVotingPluginUserManager().getVotingPluginUser(uuid.toString())).thenReturn(user);
when(plugin.getBungeeSettings().isUseBungeecoord()).thenReturn(true);
when(event.getUser()).thenReturn(base);
@@ -1,4 +1,4 @@
package com.bencodez.votingplugin.tests.listeners;
package com.bencodez.votingplugin.listeners;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
@@ -1,6 +1,4 @@
package com.bencodez.votingplugin.tests.listeners;
import com.bencodez.votingplugin.listeners.PlayerVoteListener;
package com.bencodez.votingplugin.listeners;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -20,7 +18,7 @@ class PlayerVoteListenerProxyVoteIdTest {
PlayerVoteEvent event = new PlayerVoteEvent(null, "Ben", "Example", true);
event.setBungeeTextTotals(new VoteTotalsSnapshot(1, 2, 3, 4, 5, 6, 7, 8, legacyId));
assertEquals(legacyId, PlayerVoteListenerAccess.resolveProxyVoteId(event));
assertEquals(legacyId, PlayerVoteListener.resolveProxyVoteId(event));
}
@Test
@@ -31,6 +29,6 @@ class PlayerVoteListenerProxyVoteIdTest {
event.setProxyVoteId(explicitId);
event.setBungeeTextTotals(new VoteTotalsSnapshot(1, 2, 3, 4, 5, 6, 7, 8, UUID.randomUUID()));
assertEquals(explicitId, PlayerVoteListenerAccess.resolveProxyVoteId(event));
assertEquals(explicitId, PlayerVoteListener.resolveProxyVoteId(event));
}
}
Loaded 100 of 330 files, more files were not shown because too many files have changed in this diff. Show more