mirror of
https://github.com/BenCodez/VotingPlugin.git
synced 2026-11-12 20:22:04 -05:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d845237f1f | ||
|
|
e75ce256ec | ||
|
|
d1d5891b7f | ||
|
|
548c974b69 | ||
|
|
293a01f352 | ||
|
|
2abd12466e | ||
|
|
01ac6fa8f0 | ||
|
|
9b850812f7 | ||
|
|
56eac13558 | ||
|
|
8d378a0cb5 | ||
|
|
136c9ec31e | ||
|
|
558f9e1f58 | ||
|
|
4113acdea0 | ||
|
|
10ab18db8d | ||
|
|
8d5b046fe2 | ||
|
|
26ba7af075 | ||
|
|
8e9c5aa6d6 | ||
|
|
0c4914b676 | ||
|
|
67806e473b | ||
|
|
e8fa948ecd | ||
|
|
4b83cc08bd | ||
|
|
6e26c9c6c2 | ||
|
|
dd005146f3 | ||
|
|
b212f5cabb | ||
|
|
e09fa0f039 | ||
|
|
79bbdb1395 | ||
|
|
51f0b5e4a9 | ||
|
|
eb9fc8618b | ||
|
|
86735060bc | ||
|
|
f2eb2152fc | ||
|
|
d2bc2feb8e | ||
|
|
b34229ced0 | ||
|
|
9f56166708 | ||
|
|
7746fc52dc | ||
|
|
ee33a291a6 | ||
|
|
66d1c858c7 | ||
|
|
2e8cb4bd5d | ||
|
|
334a00ed77 | ||
|
|
fdcb9e6501 | ||
|
|
2a1e4e19ce | ||
|
|
73947ee4cc | ||
|
|
dc127ce300 | ||
|
|
1f27359df7 | ||
|
|
c80e460640 | ||
|
|
c3248a0a85 | ||
|
|
3db2ba2d2a | ||
|
|
bfded64b30 | ||
|
|
8c098ede6d | ||
|
|
6ff81d7919 | ||
|
|
0554c2b954 | ||
|
|
cfd4cf5cf0 | ||
|
|
84a8724ce2 | ||
|
|
032c3834f3 | ||
|
|
bc33141f43 | ||
|
|
8f637ef582 | ||
|
|
0c83e75a16 | ||
|
|
5081f95e63 | ||
|
|
36bf96559e | ||
|
|
63c3c9aecf | ||
|
|
8acf825eaa | ||
|
|
e40bf57093 | ||
|
|
04a83ad54c | ||
|
|
0c512eb8c1 | ||
|
|
de9852a974 | ||
|
|
ad0c58d945 | ||
|
|
dea8c3a8ba | ||
|
|
f79e4c5d36 | ||
|
|
ca591ed39c | ||
|
|
8d3b35fa4f | ||
|
|
d3f7c43550 | ||
|
|
cd531e323b | ||
|
|
18f2fe92b2 | ||
|
|
00617059fd | ||
|
|
ccfe5f1cf1 | ||
|
|
2b59b83123 | ||
|
|
e0c4a1c92f | ||
|
|
1fbc1a1939 | ||
|
|
c6a099fdb1 | ||
|
|
03bbdb4c93 | ||
|
|
8b1a03afa7 | ||
|
|
8048aa3995 | ||
|
|
74e5a490d8 | ||
|
|
4a2dae0e47 | ||
|
|
1ce14cc0ec | ||
|
|
e2f326de2a | ||
|
|
071ba3edec | ||
|
|
4aa8f3cd85 | ||
|
|
3b4208c595 | ||
|
|
013c9bb583 | ||
|
|
d7b5a89955 | ||
|
|
4cf01f556e | ||
|
|
11fc55cc24 | ||
|
|
4724d57e5d | ||
|
|
a9e9c282f5 | ||
|
|
9a91be8565 | ||
|
|
2dc99a0b97 | ||
|
|
c7f5b786bb | ||
|
|
306854486b | ||
|
|
07b96c4885 | ||
|
|
05b17aad11 | ||
|
|
f0cc7f15ae | ||
|
|
2236dea0ff | ||
|
|
a2d88cb2cf | ||
|
|
42398de090 | ||
|
|
0518038d91 | ||
|
|
b02228e743 | ||
|
|
1240be93e4 | ||
|
|
63179e56ff | ||
|
|
ed0b7584e4 | ||
|
|
6bae1599ff | ||
|
|
9ef8566677 | ||
|
|
aa9d49cc72 | ||
|
|
e34232319c | ||
|
|
dadbc5423f | ||
|
|
bdd8320c8d | ||
|
|
0c26a216dc | ||
|
|
cf51409f3f | ||
|
|
42f5819f1e | ||
|
|
65f1ee3fb4 | ||
|
|
ca43cd2d33 | ||
|
|
67194213f9 | ||
|
|
612f53f48d | ||
|
|
ee0110d665 | ||
|
|
6aa5acb99d | ||
|
|
1cda20842d | ||
|
|
c3d7d11310 | ||
|
|
cf8def4c8a | ||
|
|
a9b4af5fc5 | ||
|
|
a89bb5594e | ||
|
|
3b1994c899 | ||
|
|
ce7d2f747c | ||
|
|
fe9ab829ef | ||
|
|
3b69f39f90 | ||
|
|
4409f8fdd9 | ||
|
|
81993afd60 | ||
|
|
b4aa30d283 | ||
|
|
d6d6dbc81d | ||
|
|
63d9a58a57 | ||
|
|
26441c1378 | ||
|
|
87545cc41f | ||
|
|
1535e27606 | ||
|
|
897f386f81 | ||
|
|
57ebcbc72d | ||
|
|
e2f5503cfe | ||
|
|
31f5f2eeeb | ||
|
|
ff41566f4e | ||
|
|
bd3c7382e8 | ||
|
|
073634b899 | ||
|
|
1f787df070 | ||
|
|
3c29bd8674 | ||
|
|
bca38814e9 |
No files matched your search
@@ -26,6 +26,8 @@ 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:
|
||||
@@ -58,6 +60,10 @@ 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.
|
||||
@@ -324,6 +330,7 @@ Control behavior in production.
|
||||
|
||||
- Trace whether the code runs on the connector worker, proxy thread, Bukkit primary thread, or a SQL executor.
|
||||
- Preserve queued votes across saturation, reload, runtime replacement, scheduler rejection/cancellation, shutdown, and restart; overflow handling must be bounded, durable when promised, and observable rather than silently dropping work. Scheduler admission is never proof of durable ownership.
|
||||
- Local Votifier captures remain owned after STARTED until normal callback completion or confirmed overflow transfer. Transfer execution stays fenced while the original callback runs; successful non-interrupted completion reconciles only its exact occurrence, while interruption/exception or failed transfer retains bounded recovery ownership. A callback completing after the final overflow snapshot is an explicit uncertain reconciliation case; a retired queue must not overwrite a successor, and ordinary partial external effects retain the existing at-least-once boundary.
|
||||
- Proxy-to-backend guaranteed delivery is capability negotiated and at least once. Journal a reward-bearing envelope before
|
||||
reporting transport acceptance, retain it until the matching backend completion acknowledgement is durable, persist
|
||||
completed IDs before acknowledgement for restart-safe deduplication, retire receipts only through the durable
|
||||
|
||||
@@ -52,3 +52,5 @@ or disabling it; inspections gate disabled state immediately and report a newly
|
||||
```
|
||||
|
||||
`LATEST` resolves to the latest stable release.
|
||||
|
||||
Owner-defined [DateVoteMilestones](docs/date-vote-milestones.md) count qualifying accepted votes within explicit date windows, independently of normal totals. This optional feature is disabled until events are configured.
|
||||
+16
-9
@@ -271,7 +271,7 @@
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>3.5.4</version>
|
||||
<version>3.6.1</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>default-test</id>
|
||||
@@ -316,6 +316,13 @@
|
||||
<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>
|
||||
@@ -382,7 +389,7 @@
|
||||
<dependency>
|
||||
<groupId>net.neoforged</groupId>
|
||||
<artifactId>mergetool</artifactId>
|
||||
<version>2.0.0</version>
|
||||
<version>2.0.7</version>
|
||||
<classifier>api</classifier>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
@@ -401,12 +408,12 @@
|
||||
<dependency>
|
||||
<groupId>org.yaml</groupId>
|
||||
<artifactId>snakeyaml</artifactId>
|
||||
<version>2.6</version>
|
||||
<version>2.7</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.spigotmc</groupId>
|
||||
<artifactId>spigot-api</artifactId>
|
||||
<version>26.2-R0.1-SNAPSHOT</version>
|
||||
<version>26.3-R0.1-SNAPSHOT</version>
|
||||
<scope>provided</scope>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
@@ -424,7 +431,7 @@
|
||||
<dependency>
|
||||
<groupId>com.google.code.gson</groupId>
|
||||
<artifactId>gson</artifactId>
|
||||
<version>2.14.0</version>
|
||||
<version>2.15.0</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
@@ -475,7 +482,7 @@
|
||||
<dependency>
|
||||
<groupId>redis.clients</groupId>
|
||||
<artifactId>jedis</artifactId>
|
||||
<version>7.5.3</version>
|
||||
<version>8.0.2</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>me.clip</groupId>
|
||||
@@ -525,7 +532,7 @@
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-engine</artifactId>
|
||||
<version>5.12.2</version>
|
||||
<version>6.1.3</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
@@ -537,13 +544,13 @@
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-api</artifactId>
|
||||
<version>5.12.2</version>
|
||||
<version>6.1.3</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.mockito</groupId>
|
||||
<artifactId>mockito-junit-jupiter</artifactId>
|
||||
<version>5.23.0</version>
|
||||
<version>5.24.0</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
|
||||
@@ -71,11 +71,9 @@ 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;
|
||||
@@ -87,6 +85,9 @@ 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;
|
||||
@@ -174,6 +175,9 @@ public class VotingPluginMain extends AdvancedCorePlugin {
|
||||
@Getter
|
||||
private BroadcastHandler broadcastHandler;
|
||||
|
||||
@Getter
|
||||
private com.bencodez.votingplugin.streaks.VoteStreaksMenu voteStreaksMenu;
|
||||
|
||||
@Getter
|
||||
private BackendProxyHandler backendProxyHandler;
|
||||
private ProcessedVoteCache backendProcessedVoteCache;
|
||||
@@ -213,6 +217,21 @@ 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;
|
||||
|
||||
@@ -268,6 +287,7 @@ public class VotingPluginMain extends AdvancedCorePlugin {
|
||||
|
||||
@Getter
|
||||
private TopVoterState topVoterState;
|
||||
private volatile com.bencodez.votingplugin.topvoter.TopVoterDisplayFilter topVoterDisplayFilter;
|
||||
|
||||
|
||||
@Getter
|
||||
@@ -296,6 +316,8 @@ public class VotingPluginMain extends AdvancedCorePlugin {
|
||||
|
||||
@Getter
|
||||
private ScheduledExecutorService voteTimer;
|
||||
private volatile AutoCreateVoteSitesReminderService autoCreateVoteSitesSetupReminder;
|
||||
private ScheduledExecutorService autoCreateVoteSitesReminderWorker;
|
||||
|
||||
@Getter
|
||||
private UserManager votingPluginUserManager;
|
||||
@@ -317,6 +339,9 @@ 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();
|
||||
@@ -326,7 +351,13 @@ public class VotingPluginMain extends AdvancedCorePlugin {
|
||||
private VotingPluginConfigHealth configHealth;
|
||||
private VotifierIntegration votifierIntegration;
|
||||
@Getter
|
||||
private VotifierVoteOverflowQueue votifierVoteOverflowQueue;
|
||||
private volatile VotifierVoteOverflowQueue votifierVoteOverflowQueue;
|
||||
private VotiferEvent localVotifierListener;
|
||||
private boolean acceptedVoteIngressRegistered;
|
||||
private boolean timeQueueIngressRegistered;
|
||||
private volatile boolean localVotifierIngressReady;
|
||||
private volatile boolean localVotifierIngressClosed;
|
||||
private volatile long dateVoteIngressGeneration;
|
||||
private VoteLogManager voteLogManager;
|
||||
private VotingPluginWebhookManager webhookManager;
|
||||
|
||||
@@ -505,6 +536,84 @@ 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();
|
||||
}
|
||||
@@ -608,6 +717,11 @@ public class VotingPluginMain extends AdvancedCorePlugin {
|
||||
@Getter
|
||||
private VoteStreakHandler voteStreakHandler;
|
||||
|
||||
@Getter
|
||||
private final com.bencodez.votingplugin.specialrewards.datemilestones.DateVoteMilestones dateVoteMilestones =
|
||||
new com.bencodez.votingplugin.specialrewards.datemilestones.DateVoteMilestones(this);
|
||||
|
||||
|
||||
/**
|
||||
* Registers a directly editable rewards path from SpecialRewards.yml.
|
||||
*
|
||||
@@ -621,6 +735,7 @@ public class VotingPluginMain extends AdvancedCorePlugin {
|
||||
VoteSiteRewardRegistrar.register(this);
|
||||
VotePartyRewardRegistrar.register(this);
|
||||
VoteMilestoneRewardRegistrar.register(this);
|
||||
dateVoteMilestones.reload();
|
||||
VoteStreakRewardRegistrar.register(this);
|
||||
TopVoterRewardRegistrar.register(this);
|
||||
VoteShopRewardRegistrar.register(this);
|
||||
@@ -692,8 +807,37 @@ public class VotingPluginMain extends AdvancedCorePlugin {
|
||||
new VotingPluginMetrics().load(plugin);
|
||||
}
|
||||
|
||||
/** Publish accepted and transport ingress only after the complete vote pipeline is initialized. */
|
||||
void initializeDateVoteIngress(Runnable openProxy) {
|
||||
if (localVotifierIngressClosed) throw new IllegalStateException("Vote ingress is shutting down");
|
||||
if (localVotifierIngressReady) return;
|
||||
if (voteMilestonesManager == null || voteStreakHandler == null || voteParty == null || specialRewards == null
|
||||
|| topVoterHandler == null || voteShopManager == null || placeholders == null) {
|
||||
throw new IllegalStateException("Accepted-vote handlers must initialize before transport ingress");
|
||||
}
|
||||
getDateVoteMilestones().reload();
|
||||
if (!acceptedVoteIngressRegistered) {
|
||||
getServer().getPluginManager().registerEvents(new PlayerVoteListener(this), this);
|
||||
acceptedVoteIngressRegistered = true;
|
||||
}
|
||||
// Construction itself schedules persisted replay. Open it only after its consumer.
|
||||
if (!timeQueueIngressRegistered && (!getBungeeSettings().isUseBungeecoord() || !getBungeeSettings().isGloblalDataEnabled())) {
|
||||
timeQueueHandler = new TimeQueueHandler(this);
|
||||
getServer().getPluginManager().registerEvents(timeQueueHandler, this);
|
||||
timeQueueIngressRegistered = true;
|
||||
}
|
||||
if (getBungeeSettings().isUseBungeecoord()) openProxy.run();
|
||||
localVotifierIngressReady = true;
|
||||
VotifierVoteOverflowQueue overflow = votifierVoteOverflowQueue;
|
||||
if (overflow != null) overflow.start();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onPostLoad() {
|
||||
loadVoteTimer();
|
||||
checkVotifier();
|
||||
registerEarlyVotifierIngress();
|
||||
serverData.refreshVotePartyDisplay();
|
||||
ensureCommunicationSecret();
|
||||
// auto conversion for Shop.yml
|
||||
if (plugin.getShopFile().isJustCreated()) {
|
||||
@@ -721,16 +865,20 @@ 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()) {
|
||||
loadBungeeHandler();
|
||||
}
|
||||
// Proxy ingress opens below, after every accepted-vote handler is initialized.
|
||||
|
||||
if (!bungeeSettings.isUseBungeecoord() || !bungeeSettings.isGloblalDataEnabled()) {
|
||||
this.timeQueueHandler = new TimeQueueHandler(this);
|
||||
}
|
||||
|
||||
if (Bukkit.getPluginManager().getPlugin("PlaceholderAPI") != null) {
|
||||
if (getConfigFile().isLoadInteralExpansion()) {
|
||||
@@ -745,7 +893,6 @@ public class VotingPluginMain extends AdvancedCorePlugin {
|
||||
voteStreakHandler.reload();
|
||||
|
||||
registerCommands();
|
||||
checkVotifier();
|
||||
registerEvents();
|
||||
refreshPlaceholderPlayerPresence();
|
||||
|
||||
@@ -771,6 +918,7 @@ public class VotingPluginMain extends AdvancedCorePlugin {
|
||||
});
|
||||
|
||||
topVoterState = new TopVoterState();
|
||||
initializeTopVoterDisplayFilter();
|
||||
topVoterHandler = new TopVoterHandler(this);
|
||||
|
||||
new AdminGUI(this).loadHook();
|
||||
@@ -835,11 +983,7 @@ public class VotingPluginMain extends AdvancedCorePlugin {
|
||||
}
|
||||
|
||||
VotingPluginRewardRegistrar.register(this);
|
||||
// Recovered Votifier votes may now traverse the fully initialized vote,
|
||||
// reward, placeholder, shop, and vote-party pipeline.
|
||||
if (votifierVoteOverflowQueue != null) {
|
||||
votifierVoteOverflowQueue.start();
|
||||
}
|
||||
initializeDateVoteIngress(this::loadBungeeHandler);
|
||||
|
||||
plugin.getLogger().info("Enabled VotingPlugin " + plugin.getDescription().getVersion());
|
||||
if (plugin.getDescription().getVersion().contains("SNAPSHOT")) {
|
||||
@@ -1900,9 +2044,112 @@ 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;
|
||||
}
|
||||
}
|
||||
|
||||
/** Start a fresh ingress generation only after the prior consumers retired. */
|
||||
private void resetDateVoteIngressForEnable() {
|
||||
if ((localVotifierListener != null || acceptedVoteIngressRegistered || timeQueueIngressRegistered)
|
||||
&& (completedUnloadSteps == null || !completedUnloadSteps.contains("event handlers")
|
||||
|| localVotifierListener != null && !completedUnloadSteps.contains("local Votifier ingress"))) {
|
||||
throw new IllegalStateException("Previous vote ingress did not retire");
|
||||
}
|
||||
dateVoteIngressGeneration++;
|
||||
localVotifierIngressReady = false;
|
||||
localVotifierIngressClosed = false;
|
||||
acceptedVoteIngressRegistered = false;
|
||||
timeQueueIngressRegistered = false;
|
||||
localVotifierListener = null;
|
||||
timeQueueHandler = null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onPreLoad() {
|
||||
resetDateVoteIngressForEnable();
|
||||
plugin = this;
|
||||
unloadInProgress.set(false);
|
||||
completedUnloadSteps = new java.util.HashSet<>();
|
||||
signShutdownPublication = null;
|
||||
|
||||
setupFiles();
|
||||
if ("SQLITE".equalsIgnoreCase(configFile.getData().getString("DataStorage", "SQLITE"))) {
|
||||
@@ -1944,11 +2191,83 @@ public class VotingPluginMain extends AdvancedCorePlugin {
|
||||
|
||||
@Override
|
||||
public void onDisable() {
|
||||
if (offlineVoteOwnerHandoffs != null) offlineVoteOwnerHandoffs.close();
|
||||
// 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);
|
||||
}
|
||||
});
|
||||
try {
|
||||
shutdownVoteReminders();
|
||||
runShutdownStep("offline vote handoffs", () -> {
|
||||
if (offlineVoteOwnerHandoffs != null) offlineVoteOwnerHandoffs.close();
|
||||
});
|
||||
} finally {
|
||||
super.onDisable();
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1961,48 +2280,112 @@ public class VotingPluginMain extends AdvancedCorePlugin {
|
||||
|
||||
@Override
|
||||
public void onUnLoad() {
|
||||
placeholderPlayerPresence.clear();
|
||||
stopBackendHostedControlLifecycle();
|
||||
stopBackendControlConnectorLifecycle();
|
||||
if (getBackendProxyHandler() != null) {
|
||||
try {
|
||||
getBackendProxyHandler().closeForShutdown();
|
||||
} catch (Exception e) {
|
||||
debug(e);
|
||||
}
|
||||
runShutdownStep("server-data process drain", this::beginServerDataProcessDrain);
|
||||
if (!unloadInProgress.compareAndSet(false, true)) {
|
||||
runShutdownStep("time queue retry", () -> {
|
||||
if (timeQueueHandler != null) timeQueueHandler.saveForShutdown();
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (backendOrderedVoteOverflowQueue != null) {
|
||||
backendOrderedVoteOverflowQueue.close();
|
||||
backendOrderedVoteOverflowQueue = null;
|
||||
}
|
||||
if (webhookManager != null) {
|
||||
webhookManager.shutdown();
|
||||
}
|
||||
voteTimer.shutdown();
|
||||
try {
|
||||
voteTimer.awaitTermination(1, TimeUnit.SECONDS);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
voteTimer.shutdownNow();
|
||||
if (votifierVoteOverflowQueue != null) {
|
||||
votifierVoteOverflowQueue.close();
|
||||
votifierVoteOverflowQueue = null;
|
||||
}
|
||||
if (timeQueueHandler != null) {
|
||||
timeQueueHandler.save();
|
||||
}
|
||||
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("local Votifier ingress", () -> {
|
||||
localVotifierIngressClosed = true;
|
||||
localVotifierIngressReady = false;
|
||||
if (localVotifierListener != null) localVotifierListener.stop();
|
||||
});
|
||||
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); }
|
||||
}
|
||||
|
||||
shutdownVoteReminders();
|
||||
private void beginServerDataProcessDrain() {
|
||||
var owner = serverDataPublicationFence;
|
||||
if (owner != null) owner.beginShutdown(System.nanoTime());
|
||||
}
|
||||
|
||||
if (coolDownCheck != null) {
|
||||
coolDownCheck.shutdown();
|
||||
coolDownCheck = null;
|
||||
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) {
|
||||
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.
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
getSigns().storeSigns();
|
||||
HandlerList.unregisterAll(plugin);
|
||||
plugin = null;
|
||||
private void shutdownVoteTimer() {
|
||||
if (voteTimer == null) return;
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -2013,12 +2396,6 @@ 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());
|
||||
@@ -2037,23 +2414,44 @@ public class VotingPluginMain extends AdvancedCorePlugin {
|
||||
}
|
||||
}
|
||||
|
||||
// Export documentation only after both handler lists and the player command label are ready.
|
||||
// A filesystem problem must never stop registration or normal voting.
|
||||
try {
|
||||
if (com.bencodez.votingplugin.commands.CommandDocumentationExporter.write(getDataFolder().toPath(),
|
||||
getVoteCommandPrefix(), getVoteCommand(), getAdminVoteCommand())) {
|
||||
getLogger().info("Updated generated command documentation in GeneratedDocs/");
|
||||
}
|
||||
} catch (IOException | RuntimeException error) {
|
||||
getLogger().warning("Unable to write generated command documentation: " + error.getMessage());
|
||||
}
|
||||
|
||||
plugin.debug("Loaded Commands");
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Register events.
|
||||
*/
|
||||
/** Capture external events early; only the existing bounded workers may buffer/process them. */
|
||||
void registerEarlyVotifierIngress() {
|
||||
if (localVotifierIngressClosed || !isVotifierLoaded() || localVotifierListener != null) return;
|
||||
long generation = dateVoteIngressGeneration;
|
||||
java.util.function.BooleanSupplier ready = () -> dateVoteIngressGeneration == generation
|
||||
&& localVotifierIngressReady && !localVotifierIngressClosed;
|
||||
VotiferEvent listener = new VotiferEvent(this, ready);
|
||||
// Publish the memory owner before capture. Its independent worker loads
|
||||
// disk state; vote-executor cancellation cannot discard queue setup.
|
||||
votifierVoteOverflowQueue = VotifierVoteOverflowQueue.initializeConfirmedAsync(this,
|
||||
listener::processVoteConfirmed, ready);
|
||||
localVotifierListener = listener;
|
||||
if (localVotifierIngressReady) votifierVoteOverflowQueue.start();
|
||||
getServer().getPluginManager().registerEvents(listener, this);
|
||||
}
|
||||
|
||||
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);
|
||||
if (isVotifierLoaded()) {
|
||||
VotiferEvent votifierEvent = new VotiferEvent(this);
|
||||
votifierVoteOverflowQueue = new VotifierVoteOverflowQueue(this, votifierEvent::processVote);
|
||||
pm.registerEvents(votifierEvent, this);
|
||||
}
|
||||
pm.registerEvents(new PlayerVoteListener(this), this);
|
||||
pm.registerEvents(new com.bencodez.votingplugin.listeners.DateVoteMenuOpenGuard(), this);
|
||||
pm.registerEvents(new PlayerPostVoteLoggerListener(this), this);
|
||||
pm.registerEvents(new PlayerSpecialRewardLoggerListener(this), this);
|
||||
pm.registerEvents(new VoteShopPurchaseLoggerListener(this), this);
|
||||
@@ -2067,9 +2465,6 @@ public class VotingPluginMain extends AdvancedCorePlugin {
|
||||
pm.registerEvents(new PlayerInteract(this), this);
|
||||
}
|
||||
|
||||
if (timeQueueHandler != null) {
|
||||
pm.registerEvents(timeQueueHandler, plugin);
|
||||
}
|
||||
|
||||
pm.registerEvents(new VotingPluginUpdateEvent(this), this);
|
||||
/*
|
||||
@@ -2100,15 +2495,19 @@ public class VotingPluginMain extends AdvancedCorePlugin {
|
||||
/** Captures Bukkit presence while the lifecycle caller owns platform access. */
|
||||
public void refreshPlaceholderPlayerPresence() {
|
||||
boolean onlineMode = getOptions().isOnlineMode();
|
||||
placeholderPlayerPresence.replace(Bukkit::getOnlinePlayers,
|
||||
player -> placeholderStorageUuid(player, onlineMode));
|
||||
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);
|
||||
}, () -> { }, () -> { }));
|
||||
}
|
||||
|
||||
static UUID placeholderStorageUuid(Player player, boolean onlineMode) {
|
||||
if (onlineMode) return player.getUniqueId();
|
||||
String cachedUuid = UuidLookup.getInstance().getCachedUUID(player.getName());
|
||||
String resolvedUuid = UuidLookup.getInstance().getUUIDWithoutStorage(player.getName());
|
||||
try {
|
||||
return UUID.fromString(cachedUuid);
|
||||
return UUID.fromString(resolvedUuid);
|
||||
} catch (IllegalArgumentException | NullPointerException ignored) {
|
||||
return player.getUniqueId();
|
||||
}
|
||||
@@ -2124,9 +2523,13 @@ 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();
|
||||
|
||||
@@ -2141,10 +2544,13 @@ 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();
|
||||
|
||||
getOptions().setServer(bungeeSettings.getServer());
|
||||
getDateVoteMilestones().reload();
|
||||
reloadBackendProxyRuntime(updateActiveBackendRuntime, userStorage);
|
||||
checkYMLError();
|
||||
|
||||
@@ -2176,6 +2582,7 @@ public class VotingPluginMain extends AdvancedCorePlugin {
|
||||
|
||||
setUpdate(true);
|
||||
} finally {
|
||||
if (voteStreaksMenu != null) voteStreaksMenu.resume();
|
||||
if (offlineVoteOwnerHandoffs != null) offlineVoteOwnerHandoffs.resume();
|
||||
}
|
||||
}
|
||||
|
||||
+40
-9
@@ -569,7 +569,8 @@ public class BackendProxyMessageRouter {
|
||||
}
|
||||
|
||||
String totalsRaw = nvl(fields.get(VotingPluginWire.K_TOTALS));
|
||||
VoteTotalsSnapshot totals = totalsRaw.isEmpty() ? null : VoteTotalsSnapshot.parseStorage(totalsRaw);
|
||||
VoteTotalsSnapshot totals = !com.bencodez.votingplugin.proxy.VoteOccurrenceMetadata.hasPayload(totalsRaw)
|
||||
? null : VoteTotalsSnapshot.parseStorage(totalsRaw);
|
||||
VoteSite voteSite = plugin.getVoteSiteManager()
|
||||
.getVoteSite(plugin.getVoteSiteManager().getVoteSiteName(true, service), true);
|
||||
if (voteSite == null) {
|
||||
@@ -595,7 +596,7 @@ public class BackendProxyMessageRouter {
|
||||
boolean online = fields.containsKey(VotingPluginWire.K_WAS_ONLINE)
|
||||
? Boolean.parseBoolean(fields.get(VotingPluginWire.K_WAS_ONLINE)) : user.isOnline();
|
||||
plugin.getBroadcastHandler().broadcastVote(user.getJavaUUID(), user.getPlayerName(),
|
||||
voteSite.getDisplayNameForFormatting(), online, totals);
|
||||
voteSite.getDisplayName(), online, totals);
|
||||
}
|
||||
|
||||
private WireVoteResult handleWireVoteDelayRejected(JsonEnvelope msg) {
|
||||
@@ -612,6 +613,21 @@ public class BackendProxyMessageRouter {
|
||||
if (rejected.uuid.isEmpty() || rejected.service.isEmpty()) {
|
||||
return new WireVoteResult(rejected.voteId, true);
|
||||
}
|
||||
VoteSite legacySite = null;
|
||||
if (!ServiceSiteValidator.isValid(rejected.service)
|
||||
&& ServiceSiteValidator.isValidConfiguredLegacyIdentifier(rejected.service)) {
|
||||
for (VoteSite site : plugin.getVoteSiteManager().getVoteSites().toArray(new VoteSite[0])) {
|
||||
if (site.isEnabled() && rejected.service.equalsIgnoreCase(site.getServiceSite())) {
|
||||
legacySite = site;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
boolean configuredLegacy = legacySite != null;
|
||||
if (!ServiceSiteValidator.isValid(rejected.service) && !configuredLegacy) {
|
||||
plugin.getLogger().warning("Rejected VoteDelayRejected with invalid service site");
|
||||
return new WireVoteResult(rejected.voteId, true);
|
||||
}
|
||||
UUID javaUuid;
|
||||
try {
|
||||
javaUuid = UUID.fromString(rejected.uuid);
|
||||
@@ -620,8 +636,10 @@ public class BackendProxyMessageRouter {
|
||||
+ ServiceSiteValidator.sanitizeForLog(rejected.uuid));
|
||||
return new WireVoteResult(rejected.voteId, true);
|
||||
}
|
||||
VoteSite voteSite = plugin.getVoteSiteManager()
|
||||
.getVoteSite(plugin.getVoteSiteManager().getVoteSiteName(true, rejected.service), true);
|
||||
VoteSite voteSite = configuredLegacy
|
||||
? legacySite
|
||||
: plugin.getVoteSiteManager()
|
||||
.getVoteSite(plugin.getVoteSiteManager().getVoteSiteName(true, rejected.service), true);
|
||||
if (voteSite == null) {
|
||||
plugin.getLogger().warning("No voting site with the service site: '"
|
||||
+ ServiceSiteValidator.sanitizeForLog(rejected.service) + "'");
|
||||
@@ -698,16 +716,29 @@ public class BackendProxyMessageRouter {
|
||||
user.cache();
|
||||
boolean wasOnline = vote.wasOnlineKnown ? vote.wasOnline : user.isOnline();
|
||||
boolean queuedDelivery = vote.queuedDeliveryKnown ? vote.queuedDelivery : vote.delayValidated;
|
||||
user.bungeeVotePluginMessaging(vote.service, vote.time, totals, !vote.manageTotals,
|
||||
wasOnline, vote.broadcast, vote.num, queuedDelivery, vote.delayValidationKnown,
|
||||
vote.queuedDeliveryKnown, voteId,
|
||||
VotingPluginWire.SUB_VOTE_ONLINE.equals(msg.getSubChannel()));
|
||||
if (plugin.getBungeeSettings().isPerServerPoints()) {
|
||||
com.bencodez.votingplugin.events.PlayerVoteEvent dispatchedEvent = null;
|
||||
VotingPluginUser.DateMilestoneAccountingException dateAccountingFailure = null;
|
||||
try {
|
||||
// Keep totals correlation for replay fencing, but only the original wire ID
|
||||
// identifies a canonical transport occurrence in the native event.
|
||||
dispatchedEvent = user.bungeeVotePluginMessagingEvent(vote.service, vote.time, totals, !vote.manageTotals,
|
||||
wasOnline, vote.broadcast, vote.num, queuedDelivery, vote.delayValidationKnown,
|
||||
vote.queuedDeliveryKnown, vote.voteId,
|
||||
VotingPluginWire.SUB_VOTE_ONLINE.equals(msg.getSubChannel()), vote.realVote,
|
||||
vote.canonicalOccurrenceTime);
|
||||
} catch (VotingPluginUser.DateMilestoneAccountingException incomplete) {
|
||||
dateAccountingFailure = incomplete;
|
||||
}
|
||||
if ((dispatchedEvent == null || !dispatchedEvent.isCancelled())
|
||||
&& plugin.getBungeeSettings().isPerServerPoints()) {
|
||||
user.addPoints(plugin.getConfigFile().getPointsOnVote());
|
||||
}
|
||||
if (vote.service != null && !vote.service.isEmpty()) {
|
||||
plugin.getServerData().addServiceSite(vote.service);
|
||||
}
|
||||
// Date accounting cannot suppress normal points/service observations. Keep
|
||||
// the reservation incomplete so reconciliation cannot replay normal rewards.
|
||||
if (dateAccountingFailure != null) throw dateAccountingFailure;
|
||||
return new WireVoteResult(voteId, true, false);
|
||||
}
|
||||
|
||||
|
||||
+207
@@ -0,0 +1,207 @@
|
||||
package com.bencodez.votingplugin.commands;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.AtomicMoveNotSupportedException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import com.bencodez.advancedcore.api.command.CommandHandler;
|
||||
import com.bencodez.advancedcore.api.command.PlayerCommandHandler;
|
||||
import com.google.gson.GsonBuilder;
|
||||
import com.google.gson.JsonArray;
|
||||
import com.google.gson.JsonObject;
|
||||
|
||||
/**
|
||||
* Exports the actual Bukkit command-handler registrations as a deterministic
|
||||
* machine-readable manifest and an administrator-friendly Markdown reference.
|
||||
* It never executes a command or accesses user data.
|
||||
*/
|
||||
public final class CommandDocumentationExporter {
|
||||
public static final String DIRECTORY = "GeneratedDocs";
|
||||
public static final String JSON_NAME = "commands.json";
|
||||
public static final String MARKDOWN_NAME = "commands.md";
|
||||
|
||||
private CommandDocumentationExporter() {
|
||||
}
|
||||
|
||||
public static final class CommandRow {
|
||||
private final String root;
|
||||
private final String syntax;
|
||||
private final String description;
|
||||
private final String permissionExpression;
|
||||
private final List<String> permissions;
|
||||
private final List<String> allTargetPermissions;
|
||||
private final boolean multiplePermissionChecks;
|
||||
private final String sender;
|
||||
|
||||
private CommandRow(String root, String syntax, String description, String permissionExpression,
|
||||
List<String> permissions, List<String> allTargetPermissions,
|
||||
boolean multiplePermissionChecks, String sender) {
|
||||
this.root = root;
|
||||
this.syntax = syntax;
|
||||
this.description = description;
|
||||
this.permissionExpression = permissionExpression;
|
||||
this.permissions = List.copyOf(permissions);
|
||||
this.allTargetPermissions = List.copyOf(allTargetPermissions);
|
||||
this.multiplePermissionChecks = multiplePermissionChecks;
|
||||
this.sender = sender;
|
||||
}
|
||||
}
|
||||
|
||||
/** Capture only loaded handlers, including conditionally registered handlers. */
|
||||
public static List<CommandRow> capture(String playerRoot, List<? extends CommandHandler> playerHandlers,
|
||||
List<? extends CommandHandler> adminHandlers) {
|
||||
List<CommandRow> result = new ArrayList<>();
|
||||
result.addAll(captureGroup(playerRoot, playerHandlers));
|
||||
result.addAll(captureGroup("/av", adminHandlers));
|
||||
return List.copyOf(result);
|
||||
}
|
||||
|
||||
private static List<CommandRow> captureGroup(String root, List<? extends CommandHandler> handlers) {
|
||||
List<CommandRow> result = new ArrayList<>();
|
||||
if (handlers == null) return result;
|
||||
for (CommandHandler handler : handlers) {
|
||||
if (handler == null) continue;
|
||||
String syntax = safe(handler.getHelpLineCommand(root));
|
||||
if (syntax.isEmpty()) continue;
|
||||
String permission = safe(handler.getPerm());
|
||||
List<String> allTarget = List.of();
|
||||
if (handler instanceof PlayerCommandHandler) {
|
||||
List<String> additional = ((PlayerCommandHandler) handler).getAdditionalPermissions();
|
||||
if (additional != null) allTarget = new ArrayList<>(new LinkedHashSet<>(additional));
|
||||
}
|
||||
String sender = handler.isForceConsole() ? "console" :
|
||||
handler.isAllowConsole() ? "player or console" : "player";
|
||||
result.add(new CommandRow(root, syntax, safe(handler.getHelpMessage()), permission,
|
||||
splitPermissions(permission), allTarget, handler.isAllowMultiplePermissions(), sender));
|
||||
}
|
||||
result.sort(Comparator.comparing((CommandRow row) -> row.syntax, String.CASE_INSENSITIVE_ORDER)
|
||||
.thenComparing(row -> row.permissionExpression, String.CASE_INSENSITIVE_ORDER));
|
||||
return result;
|
||||
}
|
||||
|
||||
private static String safe(String text) {
|
||||
return text == null ? "" : text.trim();
|
||||
}
|
||||
|
||||
private static List<String> splitPermissions(String expression) {
|
||||
Set<String> unique = new LinkedHashSet<>();
|
||||
for (String part : expression.split("\\|")) {
|
||||
String value = part.trim();
|
||||
if (!value.isEmpty()) unique.add(value);
|
||||
}
|
||||
return new ArrayList<>(unique);
|
||||
}
|
||||
|
||||
/** Stable JSON for future documentation bots; it contains no credentials or player data. */
|
||||
public static String toJson(List<CommandRow> rows) {
|
||||
JsonObject doc = new JsonObject();
|
||||
doc.addProperty("schemaVersion", 1);
|
||||
doc.addProperty("scope", "VotingPlugin Bukkit registered handlers");
|
||||
JsonArray commands = new JsonArray();
|
||||
for (CommandRow row : rows) {
|
||||
JsonObject object = new JsonObject();
|
||||
object.addProperty("root", row.root);
|
||||
object.addProperty("syntax", row.syntax);
|
||||
object.addProperty("description", row.description);
|
||||
object.addProperty("permissionExpression", row.permissionExpression);
|
||||
object.add("permissions", asArray(row.permissions));
|
||||
object.add("allTargetPermissions", asArray(row.allTargetPermissions));
|
||||
object.addProperty("multiplePermissionChecks", row.multiplePermissionChecks);
|
||||
object.addProperty("sender", row.sender);
|
||||
commands.add(object);
|
||||
}
|
||||
doc.add("commands", commands);
|
||||
return new GsonBuilder().disableHtmlEscaping().setPrettyPrinting().create().toJson(doc) + "\n";
|
||||
}
|
||||
|
||||
private static JsonArray asArray(List<String> values) {
|
||||
JsonArray array = new JsonArray();
|
||||
for (String value : values) array.add(value);
|
||||
return array;
|
||||
}
|
||||
|
||||
/** Reader-friendly generated snapshot for reviewing changes without running code. */
|
||||
public static String toMarkdown(List<CommandRow> rows) {
|
||||
StringBuilder markdown = new StringBuilder();
|
||||
markdown.append("# VotingPlugin Bukkit commands (generated)\n\n");
|
||||
markdown.append("This page is generated from the command handlers loaded by the running server. ");
|
||||
markdown.append("It is not a canonical release reference: configured command labels and ");
|
||||
markdown.append("conditionally loaded commands may differ between servers.\n\n");
|
||||
markdown.append("Permission expressions separated by | may provide alternatives when ");
|
||||
markdown.append("multiple-permission checks are enabled. Extra all-target permissions ");
|
||||
markdown.append("apply only to supported bulk player commands.\n\n");
|
||||
markdown.append("This export does not cover separate Velocity/BungeeCord proxy commands ");
|
||||
markdown.append("or standalone plugin.yml convenience aliases.\n\n");
|
||||
|
||||
Map<String, List<CommandRow>> groups = new LinkedHashMap<>();
|
||||
for (CommandRow row : rows) groups.computeIfAbsent(row.root, key -> new ArrayList<>()).add(row);
|
||||
for (Map.Entry<String, List<CommandRow>> group : groups.entrySet()) {
|
||||
markdown.append("## ").append(escapeCell(group.getKey())).append("\n\n");
|
||||
markdown.append("| Command | Description | Permission expression | All-target permissions | Sender |\n");
|
||||
markdown.append("|---|---|---|---|---|\n");
|
||||
for (CommandRow row : group.getValue()) {
|
||||
markdown.append("| ").append(code(row.syntax));
|
||||
markdown.append(" | ").append(escapeCell(row.description));
|
||||
markdown.append(" | ").append(code(row.permissionExpression.isEmpty() ? "(none)" : row.permissionExpression));
|
||||
markdown.append(" | ").append(row.allTargetPermissions.isEmpty() ? "—" :
|
||||
code(String.join(", ", row.allTargetPermissions)));
|
||||
markdown.append(" | ").append(escapeCell(row.sender)).append(" |\n");
|
||||
}
|
||||
markdown.append("\n");
|
||||
}
|
||||
return markdown.toString();
|
||||
}
|
||||
|
||||
private static String code(String value) {
|
||||
return String.valueOf((char) 96) + escapeCell(value) + (char) 96;
|
||||
}
|
||||
|
||||
private static String escapeCell(String value) {
|
||||
return safe(value).replace("\r", " ").replace("\n", " ").replace("|", "\\|")
|
||||
.replace(String.valueOf((char) 96), "`");
|
||||
}
|
||||
|
||||
/**
|
||||
* Write only when content changes, using temporary files and atomic moves
|
||||
* when supported. No writes occur outside the plugin data folder.
|
||||
*/
|
||||
public static boolean write(Path pluginDataFolder, String playerRoot,
|
||||
List<? extends CommandHandler> playerHandlers, List<? extends CommandHandler> adminHandlers)
|
||||
throws IOException {
|
||||
List<CommandRow> rows = capture(playerRoot, playerHandlers, adminHandlers);
|
||||
Path directory = pluginDataFolder.resolve(DIRECTORY);
|
||||
Files.createDirectories(directory);
|
||||
boolean jsonChanged = writeIfChanged(directory.resolve(JSON_NAME), toJson(rows));
|
||||
boolean markdownChanged = writeIfChanged(directory.resolve(MARKDOWN_NAME), toMarkdown(rows));
|
||||
return jsonChanged || markdownChanged;
|
||||
}
|
||||
|
||||
private static boolean writeIfChanged(Path target, String content) throws IOException {
|
||||
if (Files.isSymbolicLink(target)) throw new IOException("Refusing to overwrite symbolic link: " + target);
|
||||
if (Files.isRegularFile(target) && content.equals(Files.readString(target, StandardCharsets.UTF_8))) {
|
||||
return false;
|
||||
}
|
||||
Path temporary = Files.createTempFile(target.getParent(), target.getFileName().toString(), ".tmp");
|
||||
try {
|
||||
Files.writeString(temporary, content, StandardCharsets.UTF_8);
|
||||
try {
|
||||
Files.move(temporary, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
|
||||
} catch (AtomicMoveNotSupportedException unsupported) {
|
||||
Files.move(temporary, target, StandardCopyOption.REPLACE_EXISTING);
|
||||
}
|
||||
} finally {
|
||||
Files.deleteIfExists(temporary);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -56,6 +56,7 @@ 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;
|
||||
@@ -82,6 +83,7 @@ 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;
|
||||
@@ -115,6 +117,13 @@ 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.
|
||||
@@ -123,6 +132,131 @@ 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) {
|
||||
@@ -220,7 +354,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)));
|
||||
users.add(plugin.getVotingPluginUserManager().getVotingPluginUser(UUID.fromString(uuidString), true));
|
||||
}
|
||||
} catch (Throwable failure) {
|
||||
plugin.debug(failure);
|
||||
@@ -403,26 +537,28 @@ 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());
|
||||
}
|
||||
|
||||
if (commands.containsKey(cmd)) {
|
||||
return commands.get(cmd).hasPerm(player);
|
||||
for (var entry : commands.entrySet()) {
|
||||
if (entry.getKey().equalsIgnoreCase(cmd)) return entry.getValue().hasPerm(player);
|
||||
}
|
||||
|
||||
boolean adminCommand = false;
|
||||
String rootLabel = voteCommandName.substring(voteCommandName.indexOf(':') + 1);
|
||||
|
||||
if (cmd.startsWith("vote")) {
|
||||
cmd = cmd.substring("vote".length());
|
||||
} else if (cmd.startsWith("v")) {
|
||||
cmd = cmd.substring(1);
|
||||
} else if (cmd.startsWith("av")) {
|
||||
if (cmd.equals("adminvote") || cmd.startsWith("adminvote ")) {
|
||||
adminCommand = true;
|
||||
cmd = cmd.substring("av".length());
|
||||
} else if (cmd.startsWith("adminvote")) {
|
||||
cmd = cmd.substring("adminvote".length()).trim();
|
||||
} else if (cmd.equals("av") || cmd.startsWith("av ")) {
|
||||
adminCommand = true;
|
||||
cmd = cmd.substring("adminvote".length());
|
||||
cmd = cmd.substring("av".length()).trim();
|
||||
} else if (voteCommandEnabled && (cmd.equals(rootLabel) || cmd.startsWith(rootLabel + " "))) {
|
||||
cmd = cmd.substring(rootLabel.length()).trim();
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
// plugin.debug(cmd);
|
||||
if (!adminCommand) {
|
||||
@@ -459,13 +595,11 @@ public class CommandLoader {
|
||||
* @return true if it's a VotingPlugin command
|
||||
*/
|
||||
public boolean isVotingPluginCommand(Player player, String cmd) {
|
||||
if (plugin.getCommand(cmd) != null || cmd.startsWith("votingplugin")) {
|
||||
return true;
|
||||
}
|
||||
for (String str : commands.keySet()) {
|
||||
if (str.equalsIgnoreCase(cmd)) {
|
||||
return true;
|
||||
}
|
||||
try {
|
||||
org.bukkit.command.Command command = getCommandMap().getCommand(cmd);
|
||||
return command instanceof PluginCommand owned && owned.getPlugin() == plugin;
|
||||
} catch (ReflectiveOperationException failure) {
|
||||
plugin.debug(failure);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -473,8 +607,31 @@ 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<>());
|
||||
DateVoteMilestoneCommands.register(plugin, adminPerm);
|
||||
|
||||
plugin.getAdminVoteCommand().add(new CommandHandler(plugin, new String[] { "CurrentPluginTime" },
|
||||
"VotingPlugin.Commands.AdminVote.CurrentPluginTime|" + adminPerm, "Current plugin time") {
|
||||
@@ -709,7 +866,7 @@ public class CommandLoader {
|
||||
@Override
|
||||
public void executeSinglePlayer(CommandSender sender, String[] args) {
|
||||
VotingPluginUser user = plugin.getVotingPluginUserManager().getVotingPluginUser(args[1]);
|
||||
user.cache();
|
||||
if (!UserStorage.MYSQL.equals(plugin.getStorageType())) user.cache();
|
||||
user.removePoints(Integer.parseInt(args[3]), removed -> {
|
||||
if (!removed) {
|
||||
runForCommandSender(sender, () -> sender.sendMessage(MessageAPI.colorize(
|
||||
@@ -2813,9 +2970,7 @@ public class CommandLoader {
|
||||
public void execute(CommandSender sender, String[] args) {
|
||||
String topVoter = args[1];
|
||||
TopVoter top = TopVoter.getTopVoter(topVoter);
|
||||
plugin.getServerData().setTopVoterMessageId(top, 0);
|
||||
plugin.getDiscordHandler().getTopVoterMessageIds().put(top, 0L);
|
||||
sendMessage(sender, "&cCleared discord message ID for " + top.toString());
|
||||
clearDiscordMessageId(sender, top);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -2969,9 +3124,10 @@ public class CommandLoader {
|
||||
public void loadAliases() {
|
||||
commands = new HashMap<>();
|
||||
aliasCommandNames.clear();
|
||||
configurePlayerCommand();
|
||||
|
||||
// Bukkit registers plugin.yml commands before this loader runs.
|
||||
if (!plugin.getConfigFile().isLoadCommandAliases()) {
|
||||
if (!startupLoadCommandAliases) {
|
||||
unregisterOptionalPluginYMLCommands();
|
||||
} else {
|
||||
unregisterDisabledPluginYMLCommands();
|
||||
@@ -2979,7 +3135,7 @@ public class CommandLoader {
|
||||
|
||||
// If false: still wire permissions, but don't wire alias executors/tab
|
||||
// completers.
|
||||
final boolean enableAliases = plugin.getConfigFile().isLoadCommandAliases();
|
||||
final boolean enableAliases = startupLoadCommandAliases;
|
||||
|
||||
// ---------------------------
|
||||
// /vote aliases
|
||||
@@ -3011,16 +3167,18 @@ public class CommandLoader {
|
||||
}
|
||||
registerAdditionalPermissions(Bukkit.getPluginManager(), cmdHandle);
|
||||
|
||||
if (argLength > 0) {
|
||||
if (argLength > 0 && voteCommandEnabled) {
|
||||
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 = plugin.getCommand(commandName);
|
||||
PluginCommand command = ownedCommand(commandName);
|
||||
if (command == null) {
|
||||
plugin.devDebug("Command " + commandName + " not found in plugin.yml");
|
||||
continue;
|
||||
@@ -3094,11 +3252,13 @@ 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 = plugin.getCommand(commandName);
|
||||
PluginCommand command = ownedCommand(commandName);
|
||||
if (command == null) {
|
||||
plugin.devDebug("Command " + commandName + " not found in plugin.yml");
|
||||
continue;
|
||||
@@ -3164,8 +3324,8 @@ public class CommandLoader {
|
||||
|| commandName.equalsIgnoreCase("av")) {
|
||||
continue;
|
||||
}
|
||||
PluginCommand command = plugin.getCommand(commandName);
|
||||
if (command != null) {
|
||||
PluginCommand command = ownedCommand(commandName);
|
||||
if (command != null && command != playerRootCommand) {
|
||||
unregisterCommand(commandMap, command);
|
||||
}
|
||||
}
|
||||
@@ -3179,8 +3339,8 @@ public class CommandLoader {
|
||||
try {
|
||||
CommandMap commandMap = getCommandMap();
|
||||
for (String commandName : disabledAliasCommandNames) {
|
||||
PluginCommand command = plugin.getCommand(commandName);
|
||||
if (command != null) {
|
||||
PluginCommand command = ownedCommand(commandName);
|
||||
if (command != null && command != playerRootCommand) {
|
||||
unregisterCommand(commandMap, command);
|
||||
}
|
||||
}
|
||||
@@ -3192,22 +3352,7 @@ 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);
|
||||
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);
|
||||
Map<String, org.bukkit.command.Command> knownCommands = getKnownCommands(commandMap);
|
||||
Set<String> removedLabels = new HashSet<>();
|
||||
for (Map.Entry<String, org.bukkit.command.Command> entry : knownCommands.entrySet()) {
|
||||
if (entry.getValue() == command) {
|
||||
@@ -3236,6 +3381,27 @@ 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");
|
||||
@@ -3486,7 +3652,15 @@ public class CommandLoader {
|
||||
*/
|
||||
private void loadVoteCommand() {
|
||||
plugin.setVoteCommand(new ArrayList<>());
|
||||
plugin.getVoteCommand().add(new CommandHandler(plugin, new String[] { "Help&?" },
|
||||
plugin.getVoteCommand().add(new CommandHandler(plugin, new String[] { "DateEvents" },
|
||||
"VotingPlugin.Commands.Vote.DateEvents|" + playerPerm, "View date-window vote milestone progress") {
|
||||
@Override public void execute(CommandSender sender, String[] args) {
|
||||
if (sender instanceof Player player) plugin.getDateVoteMilestones().progress(player);
|
||||
else sender.sendMessage("Run /vote dateevents as a player.");
|
||||
}
|
||||
});
|
||||
|
||||
plugin.getVoteCommand().add(new CommandHandler(plugin, new String[] { "Help&?" },
|
||||
"VotingPlugin.Commands.Vote.Help|" + playerPerm, "View help page") {
|
||||
|
||||
@Override
|
||||
@@ -4069,6 +4243,9 @@ 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) {
|
||||
@@ -4135,7 +4312,7 @@ public class CommandLoader {
|
||||
} else if (MessageAPI.startsWithIgnoreCase(slot, "today")) {
|
||||
new VoteToday(plugin, player, user, 1).open();
|
||||
} else if (MessageAPI.startsWithIgnoreCase(slot, "help")) {
|
||||
player.performCommand("vote help");
|
||||
performVoteCommand(player, "help");
|
||||
} else if (MessageAPI.startsWithIgnoreCase(slot, "shop")) {
|
||||
new VoteShop(plugin, player, user).open();
|
||||
} else if (MessageAPI.startsWithIgnoreCase(slot, "lastmonth")) {
|
||||
@@ -4144,6 +4321,8 @@ 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);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
package com.bencodez.votingplugin.commands;
|
||||
|
||||
import com.bencodez.advancedcore.api.command.CommandHandler;
|
||||
import com.bencodez.simpleapi.command.TabCompleteHandler;
|
||||
import com.bencodez.votingplugin.VotingPluginMain;
|
||||
import com.bencodez.votingplugin.specialrewards.datemilestones.DateVoteMilestones.AdminAction;
|
||||
import org.bukkit.command.CommandSender;
|
||||
|
||||
/** Exact-target administration; storage and confirmed completion belong to the manager. */
|
||||
final class DateVoteMilestoneCommands {
|
||||
private DateVoteMilestoneCommands() { }
|
||||
|
||||
static void register(VotingPluginMain plugin, String adminPermission) {
|
||||
// The SDK only matches registered variable tokens; its built-in player token also rewrites fuzzy names.
|
||||
for (String token : new String[] { "(player-id)", "(date-event)", "(vote-count)", "(date-milestone)" })
|
||||
TabCompleteHandler.getInstance().addTabCompleteOption(token, new java.util.ArrayList<>());
|
||||
for (AdminAction action : AdminAction.values()) {
|
||||
String[] arguments = switch (action) {
|
||||
case Status, Preview -> new String[] { "DateVoteMilestone&DVM", action.name(), "(player-id)", "(date-event)" };
|
||||
case SetVotes -> new String[] { "DateVoteMilestone&DVM", action.name(), "(player-id)", "(date-event)", "(vote-count)" };
|
||||
case Force, ForceNoLimits -> new String[] { "DateVoteMilestone&DVM", action.name(), "(player-id)", "(date-event)", "(date-milestone)" };
|
||||
};
|
||||
String description = switch (action) {
|
||||
case Status, Preview -> "Inspect date event counts and reward fences without submitting rewards";
|
||||
case SetVotes -> "Set date event count (0-4096), preserving receipt IDs and reward fences";
|
||||
case Force -> "Force selected date milestones, preserving prior submission and uncertain reservation fences";
|
||||
case ForceNoLimits -> "Repeat submitted date milestones; uncertain reservations remain blocked";
|
||||
};
|
||||
CommandHandler handler = new CommandHandler(plugin, arguments,
|
||||
"VotingPlugin.Commands.AdminVote.DateVoteMilestone." + action.name() + "|" + adminPermission, description) {
|
||||
@Override public void execute(CommandSender sender, String[] args) {
|
||||
var manager = plugin.getDateVoteMilestones();
|
||||
if (manager == null) { sender.sendMessage("Date milestones are unavailable."); return; }
|
||||
manager.administer(sender, action, args[2], args[3], args.length > 4 ? args[4] : null);
|
||||
}
|
||||
};
|
||||
handler.setAllowMultiplePermissions(true);
|
||||
plugin.getAdminVoteCommand().add(handler);
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -74,7 +74,7 @@ public class CommandAliases implements CommandExecutor {
|
||||
if (adminCommand) {
|
||||
sender.sendMessage(MessageAPI.colorize(plugin.getConfigFile().getFormatInvalidCommandAdminVote()));
|
||||
} else {
|
||||
sender.sendMessage(MessageAPI.colorize(plugin.getConfigFile().getFormatInvalidCommandVote()));
|
||||
sender.sendMessage(MessageAPI.colorize(plugin.formatVoteCommandMessage(plugin.getConfigFile().getFormatInvalidCommandVote())));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
+1
-1
@@ -35,7 +35,7 @@ public class CommandVote implements CommandExecutor {
|
||||
}
|
||||
|
||||
// invalid command
|
||||
sender.sendMessage(MessageAPI.colorize(plugin.getConfigFile().getFormatInvalidCommandVote()));
|
||||
sender.sendMessage(MessageAPI.colorize(plugin.formatVoteCommandMessage(plugin.getConfigFile().getFormatInvalidCommandVote())));
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
+8
-8
@@ -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("/vote") + " : "
|
||||
msg.add("&6" + handle.getHelpLineCommand(plugin.getVoteCommandPrefix()) + " : "
|
||||
+ handle.getPerm().split(Pattern.quote("|"))[0] + " : &atrue");
|
||||
} else {
|
||||
msg.add("&6" + handle.getHelpLineCommand("/vote") + " : "
|
||||
msg.add("&6" + handle.getHelpLineCommand(plugin.getVoteCommandPrefix()) + " : "
|
||||
+ handle.getPerm().split(Pattern.quote("|"))[0] + " : &cfalse");
|
||||
}
|
||||
} else {
|
||||
msg.add(handle.getHelpLineCommand("/vote") + " : " + handle.getPerm().split(Pattern.quote("|"))[0]);
|
||||
msg.add(handle.getHelpLineCommand(plugin.getVoteCommandPrefix()) + " : " + handle.getPerm().split(Pattern.quote("|"))[0]);
|
||||
}
|
||||
addAdditionalPermissions(msg, sender, handle, "/vote");
|
||||
addAdditionalPermissions(msg, sender, handle, plugin.getVoteCommandPrefix());
|
||||
|
||||
}
|
||||
|
||||
@@ -164,13 +164,13 @@ public class AdminVotePerms extends GUIHandler {
|
||||
|
||||
for (CommandHandler handle : plugin.getVoteCommand()) {
|
||||
if (handle.hasPerm(p)) {
|
||||
msg.add("&6" + handle.getHelpLineCommand("/vote") + " : "
|
||||
msg.add("&6" + handle.getHelpLineCommand(plugin.getVoteCommandPrefix()) + " : "
|
||||
+ handle.getPerm().split(Pattern.quote("|"))[0] + " : &atrue");
|
||||
} else {
|
||||
msg.add("&6" + handle.getHelpLineCommand("/vote") + " : "
|
||||
msg.add("&6" + handle.getHelpLineCommand(plugin.getVoteCommandPrefix()) + " : "
|
||||
+ handle.getPerm().split(Pattern.quote("|"))[0] + " : &cfalse");
|
||||
}
|
||||
addAdditionalPermissions(msg, p, handle, "/vote");
|
||||
addAdditionalPermissions(msg, p, handle, plugin.getVoteCommandPrefix());
|
||||
|
||||
}
|
||||
|
||||
@@ -237,7 +237,7 @@ public class AdminVotePerms extends GUIHandler {
|
||||
msg.add(" ");
|
||||
|
||||
for (CommandHandler handle : plugin.getVoteCommand()) {
|
||||
msg.add(handle.getHelpLineCommand("/vote"));
|
||||
msg.add(handle.getHelpLineCommand(plugin.getVoteCommandPrefix()));
|
||||
msg.add(" " + handle.getPerm());
|
||||
msg.add(" " + handle.getHelpMessage());
|
||||
for (String permission : additionalPermissions(handle)) {
|
||||
|
||||
+1
-1
@@ -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);
|
||||
VotingPluginUser vpUser = plugin.getVotingPluginUserManager().getVotingPluginUser(uuid, true);
|
||||
vpUser.userDataFetechMode(UserDataFetchMode.NO_CACHE);
|
||||
int points = vpUser.getPoints();
|
||||
if (points <= 0) continue;
|
||||
|
||||
+170
@@ -0,0 +1,170 @@
|
||||
package com.bencodez.votingplugin.commands.gui.player;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneId;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.function.BooleanSupplier;
|
||||
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.inventory.meta.ItemMeta;
|
||||
import org.bukkit.entity.HumanEntity;
|
||||
|
||||
import com.bencodez.advancedcore.api.inventory.BInventory;
|
||||
import com.bencodez.advancedcore.api.inventory.BInventory.ClickEvent;
|
||||
import com.bencodez.advancedcore.api.inventory.BInventoryButton;
|
||||
import com.bencodez.advancedcore.api.item.ItemBuilder;
|
||||
import com.bencodez.votingplugin.VotingPluginMain;
|
||||
import com.bencodez.votingplugin.core.datemilestones.DateVoteProgressSnapshot;
|
||||
import com.bencodez.votingplugin.core.datemilestones.DateVoteProgressSnapshot.Availability;
|
||||
import com.bencodez.votingplugin.core.datemilestones.DateVoteProgressSnapshot.Event;
|
||||
import com.bencodez.votingplugin.core.datemilestones.DateVoteProgressSnapshot.Milestone;
|
||||
|
||||
/** Entity-thread presentation of an immutable storage-worker result. */
|
||||
public final class DateVoteEventsMenu {
|
||||
private static final int PAGE_SIZE = 45;
|
||||
private static final int LIMIT = 64;
|
||||
private static final String OPEN_GUARD = "DateVoteEventsOpenGuard";
|
||||
private record OpenGuard(java.util.UUID owner, BooleanSupplier eligible) { }
|
||||
private static final DateTimeFormatter TIME = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
|
||||
|
||||
private final VotingPluginMain plugin;
|
||||
private final Player player;
|
||||
private final DateVoteProgressSnapshot snapshot;
|
||||
private final BooleanSupplier current;
|
||||
|
||||
private DateVoteEventsMenu(VotingPluginMain plugin, Player player, DateVoteProgressSnapshot snapshot,
|
||||
BooleanSupplier current) {
|
||||
this.plugin = plugin;
|
||||
this.player = player;
|
||||
this.snapshot = snapshot;
|
||||
this.current = current;
|
||||
}
|
||||
|
||||
public static void open(VotingPluginMain plugin, Player player, DateVoteProgressSnapshot snapshot,
|
||||
BooleanSupplier current) {
|
||||
new DateVoteEventsMenu(plugin, player, snapshot, current).list(0);
|
||||
}
|
||||
|
||||
private boolean eligible() {
|
||||
return current.getAsBoolean() && plugin.isEnabled() && player.isOnline()
|
||||
&& (player.hasPermission("VotingPlugin.Commands.Vote.DateEvents")
|
||||
|| player.hasPermission("VotingPlugin.Player"));
|
||||
}
|
||||
|
||||
private BInventory inventory(String title) {
|
||||
BInventory inventory = new BInventory(title);
|
||||
inventory.setMaxInvSize(54);
|
||||
inventory.setPages(false);
|
||||
inventory.runClicksSync();
|
||||
inventory.dontClose();
|
||||
inventory.addData(OPEN_GUARD, new OpenGuard(player.getUniqueId(), this::eligible));
|
||||
return inventory;
|
||||
}
|
||||
|
||||
/** Called at Bukkit's final InventoryOpenEvent, after AdvancedCore's deferred callback. */
|
||||
public static boolean permitsOpen(BInventory inventory, HumanEntity viewer) {
|
||||
Object value = inventory.getData(OPEN_GUARD);
|
||||
return !(value instanceof OpenGuard guard)
|
||||
|| guard.owner().equals(viewer.getUniqueId()) && guard.eligible().getAsBoolean();
|
||||
}
|
||||
|
||||
private void list(int page) {
|
||||
if (!eligible()) return;
|
||||
List<Event> events = snapshot.events().stream().limit(LIMIT).toList();
|
||||
BInventory inventory = inventory("Date vote events " + (page + 1) + "/" + pages(events.size()));
|
||||
int end = Math.min(events.size(), (page + 1) * PAGE_SIZE);
|
||||
for (int index = page * PAGE_SIZE; index < end; index++) {
|
||||
Event event = events.get(index);
|
||||
inventory.addButton(index % PAGE_SIZE, button(Material.PAPER,
|
||||
event.definition().displayName(), eventLore(event), () -> detail(event, 0, page)));
|
||||
}
|
||||
List<String> summary = new ArrayList<>();
|
||||
if (events.isEmpty()) summary.add("No date vote events configured.");
|
||||
else if (events.stream().noneMatch(event -> event.definition().enabled()))
|
||||
summary.add("No enabled date vote events.");
|
||||
else summary.add("Select an event to view milestones.");
|
||||
summary.add("Snapshot: " + Instant.ofEpochMilli(snapshot.capturedAt()));
|
||||
inventory.addButton(49, button(Material.BOOK, "Date vote events", summary, () -> {}));
|
||||
if (page > 0) inventory.addButton(45, button(Material.ARROW, "Previous page", List.of(), () -> list(page - 1)));
|
||||
if (end < events.size()) inventory.addButton(53, button(Material.ARROW, "Next page", List.of(), () -> list(page + 1)));
|
||||
if (eligible()) inventory.openInventory(player);
|
||||
}
|
||||
|
||||
private void detail(Event event, int page, int listPage) {
|
||||
if (!eligible()) return;
|
||||
List<Milestone> milestones = event.milestones().stream().limit(LIMIT).toList();
|
||||
BInventory inventory = inventory("Date vote milestones " + (page + 1) + "/" + pages(milestones.size()));
|
||||
int end = Math.min(milestones.size(), (page + 1) * PAGE_SIZE);
|
||||
for (int index = page * PAGE_SIZE; index < end; index++) {
|
||||
Milestone milestone = milestones.get(index);
|
||||
List<String> lore = new ArrayList<>();
|
||||
lore.add("ID: " + milestone.id());
|
||||
lore.add("Enabled: " + milestone.enabled());
|
||||
lore.add("Award state: " + event.awardState(milestone.threshold()));
|
||||
List<String> types = milestone.rewardTypes().stream().limit(LIMIT)
|
||||
.map(type -> type.matches("[A-Za-z0-9_-]{1,64}") ? type : "Other").distinct().toList();
|
||||
lore.add("Reward types: " + (types.isEmpty() ? "none" : String.join(", ", types)));
|
||||
inventory.addButton(index % PAGE_SIZE, button(Material.PAPER, milestone.threshold() + " votes", lore, () -> {}));
|
||||
}
|
||||
List<String> summary = eventLore(event);
|
||||
if (milestones.isEmpty()) summary.add("No milestones configured.");
|
||||
inventory.addButton(48, button(Material.BOOK, event.definition().displayName(), summary, () -> {}));
|
||||
inventory.addButton(49, button(Material.ARROW, "Back to events", List.of(), () -> list(listPage)));
|
||||
if (page > 0) inventory.addButton(45, button(Material.ARROW, "Previous page", List.of(), () -> detail(event, page - 1, listPage)));
|
||||
if (end < milestones.size()) inventory.addButton(53, button(Material.ARROW, "Next page", List.of(), () -> detail(event, page + 1, listPage)));
|
||||
if (eligible()) inventory.openInventory(player);
|
||||
}
|
||||
|
||||
private List<String> eventLore(Event event) {
|
||||
var definition = event.definition();
|
||||
List<String> lore = new ArrayList<>();
|
||||
lore.add("ID: " + definition.id());
|
||||
lore.add("Status: " + event.status(snapshot.capturedAt()));
|
||||
ZoneId zone = ZoneId.of(definition.timezone());
|
||||
lore.add("Start: " + TIME.format(Instant.ofEpochMilli(definition.start()).atZone(zone)));
|
||||
lore.add("End (exclusive): " + TIME.format(Instant.ofEpochMilli(definition.end()).atZone(zone)));
|
||||
lore.add("Timezone: " + definition.timezone());
|
||||
if (event.availability() == Availability.OWNED) {
|
||||
lore.add("Votes: " + event.votes());
|
||||
lore.add("Next milestone: " + (event.nextThreshold().isPresent() ? event.nextThreshold().getAsInt() + " votes" : "none"));
|
||||
} else if (event.availability() == Availability.REMOTE) {
|
||||
lore.add("Progress owned by: " + definition.accountingServer());
|
||||
lore.add("Progress unavailable on this server.");
|
||||
} else {
|
||||
lore.add("Progress unavailable: accounting read failed.");
|
||||
}
|
||||
return lore;
|
||||
}
|
||||
|
||||
private static int pages(int size) {
|
||||
return Math.max(1, (size + PAGE_SIZE - 1) / PAGE_SIZE);
|
||||
}
|
||||
|
||||
private BInventoryButton button(Material material, String name, List<String> lore, Runnable action) {
|
||||
List<String> lines = List.copyOf(lore);
|
||||
return new BInventoryButton(new ItemBuilder(material)) {
|
||||
// ItemBuilder evaluates display Javascript and formatting while rendering. Render only
|
||||
// the blank material through it, then apply snapshot text literally to Bukkit metadata.
|
||||
@Override public ItemStack getItem() {
|
||||
ItemStack item = new ItemBuilder(material).toItemStack();
|
||||
ItemMeta meta = item.getItemMeta();
|
||||
if (meta != null) {
|
||||
meta.setDisplayName(name);
|
||||
meta.setLore(lines);
|
||||
item.setItemMeta(meta);
|
||||
}
|
||||
return item;
|
||||
}
|
||||
@Override public ItemStack getItem(Player ignored) { return getItem(); }
|
||||
@Override public ItemStack getItem(Player ignored, HashMap<String, String> placeholders) { return getItem(); }
|
||||
@Override public void onClick(ClickEvent click) {
|
||||
if (eligible()) action.run();
|
||||
}
|
||||
}.dontClose();
|
||||
}
|
||||
}
|
||||
+5
-3
@@ -55,6 +55,7 @@ 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();
|
||||
@@ -70,7 +71,7 @@ public class VoteHelp extends GUIHandler {
|
||||
}
|
||||
for (CommandHandler cmdHandle : plugin.getVoteCommand()) {
|
||||
if (!requirePerms || cmdHandle.hasPerm(sender)) {
|
||||
unsorted.put(cmdHandle.getHelpLineCommand("/vote"), cmdHandle.getHelpLine("/vote",
|
||||
unsorted.put(cmdHandle.getHelpLineCommand(plugin.getVoteCommandPrefix()), cmdHandle.getHelpLine(plugin.getVoteCommandPrefix(),
|
||||
plugin.getConfigFile().getFormatCommandsVoteHelpLine(), hoverColor));
|
||||
}
|
||||
}
|
||||
@@ -92,14 +93,15 @@ 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("/vote"),
|
||||
cmdHandle.getHelpLine("/vote", plugin.getConfigFile().getFormatCommandsVoteHelpLine()));
|
||||
unsorted.put(cmdHandle.getHelpLineCommand(plugin.getVoteCommandPrefix()),
|
||||
cmdHandle.getHelpLine(plugin.getVoteCommandPrefix(), plugin.getConfigFile().getFormatCommandsVoteHelpLine()));
|
||||
}
|
||||
}
|
||||
ArrayList<String> unsortedList = new ArrayList<>();
|
||||
|
||||
+5
-5
@@ -71,7 +71,7 @@ public class VoteLast extends GUIHandler {
|
||||
continue;
|
||||
}
|
||||
|
||||
dialog.placeholder("sitename", site.getDisplayNameForFormatting()).button(site.getDisplayNameForFormatting(),
|
||||
dialog.placeholder("sitename", site.getDisplayName()).button(site.getDisplayName(),
|
||||
user.voteCommandLastLine(site), payload -> {
|
||||
|
||||
if (plugin.getGui().isChestVoteLastClickableLinks()) {
|
||||
@@ -83,7 +83,7 @@ public class VoteLast extends GUIHandler {
|
||||
|
||||
HashMap<String, String> placeholders = new HashMap<String, String>();
|
||||
placeholders.put("voteurl", site.getVoteURL());
|
||||
placeholders.put("sitename", site.getDisplayNameForFormatting());
|
||||
placeholders.put("sitename", site.getDisplayName());
|
||||
placeholders.put("player", clicked.getName());
|
||||
|
||||
clickedUser.sendMessage(plugin.getGui().getChestVoteURLURLText(), placeholders);
|
||||
@@ -121,7 +121,7 @@ public class VoteLast extends GUIHandler {
|
||||
for (VoteSite site : plugin.getVoteSiteManager().getVoteSitesEnabled()) {
|
||||
if (!site.isHidden()) {
|
||||
inv.addButton(inv.getNextSlot(),
|
||||
new UpdatingBInventoryButton(plugin, site.getItem().setName(site.getDisplayNameForFormatting())
|
||||
new UpdatingBInventoryButton(plugin, site.getItem().setName(site.getDisplayName())
|
||||
.setLore(user.voteCommandLastGUILine(site)).setAmountNone(1), 1000, 1000) {
|
||||
|
||||
@Override
|
||||
@@ -139,7 +139,7 @@ public class VoteLast extends GUIHandler {
|
||||
plugin.getGui()
|
||||
.getChestVoteURLURLText(),
|
||||
"voteurl", site.getVoteURL()),
|
||||
"sitename", site.getDisplayNameForFormatting()),
|
||||
"sitename", site.getDisplayName()),
|
||||
"player", player.getName()));
|
||||
|
||||
}
|
||||
@@ -148,7 +148,7 @@ public class VoteLast extends GUIHandler {
|
||||
|
||||
@Override
|
||||
public ItemBuilder onUpdate(Player p) {
|
||||
return site.getItem().setName(site.getDisplayNameForFormatting())
|
||||
return site.getItem().setName(site.getDisplayName())
|
||||
.setLore(user.voteCommandLastGUILine(site)).setAmountNone(1);
|
||||
}
|
||||
});
|
||||
|
||||
+6
-6
@@ -60,7 +60,7 @@ public class VoteNext extends GUIHandler {
|
||||
|
||||
msgLine = MessageAPI.replaceIgnoreCase(msgLine, "%info%", user.voteCommandNextInfo(voteSite));
|
||||
|
||||
msgLine = MessageAPI.replaceIgnoreCase(msgLine, "%SiteName%", voteSite.getDisplayNameForFormatting());
|
||||
msgLine = MessageAPI.replaceIgnoreCase(msgLine, "%SiteName%", voteSite.getDisplayName());
|
||||
msg.add(MessageAPI.colorize(msgLine));
|
||||
}
|
||||
}
|
||||
@@ -81,10 +81,10 @@ public class VoteNext extends GUIHandler {
|
||||
String siteNameDisplay = plugin.getGui().getChestVoteNextCustomSiteNamesDisplays(site.getKey());
|
||||
|
||||
if (siteNameDisplay.isEmpty()) {
|
||||
siteNameDisplay = site.getDisplayNameForFormatting();
|
||||
siteNameDisplay = site.getDisplayName();
|
||||
}
|
||||
|
||||
dialog.placeholder("sitename", site.getDisplayNameForFormatting()).placeholder("SiteName", site.getDisplayNameForFormatting())
|
||||
dialog.placeholder("sitename", site.getDisplayName()).placeholder("SiteName", site.getDisplayName())
|
||||
.placeholder("info", user.voteCommandNextInfo(site))
|
||||
.button(siteNameDisplay, user.voteCommandNextInfo(site), payload -> {
|
||||
|
||||
@@ -117,7 +117,7 @@ public class VoteNext extends GUIHandler {
|
||||
if (!site.isHidden()) {
|
||||
Layout nextLayout = new Layout(new ArrayList<>(Arrays.asList("[Json]")));
|
||||
nextLayout.replaceTextComponent("[Json]",
|
||||
BookUtil.TextBuilder.of(book.colorize(site.getDisplayNameForFormatting()))
|
||||
BookUtil.TextBuilder.of(book.colorize(site.getDisplayName()))
|
||||
.onClick(BookUtil.ClickAction.openUrl(site.getVoteURLJsonStrip()))
|
||||
.onHover(BookUtil.HoverAction.showText(user.voteCommandNextInfo(site))).build());
|
||||
book.addLayout(nextLayout);
|
||||
@@ -141,7 +141,7 @@ public class VoteNext extends GUIHandler {
|
||||
if (!site.isHidden()) {
|
||||
String siteNameDisplay = plugin.getGui().getChestVoteNextCustomSiteNamesDisplays(site.getKey());
|
||||
if (siteNameDisplay.isEmpty()) {
|
||||
siteNameDisplay = site.getDisplayNameForFormatting();
|
||||
siteNameDisplay = site.getDisplayName();
|
||||
}
|
||||
inv.addButton(inv.getNextSlot(),
|
||||
new UpdatingBInventoryButton(plugin,
|
||||
@@ -159,7 +159,7 @@ public class VoteNext extends GUIHandler {
|
||||
|
||||
@Override
|
||||
public ItemBuilder onUpdate(Player player) {
|
||||
return site.getItem().setName(site.getDisplayNameForFormatting())
|
||||
return site.getItem().setName(site.getDisplayName())
|
||||
.setLore(user.voteCommandNextInfo(site)).setAmountNone(1)
|
||||
.addPlaceholder("player", user.getPlayerName());
|
||||
}
|
||||
|
||||
+10
-10
@@ -52,15 +52,15 @@ public class VoteToday extends GUIHandler {
|
||||
final UUID uuid = topPlayer.getUuid();
|
||||
|
||||
dialog.placeholder("player", topPlayer.getPlayerName()).placeholder("votesite", voteSite.getKey())
|
||||
.placeholder("sitename", voteSite.getDisplayNameForFormatting())
|
||||
.placeholder("SiteName", voteSite.getDisplayNameForFormatting())
|
||||
.placeholder("VoteSite", voteSite.getDisplayNameForFormatting()).placeholder("time", timeString)
|
||||
.placeholder("sitename", voteSite.getDisplayName())
|
||||
.placeholder("SiteName", voteSite.getDisplayName())
|
||||
.placeholder("VoteSite", voteSite.getDisplayName()).placeholder("time", timeString)
|
||||
.placeholder("Time", timeString).button("&e" + topPlayer.getPlayerName(),
|
||||
plugin.getConfigFile().getFormatCommandsVoteTodayLine(), payload -> {
|
||||
Player clicked = player.getServer().getPlayer(payload.owner());
|
||||
if (clicked != null) {
|
||||
VotingPluginUser clickedUser = plugin.getVotingPluginUserManager()
|
||||
.getVotingPluginUser(uuid);
|
||||
.getVotingPluginUser(uuid, true);
|
||||
new VoteGUI(plugin, clicked, clickedUser).open(
|
||||
GUIMethod.valueOf(plugin.getGui().getGuiMethodGUI().toUpperCase()));
|
||||
}
|
||||
@@ -136,9 +136,9 @@ public class VoteToday extends GUIHandler {
|
||||
HashMap<String, String> placeholders = new HashMap<>();
|
||||
placeholders.put("player", user.getPlayerName());
|
||||
placeholders.put("votesite", voteSite.getKey());
|
||||
placeholders.put("sitename", voteSite.getDisplayNameForFormatting());
|
||||
placeholders.put("SiteName", voteSite.getDisplayNameForFormatting());
|
||||
placeholders.put("VoteSite", voteSite.getDisplayNameForFormatting());
|
||||
placeholders.put("sitename", voteSite.getDisplayName());
|
||||
placeholders.put("SiteName", voteSite.getDisplayName());
|
||||
placeholders.put("VoteSite", voteSite.getDisplayName());
|
||||
placeholders.put("time", timeString);
|
||||
placeholders.put("Time", timeString);
|
||||
|
||||
@@ -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);
|
||||
VotingPluginUser user = plugin.getVotingPluginUserManager().getVotingPluginUser(uuid, true);
|
||||
new VoteGUI(plugin, player, user)
|
||||
.open(GUIMethod.valueOf(plugin.getGui().getGuiMethodGUI().toUpperCase()));
|
||||
}
|
||||
@@ -204,7 +204,7 @@ public class VoteToday extends GUIHandler {
|
||||
HashMap<String, String> placeholders = new HashMap<>();
|
||||
placeholders.put("player", user.getPlayerName());
|
||||
placeholders.put("votesite", voteSite.getKey());
|
||||
placeholders.put("sitename", voteSite.getDisplayNameForFormatting());
|
||||
placeholders.put("sitename", voteSite.getDisplayName());
|
||||
placeholders.put("time", timeString);
|
||||
msg.add(PlaceholderUtils.replacePlaceHolder(plugin.getConfigFile().getFormatCommandsVoteTodayLine(),
|
||||
placeholders));
|
||||
@@ -234,7 +234,7 @@ public class VoteToday extends GUIHandler {
|
||||
HashMap<String, String> placeholders = new HashMap<>();
|
||||
placeholders.put("player", user.getPlayerName());
|
||||
placeholders.put("votesite", mostRecentSite.getKey());
|
||||
placeholders.put("sitename", mostRecentSite.getDisplayNameForFormatting());
|
||||
placeholders.put("sitename", mostRecentSite.getDisplayName());
|
||||
placeholders.put("time", timeString);
|
||||
msg.add(PlaceholderUtils.replacePlaceHolder(plugin.getConfigFile().getFormatCommandsVoteTodayLine(),
|
||||
placeholders));
|
||||
|
||||
+2
-2
@@ -51,7 +51,7 @@ public class VoteTopVoter extends GUIHandler {
|
||||
String topVoter = top.getName();
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
LinkedHashMap<TopVoterPlayer, Integer> topVotes = (LinkedHashMap<TopVoterPlayer, Integer>) plugin.getTopVoter(top)
|
||||
LinkedHashMap<TopVoterPlayer, Integer> topVotes = (LinkedHashMap<TopVoterPlayer, Integer>) plugin.getTopVoterDisplay(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
|
||||
.getTopVoter(top).clone();
|
||||
.getTopVoterDisplay(top).clone();
|
||||
users = topVotes.entrySet();
|
||||
|
||||
ConfigurationSection customization = plugin.getGui().getChestVoteTopCustomization();
|
||||
|
||||
+2
-2
@@ -31,7 +31,7 @@ public class VoteTopVoterLastMonth extends GUIHandler {
|
||||
|
||||
@Override
|
||||
public void onDialog(Player player) {
|
||||
Set<Entry<TopVoterPlayer, Integer>> users = plugin.getLastMonthTopVoter().entrySet();
|
||||
Set<Entry<TopVoterPlayer, Integer>> users = plugin.getLastMonthTopVoterDisplay().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.getLastMonthTopVoter().entrySet();
|
||||
users = plugin.getLastMonthTopVoterDisplay().entrySet();
|
||||
|
||||
BInventory inv = new BInventory(plugin.getGui().getChestVoteTopName());
|
||||
inv.addPlaceholder("topvoter", "Last Month");
|
||||
|
||||
+2
-2
@@ -60,7 +60,7 @@ public class VoteTopVoterPreviousMonths extends GUIHandler {
|
||||
return;
|
||||
}
|
||||
|
||||
Set<Entry<TopVoterPlayer, Integer>> users = plugin.getPreviousMonthsTopVoters().get(yearMonth).entrySet();
|
||||
Set<Entry<TopVoterPlayer, Integer>> users = plugin.getPreviousMonthTopVoterDisplay(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.getPreviousMonthsTopVoters().get(yearMonth).entrySet();
|
||||
users = plugin.getPreviousMonthTopVoterDisplay(yearMonth).entrySet();
|
||||
|
||||
BInventory inv = new BInventory(plugin.getGui().getChestVoteTopName());
|
||||
inv.addPlaceholder("topvoter", yearMonth.toString());
|
||||
|
||||
+14
-14
@@ -71,7 +71,7 @@ public class VoteURL extends GUIHandler {
|
||||
plugin.getConfigFile().getFormatCommandsVoteURLS());
|
||||
message.replacePlaceholder("num", Integer.toString(counter))
|
||||
.replacePlaceholder("url", voteURL)
|
||||
.replacePlaceholder("SiteName", voteSite.getDisplayNameForFormatting());
|
||||
.replacePlaceholder("SiteName", voteSite.getDisplayName());
|
||||
if (user != null && user.getPlayerName() != null) {
|
||||
message.replacePlaceholder("player", "" + user.getPlayerName())
|
||||
.replacePlaceholder("Next", "" + user.voteCommandNextInfo(voteSite));
|
||||
@@ -150,14 +150,14 @@ public class VoteURL extends GUIHandler {
|
||||
boolean canVote = finalUser.canVoteSite(voteSite);
|
||||
String color = canVote ? "&a" : "&c";
|
||||
|
||||
dialog.placeholder("sitename", voteSite.getDisplayNameForFormatting())
|
||||
.placeholder("SiteName", voteSite.getDisplayNameForFormatting())
|
||||
.placeholder("servicesite", voteSite.getServiceSiteForFormatting())
|
||||
.placeholder("ServiceSite", voteSite.getServiceSiteForFormatting())
|
||||
dialog.placeholder("sitename", voteSite.getDisplayName())
|
||||
.placeholder("SiteName", voteSite.getDisplayName())
|
||||
.placeholder("servicesite", voteSite.getServiceSite())
|
||||
.placeholder("ServiceSite", voteSite.getServiceSite())
|
||||
.placeholder("VoteDelay", "" + voteSite.getVoteDelay())
|
||||
.placeholder("VoteHour", "" + voteSite.getVoteDelayDailyHour())
|
||||
.placeholder("Next", finalUser.voteCommandNextInfo(voteSite))
|
||||
.button(color + voteSite.getDisplayNameForFormatting(),
|
||||
.button(color + voteSite.getDisplayName(),
|
||||
canVote ? "&aClick to view vote link" : "&c" + finalUser.voteCommandNextInfo(voteSite),
|
||||
payload -> {
|
||||
Player clicked = player.getServer().getPlayer(payload.owner());
|
||||
@@ -166,9 +166,9 @@ public class VoteURL extends GUIHandler {
|
||||
.getVotingPluginUser(clicked);
|
||||
HashMap<String, String> placeholders = new HashMap<String, String>();
|
||||
placeholders.put("voteurl", voteSite.getVoteURL());
|
||||
placeholders.put("sitename", voteSite.getDisplayNameForFormatting());
|
||||
placeholders.put("sitename", voteSite.getDisplayName());
|
||||
placeholders.put("player", clicked.getName());
|
||||
placeholders.put("servicesite", voteSite.getServiceSiteForFormatting());
|
||||
placeholders.put("servicesite", voteSite.getServiceSite());
|
||||
placeholders.put("VoteDelay", "" + voteSite.getVoteDelay());
|
||||
placeholders.put("VoteHour", "" + voteSite.getVoteDelayDailyHour());
|
||||
clickedUser.sendMessage(plugin.getGui().getChestVoteURLURLText(), placeholders);
|
||||
@@ -177,7 +177,7 @@ public class VoteURL extends GUIHandler {
|
||||
}
|
||||
|
||||
if (plugin.getGui().isChestVoteURLBackButton()) {
|
||||
dialog.button("&eBack", "&7Return to previous menu", payload -> player.performCommand("vote gui"));
|
||||
dialog.button("&eBack", "&7Return to previous menu", payload -> plugin.getCommandLoader().performVoteCommand(player, "gui"));
|
||||
}
|
||||
|
||||
dialog.open();
|
||||
@@ -218,8 +218,8 @@ public class VoteURL extends GUIHandler {
|
||||
builder.setName(plugin.getGui().getChestVoteURLGUISiteName());
|
||||
builder.addLoreLine(plugin.getGui().getChestVoteURLNextVote());
|
||||
}
|
||||
builder.addPlaceholder("ServiceSite", voteSite.getServiceSiteForFormatting());
|
||||
builder.addPlaceholder("Name", voteSite.getDisplayNameForFormatting());
|
||||
builder.addPlaceholder("ServiceSite", voteSite.getServiceSite());
|
||||
builder.addPlaceholder("Name", voteSite.getDisplayName());
|
||||
builder.addPlaceholder("VoteDelay", "" + voteSite.getVoteDelay());
|
||||
builder.addPlaceholder("VoteHour", "" + voteSite.getVoteDelayDailyHour());
|
||||
builder.addPlaceholder("Info", user.voteCommandNextInfo(voteSite));
|
||||
@@ -240,7 +240,7 @@ public class VoteURL extends GUIHandler {
|
||||
if (!site.isHidden()) {
|
||||
if (site.getPermissionToView().isEmpty() || player.hasPermission(site.getPermissionToView())) {
|
||||
Layout layout = new Layout(plugin.getGui().getBookVoteURLBookGUILayout())
|
||||
.addPlaceholder("sitename", site.getDisplayNameForFormatting()).addPlaceholder("num", "" + i);
|
||||
.addPlaceholder("sitename", site.getDisplayName()).addPlaceholder("num", "" + i);
|
||||
String text = plugin.getGui().getBookVoteURLBookGUIAlreadyVotedText();
|
||||
ChatColor color = ChatColor.valueOf(plugin.getGui().getBookVoteURLBookGUIAlreadyVotedColor());
|
||||
if (user.canVoteSite(site)) {
|
||||
@@ -342,9 +342,9 @@ public class VoteURL extends GUIHandler {
|
||||
VotingPluginUser user = plugin.getVotingPluginUserManager().getVotingPluginUser(player);
|
||||
HashMap<String, String> placeholders = new HashMap<>();
|
||||
placeholders.put("voteurl", voteSite.getVoteURL());
|
||||
placeholders.put("sitename", voteSite.getDisplayNameForFormatting());
|
||||
placeholders.put("sitename", voteSite.getDisplayName());
|
||||
placeholders.put("player", player.getName());
|
||||
placeholders.put("servicesite", voteSite.getServiceSiteForFormatting());
|
||||
placeholders.put("servicesite", voteSite.getServiceSite());
|
||||
placeholders.put("VoteDelay", "" + voteSite.getVoteDelay());
|
||||
placeholders.put("VoteHour", "" + voteSite.getVoteDelayDailyHour());
|
||||
user.sendMessage(plugin.getGui().getChestVoteURLURLText(), placeholders);
|
||||
|
||||
+5
-5
@@ -53,7 +53,7 @@ public class VoteURLVoteSite extends GUIHandler {
|
||||
}
|
||||
VoteSite site = plugin.getVoteSiteManager().getVoteSite(voteSite, true);
|
||||
BInventory inv = new BInventory(plugin.getGui().getChestVoteURLSiteName());
|
||||
inv.addPlaceholder("site", site.getDisplayNameForFormatting());
|
||||
inv.addPlaceholder("site", site.getDisplayName());
|
||||
inv.setMeta(player, "VoteSite", site);
|
||||
if (!plugin.getConfigFile().isAlwaysCloseInventory()) {
|
||||
inv.dontClose();
|
||||
@@ -117,10 +117,10 @@ public class VoteURLVoteSite extends GUIHandler {
|
||||
VoteSite site = plugin.getVoteSiteManager().getVoteSite(voteSite, true);
|
||||
|
||||
com.bencodez.simpleapi.dialog.MultiActionDialogBuilder dialog = plugin.getDialogService().multiAction(player)
|
||||
.placeholder("player", user.getPlayerName()).placeholder("site", site.getDisplayNameForFormatting())
|
||||
.placeholder("sitename", site.getDisplayNameForFormatting()).placeholder("SiteName", site.getDisplayNameForFormatting())
|
||||
.placeholder("servicesite", site.getServiceSiteForFormatting())
|
||||
.placeholder("ServiceSite", site.getServiceSiteForFormatting())
|
||||
.placeholder("player", user.getPlayerName()).placeholder("site", site.getDisplayName())
|
||||
.placeholder("sitename", site.getDisplayName()).placeholder("SiteName", site.getDisplayName())
|
||||
.placeholder("servicesite", site.getServiceSite())
|
||||
.placeholder("ServiceSite", site.getServiceSite())
|
||||
.placeholder("VoteDelay", "" + site.getVoteDelay())
|
||||
.placeholder("VoteHour", "" + site.getVoteDelayDailyHour())
|
||||
.placeholder("Next", user.voteCommandNextInfo(site)).placeholder("Last", user.voteCommandLastLine(site))
|
||||
|
||||
@@ -522,6 +522,15 @@ 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;
|
||||
@@ -800,6 +809,10 @@ 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;
|
||||
|
||||
@@ -87,7 +87,7 @@ public class ConfigVoteSites extends YMLFile {
|
||||
setVoteDelay(siteName, "24h");
|
||||
set(siteName, "DisplayItem.Material", "STONE");
|
||||
set(siteName, "DisplayItem.Amount", 1);
|
||||
set(siteName, "Rewards.Messages.Player", "&aThanks for voting on %SiteName%!");
|
||||
set(siteName, "Rewards.Messages.Player", "&aThanks for voting on %ServiceSite%!");
|
||||
set(siteName, "WaitUntilVoteDelayRewards", Collections.emptyMap());
|
||||
|
||||
plugin.loadVoteSites();
|
||||
|
||||
@@ -26,6 +26,10 @@ 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,10 +11,13 @@ 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;
|
||||
@@ -36,12 +39,14 @@ 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.
|
||||
@@ -74,6 +79,8 @@ 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()) {
|
||||
@@ -147,6 +154,7 @@ public class CoolDownCheck implements Listener {
|
||||
user.updateTempCacheWithColumns(cols);
|
||||
cols.clear(); // help GC (only useful if reused)
|
||||
}
|
||||
capturePlayerName(user);
|
||||
|
||||
checkPerSite(site, user);
|
||||
} finally {
|
||||
@@ -219,13 +227,20 @@ 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;
|
||||
return coolDownChecks;
|
||||
}
|
||||
|
||||
HashMap<String, Boolean> coolDownChecks = user.getCoolDownCheckSiteList();
|
||||
if (coolDownChecks == null) {
|
||||
coolDownChecks = user.getCoolDownCheckSiteList();
|
||||
}
|
||||
if (Boolean.TRUE.equals(coolDownChecks.get(site.getKey()))) {
|
||||
return;
|
||||
return coolDownChecks;
|
||||
}
|
||||
|
||||
if (user.canVoteSite(site)) {
|
||||
@@ -237,6 +252,7 @@ public class CoolDownCheck implements Listener {
|
||||
PlayerVoteSiteCoolDownEndEvent event = new PlayerVoteSiteCoolDownEndEvent(user, site);
|
||||
plugin.getServer().getPluginManager().callEvent(event);
|
||||
}
|
||||
return coolDownChecks;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -267,8 +283,8 @@ public class CoolDownCheck implements Listener {
|
||||
*/
|
||||
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
|
||||
public void onCoolDownEnd(PlayerVoteCoolDownEndEvent event) {
|
||||
plugin.getRewardHandler().giveReward(event.getPlayer(), plugin.getSpecialRewardsConfig().getData(),
|
||||
"VoteCoolDownEndedReward", new RewardOptions());
|
||||
dispatchCooldownReward(event.getPlayer(), plugin.getSpecialRewardsConfig().getData(),
|
||||
"VoteCoolDownEndedReward", "all", new RewardOptions());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -278,12 +294,73 @@ public class CoolDownCheck implements Listener {
|
||||
*/
|
||||
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
|
||||
public void onCoolDownEnd(PlayerVoteSiteCoolDownEndEvent event) {
|
||||
plugin.getRewardHandler().giveReward(event.getPlayer(), event.getSite().getSiteData(), "CoolDownEndRewards",
|
||||
new RewardOptions().addPlaceholder("sitename", event.getSite().getDisplayName())
|
||||
.addDisplayPlaceholder("sitename", event.getSite().getDisplayNameForFormatting())
|
||||
dispatchCooldownReward(event.getPlayer(), event.getSite().getSiteData(), "CoolDownEndRewards",
|
||||
"site:" + event.getSite().getKey(), 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.
|
||||
*
|
||||
@@ -325,7 +402,7 @@ public class CoolDownCheck implements Listener {
|
||||
* @param force whether to force the schedule
|
||||
*/
|
||||
public void schedulePerSite(VotingPluginUser user, boolean force) {
|
||||
if (!plugin.getConfigFile().isPerSiteCoolDownEvents()) {
|
||||
if (stopped || !plugin.getConfigFile().isPerSiteCoolDownEvents()) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -334,6 +411,7 @@ public class CoolDownCheck implements Listener {
|
||||
}
|
||||
|
||||
final UUID uuid = user.getJavaUUID();
|
||||
final String scheduledName = user.getPlayerName();
|
||||
|
||||
final NextSite next = user.getNextSiteAvailable();
|
||||
|
||||
@@ -341,8 +419,13 @@ 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
|
||||
}
|
||||
@@ -350,21 +433,60 @@ public class CoolDownCheck implements Listener {
|
||||
plugin.devDebug("PerSiteCoolDownEvent schedule: site=" + next.getSite().getKey() + " time="
|
||||
+ next.getSecondsUntilAvailable() + " seconds");
|
||||
|
||||
return timer.schedule(() -> {
|
||||
if (!plugin.isEnabled()) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 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);
|
||||
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;
|
||||
}
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles a vote event for cooldown scheduling.
|
||||
*
|
||||
@@ -382,6 +504,14 @@ 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.
|
||||
*/
|
||||
@@ -422,9 +552,11 @@ 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++) {
|
||||
checkPerSite(dailySites.get(i), user);
|
||||
coolDownChecks = checkPerSite(dailySites.get(i), user, coolDownChecks);
|
||||
}
|
||||
|
||||
check(user);
|
||||
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
package com.bencodez.votingplugin.core.datemilestones;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.DataOutputStream;
|
||||
import java.security.MessageDigest;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
/** Immutable owner-defined event accounting contract; display text is not identity. */
|
||||
public record DateVoteEvent(String id, String displayName, boolean enabled, long start, long end,
|
||||
String timezone, List<Integer> thresholds, Set<String> sites, String accountingServer) {
|
||||
public DateVoteEvent {
|
||||
if (id == null || !id.matches("[A-Za-z0-9_-]{1,64}")) throw new IllegalArgumentException("Invalid event ID");
|
||||
if (start <= 0 || end <= start) throw new IllegalArgumentException("End must be after start");
|
||||
ZoneId.of(timezone);
|
||||
if (thresholds.isEmpty() || thresholds.size() > 64 || thresholds.stream().anyMatch(n -> n <= 0 || n > 4096)
|
||||
|| thresholds.stream().distinct().count() != thresholds.size()) throw new IllegalArgumentException("Invalid thresholds (1–4096, unique, max 64)");
|
||||
thresholds = thresholds.stream().sorted().toList();
|
||||
if (sites.size() > 100 || sites.stream().anyMatch(s -> s == null || s.length() > 128 || s.isBlank()))
|
||||
throw new IllegalArgumentException("Invalid site filters");
|
||||
sites = Set.copyOf(sites);
|
||||
if (accountingServer == null || accountingServer.length() > 128) throw new IllegalArgumentException("Invalid accounting server");
|
||||
if (displayName == null || displayName.length() > 256) throw new IllegalArgumentException("Invalid display name");
|
||||
}
|
||||
public boolean matches(long occurredAt, String site, boolean real, boolean proxy, String server) {
|
||||
return enabled && real && occurredAt >= start && occurredAt < end && (sites.isEmpty() || sites.contains(site))
|
||||
&& (!proxy || !accountingServer.isBlank() && accountingServer.equals(server));
|
||||
}
|
||||
public String fingerprint() {
|
||||
try {
|
||||
var bytes = new ByteArrayOutputStream();
|
||||
try (var data = new DataOutputStream(bytes)) {
|
||||
data.writeLong(start); data.writeLong(end); data.writeUTF(timezone);
|
||||
data.writeInt(thresholds.size());
|
||||
for (int threshold : thresholds) data.writeInt(threshold);
|
||||
data.writeInt(sites.size());
|
||||
for (String site : sites.stream().sorted().toList()) data.writeUTF(site);
|
||||
data.writeUTF(accountingServer);
|
||||
}
|
||||
return hash(bytes.toByteArray());
|
||||
} catch (java.io.IOException impossible) { throw new IllegalStateException(impossible); }
|
||||
}
|
||||
/** Portable case-sensitive identity, including on case-insensitive filesystems. */
|
||||
public String fileId() { return fileId(id); }
|
||||
public static String fileId(String id) {
|
||||
if (id == null || !id.matches("[A-Za-z0-9_-]{1,64}")) throw new IllegalArgumentException("Invalid event ID");
|
||||
return hash(id.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
private static String hash(byte[] bytes) {
|
||||
try { return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); }
|
||||
catch (java.security.NoSuchAlgorithmException impossible) { throw new IllegalStateException(impossible); }
|
||||
}
|
||||
public static long timestamp(String localIso, String timezone) {
|
||||
LocalDateTime time = LocalDateTime.parse(localIso);
|
||||
ZoneId zone = ZoneId.of(timezone);
|
||||
if (zone.getRules().getValidOffsets(time).size() != 1)
|
||||
throw new IllegalArgumentException("Ambiguous/nonexistent local time; choose an unambiguous boundary");
|
||||
return time.atZone(zone).toInstant().toEpochMilli();
|
||||
}
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
package com.bencodez.votingplugin.core.datemilestones;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.OptionalInt;
|
||||
import java.util.Set;
|
||||
|
||||
/** Immutable worker result; viewing this snapshot never mutates accounting or rewards. */
|
||||
public record DateVoteProgressSnapshot(long capturedAt, List<Event> events) {
|
||||
public DateVoteProgressSnapshot { events = List.copyOf(events); }
|
||||
public enum Availability { OWNED, REMOTE, UNAVAILABLE }
|
||||
public record Milestone(int threshold, String id, boolean enabled, List<String> rewardTypes) {
|
||||
public Milestone { rewardTypes = List.copyOf(rewardTypes); }
|
||||
}
|
||||
public record Event(DateVoteEvent definition, Availability availability, int votes,
|
||||
Set<Integer> submitted, Set<Integer> deferred, Set<Integer> reserved, List<Milestone> milestones) {
|
||||
public Event {
|
||||
submitted = Set.copyOf(submitted); deferred = Set.copyOf(deferred); reserved = Set.copyOf(reserved);
|
||||
milestones = List.copyOf(milestones);
|
||||
}
|
||||
public String status(long now) {
|
||||
return !definition.enabled() ? "disabled" : now < definition.start() ? "upcoming"
|
||||
: now >= definition.end() ? "ended" : "active";
|
||||
}
|
||||
public OptionalInt nextThreshold() {
|
||||
return availability == Availability.OWNED ? milestones.stream().filter(m -> m.enabled() && m.threshold() > votes)
|
||||
.mapToInt(Milestone::threshold).min() : OptionalInt.empty();
|
||||
}
|
||||
public String awardState(int threshold) {
|
||||
if (availability != Availability.OWNED) return "progress unavailable";
|
||||
if (reserved.contains(threshold)) return "pending review";
|
||||
if (submitted.contains(threshold)) return "submitted";
|
||||
if (deferred.contains(threshold)) return "deferred";
|
||||
return votes >= threshold ? "reached" : "not reached";
|
||||
}
|
||||
}
|
||||
}
|
||||
+127
@@ -0,0 +1,127 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
+8
-7
@@ -1,7 +1,5 @@
|
||||
package com.bencodez.votingplugin.core.vote;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.util.UUID;
|
||||
|
||||
/** The accepted vote sequence. Platform operations are supplied by the receiving adapter. */
|
||||
@@ -67,12 +65,15 @@ public final class SharedVoteProcessor {
|
||||
boolean forceProxyRouting();
|
||||
boolean wasOnline();
|
||||
boolean realVote();
|
||||
default long currentTimeMillis() { return System.currentTimeMillis(); }
|
||||
boolean addTotals();
|
||||
boolean broadcastEnabled();
|
||||
boolean hasBroadcastHandler();
|
||||
void broadcast(UUID uuid, String name, String siteDisplayName, boolean online);
|
||||
boolean hasProxyTextTotals();
|
||||
UUID proxyVoteId();
|
||||
/** Local receipt identity, without implying proxy provenance. */
|
||||
default UUID localOccurrenceId() { return null; }
|
||||
default boolean identifiedQueuedProxyVote() { return false; }
|
||||
default boolean proxyQueueClassificationKnown() { return false; }
|
||||
default boolean proxyDelayValidationKnown() { return false; }
|
||||
@@ -105,6 +106,7 @@ public final class SharedVoteProcessor {
|
||||
int enabledSiteCount();
|
||||
void setMonthTotal(U user, int total);
|
||||
void milestones(U user, UUID voteId, boolean forceProxyRouting);
|
||||
default void dateMilestones(U user, S site, long voteTime, UUID voteId) { }
|
||||
void cooldown(U user, S site);
|
||||
void voteStreak(U user, long voteTime, UUID voteId);
|
||||
void postVote(S site, U user, String playerName, long voteTime, UUID voteId, boolean cached);
|
||||
@@ -186,10 +188,8 @@ public final class SharedVoteProcessor {
|
||||
+ (legacyRecordedProxyVote ? "; legacy timestamp matches LastVotes: " + ops.incomingTime()
|
||||
: "; stable vote ID identifies this queued delivery: " + ops.proxyVoteId()));
|
||||
}
|
||||
UUID voteId = UUID.randomUUID();
|
||||
if (ops.proxyVote() && ops.proxyVoteId() != null) {
|
||||
voteId = ops.proxyVoteId();
|
||||
}
|
||||
UUID voteId = ops.proxyVote() ? ops.proxyVoteId() : ops.localOccurrenceId();
|
||||
if (voteId == null) voteId = UUID.randomUUID();
|
||||
String userId = ops.userId(user);
|
||||
ops.cache(user);
|
||||
ops.updateName(user);
|
||||
@@ -217,7 +217,7 @@ public final class SharedVoteProcessor {
|
||||
voteTime = ops.incomingTime();
|
||||
} else {
|
||||
ops.setTimeNow(user, site);
|
||||
voteTime = LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
|
||||
voteTime = ops.currentTimeMillis();
|
||||
}
|
||||
boolean cached = false;
|
||||
if (SharedVoteDelivery.shouldDeliverNow(ops::proxyVote, () -> ops.userOnline(user),
|
||||
@@ -251,6 +251,7 @@ public final class SharedVoteProcessor {
|
||||
}
|
||||
}
|
||||
ops.milestones(user, voteId, ops.forceProxyRouting());
|
||||
ops.dateMilestones(user, site, voteTime, voteId);
|
||||
ops.cooldown(user, site);
|
||||
ops.voteStreak(user, voteTime, voteId);
|
||||
ops.postVote(site, user, playerName, voteTime, voteId, cached);
|
||||
|
||||
+247
@@ -0,0 +1,247 @@
|
||||
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,9 +18,182 @@ import com.bencodez.votingplugin.signs.SignHandler;
|
||||
import com.bencodez.votingplugin.timequeue.VoteTimeQueue;
|
||||
import com.bencodez.votingplugin.topvoter.TopVoter;
|
||||
|
||||
public class ServerData {
|
||||
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"));
|
||||
}
|
||||
|
||||
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.
|
||||
@@ -29,6 +202,7 @@ public class ServerData {
|
||||
*/
|
||||
public ServerData(VotingPluginMain plugin) {
|
||||
this.plugin = plugin;
|
||||
this.generationFence = plugin.getServerDataPublicationFence();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -36,13 +210,15 @@ public class ServerData {
|
||||
*
|
||||
* @param placeholder the placeholder to add
|
||||
*/
|
||||
public void addAutoCachedPlaceholder(String placeholder) {
|
||||
List<String> p = getAutoCachedPlaceholder();
|
||||
|
||||
if (!ArrayUtils.containsIgnoreCase(p, placeholder)) {
|
||||
p.add(placeholder);
|
||||
setAutoCachedPlaceholder(p);
|
||||
}
|
||||
public void addAutoCachedPlaceholder(String placeholder) {
|
||||
mutateData(() -> {
|
||||
List<String> p = getAutoCachedPlaceholder();
|
||||
|
||||
if (!ArrayUtils.containsIgnoreCase(p, placeholder)) {
|
||||
p.add(placeholder);
|
||||
setAutoCachedPlaceholder(p);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -50,12 +226,14 @@ public class ServerData {
|
||||
*
|
||||
* @param site the service site to add
|
||||
*/
|
||||
public synchronized void addServiceSite(String site) {
|
||||
ArrayList<String> l = getServiceSites();
|
||||
if (!getServiceSites().contains(site)) {
|
||||
l.add(site);
|
||||
}
|
||||
setServiceSites(ArrayUtils.removeDuplicates(l));
|
||||
public void addServiceSite(String site) {
|
||||
mutateData(() -> {
|
||||
ArrayList<String> l = getServiceSites();
|
||||
if (!getServiceSites().contains(site)) {
|
||||
l.add(site);
|
||||
}
|
||||
setServiceSites(ArrayUtils.removeDuplicates(l));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -65,19 +243,20 @@ public class ServerData {
|
||||
* @param data the data
|
||||
* @param position the position
|
||||
*/
|
||||
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)));
|
||||
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)));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -87,10 +266,14 @@ public class ServerData {
|
||||
* @param vote the vote time queue entry
|
||||
*/
|
||||
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();
|
||||
mutateData(() -> {
|
||||
getData().set("TimedVoteCache." + num + ".Name", vote.getName());
|
||||
getData().set("TimedVoteCache." + num + ".Service", vote.getService());
|
||||
getData().set("TimedVoteCache." + num + ".Time", vote.getTime());
|
||||
getData().set("TimedVoteCache." + num + ".LocalOccurrenceId", vote.getLocalOccurrenceId() == null ? null : vote.getLocalOccurrenceId().toString());
|
||||
getData().set("TimedVoteCache." + num + ".CanonicalOccurrenceTime", vote.getCanonicalOccurrenceTime() == 0L ? null : vote.getCanonicalOccurrenceTime());
|
||||
saveTimedVoteCache();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -98,16 +281,28 @@ public class ServerData {
|
||||
*
|
||||
* @param ident the vote shop identifier
|
||||
*/
|
||||
public void addVoteShopPurchase(String ident) {
|
||||
setVoteShopPurchases(ident, (getVoteShopPurchases(ident) + 1));
|
||||
public void addVoteShopPurchase(String ident) {
|
||||
mutateData(() -> {
|
||||
setVoteShopPurchases(ident, (getVoteShopPurchases(ident) + 1));
|
||||
});
|
||||
}
|
||||
|
||||
/** Assign a legacy local cache row its identity before replay is scheduled. */
|
||||
public void setTimedVoteLocalOccurrenceId(String key, UUID occurrenceId) {
|
||||
mutateData(() -> {
|
||||
getData().set("TimedVoteCache." + key + ".LocalOccurrenceId", occurrenceId.toString());
|
||||
saveTimedVoteCache();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Clears the timed vote cache.
|
||||
*/
|
||||
public void clearTimedVoteCache() {
|
||||
getData().set("TimedVoteCache", null);
|
||||
saveData();
|
||||
public void clearTimedVoteCache() {
|
||||
mutateData(() -> {
|
||||
getData().set("TimedVoteCache", null);
|
||||
saveTimedVoteCache();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -142,13 +337,15 @@ public class ServerData {
|
||||
*
|
||||
* @return the 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;
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -165,9 +362,10 @@ public class ServerData {
|
||||
*
|
||||
* @return the service sites
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public ArrayList<String> getServiceSites() {
|
||||
return (ArrayList<String>) getData().getList("GottenServiceSites", new ArrayList<>());
|
||||
public ArrayList<String> getServiceSites() {
|
||||
synchronized (publicationMonitor()) {
|
||||
return new ArrayList<>(getData().getStringList("GottenServiceSites"));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -176,9 +374,11 @@ public class ServerData {
|
||||
*
|
||||
* @return persisted service-site observations
|
||||
*/
|
||||
public synchronized List<String> getServiceSitesReadOnly() {
|
||||
ConfigurationSection root = plugin.getServerDataFile().getData().getConfigurationSection("VotingPlugin");
|
||||
return root == null ? List.of() : List.copyOf(root.getStringList("GottenServiceSites"));
|
||||
public List<String> getServiceSitesReadOnly() {
|
||||
synchronized (publicationMonitor()) {
|
||||
ConfigurationSection root = getFile().getData().getConfigurationSection("VotingPlugin");
|
||||
return root == null ? List.of() : List.copyOf(root.getStringList("GottenServiceSites"));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -339,8 +539,11 @@ public class ServerData {
|
||||
/**
|
||||
* Reload data.
|
||||
*/
|
||||
public void reloadData() {
|
||||
plugin.getServerDataFile().reloadData();
|
||||
public void reloadData() {
|
||||
mutateData(() -> {
|
||||
getFile().reloadData();
|
||||
captureVotePartyDisplay();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -359,36 +562,168 @@ public class ServerData {
|
||||
* @param top the top voter type
|
||||
* @param messageId the message ID
|
||||
*/
|
||||
public void setTopVoterMessageId(TopVoter top, long messageId) {
|
||||
getData().set("DiscordSRV.TopVoterMessageId." + top.toString(), messageId);
|
||||
saveData();
|
||||
public void setTopVoterMessageId(TopVoter top, long messageId) {
|
||||
mutateSavedData(() -> {
|
||||
getData().set("DiscordSRV.TopVoterMessageId." + top.toString(), messageId);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
/**
|
||||
* 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) {
|
||||
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();
|
||||
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);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Save data.
|
||||
*/
|
||||
public synchronized void saveData() {
|
||||
plugin.getServerDataFile().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());
|
||||
if (vote.getLocalOccurrenceId() != null) fields.put("LocalOccurrenceId", vote.getLocalOccurrenceId().toString());
|
||||
if (vote.getCanonicalOccurrenceTime() != 0L) fields.put("CanonicalOccurrenceTime", vote.getCanonicalOccurrenceTime());
|
||||
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());
|
||||
getData().set(path + ".LocalOccurrenceId", vote.getLocalOccurrenceId() == null ? null : vote.getLocalOccurrenceId().toString());
|
||||
getData().set(path + ".CanonicalOccurrenceTime", vote.getCanonicalOccurrenceTime() == 0L ? null : vote.getCanonicalOccurrenceTime());
|
||||
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();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -396,13 +731,10 @@ 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());
|
||||
}
|
||||
getData().set("DisabledReminders", uuids);
|
||||
saveData();
|
||||
public void saveDisabledReminders(ArrayList<UUID> disabledReminders) {
|
||||
ArrayList<String> uuids = new ArrayList<>();
|
||||
for (UUID uuid : disabledReminders) uuids.add(uuid.toString());
|
||||
setStringList("DisabledReminders", uuids);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -410,9 +742,8 @@ public class ServerData {
|
||||
*
|
||||
* @param placeholders the list of placeholders
|
||||
*/
|
||||
public void setAutoCachedPlaceholder(List<String> placeholders) {
|
||||
getData().set("AutoCachePlaceholders", placeholders);
|
||||
saveData();
|
||||
public void setAutoCachedPlaceholder(List<String> placeholders) {
|
||||
setStringList("AutoCachePlaceholders", placeholders);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -420,9 +751,8 @@ public class ServerData {
|
||||
*
|
||||
* @param current the current vote count
|
||||
*/
|
||||
public void setBungeeVotePartyCurrent(int current) {
|
||||
getData().set("BungeeVotePartyCurrent", current);
|
||||
saveData();
|
||||
public void setBungeeVotePartyCurrent(int current) {
|
||||
setInt("BungeeVotePartyCurrent", current);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -430,9 +760,8 @@ public class ServerData {
|
||||
*
|
||||
* @param required the required vote count
|
||||
*/
|
||||
public void setBungeeVotePartyRequired(int required) {
|
||||
getData().set("BungeeVotePartyRequired", required);
|
||||
saveData();
|
||||
public void setBungeeVotePartyRequired(int required) {
|
||||
setInt("BungeeVotePartyRequired", required);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -440,9 +769,8 @@ public class ServerData {
|
||||
*
|
||||
* @param list the service sites list
|
||||
*/
|
||||
public void setServiceSites(ArrayList<String> list) {
|
||||
getData().set("GottenServiceSites", list);
|
||||
saveData();
|
||||
public void setServiceSites(ArrayList<String> list) {
|
||||
setStringList("GottenServiceSites", list);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -450,9 +778,10 @@ public class ServerData {
|
||||
*
|
||||
* @param value the converted status
|
||||
*/
|
||||
public void setShopConverted(boolean value) {
|
||||
getData().set("VoteShopConverted", value);
|
||||
saveData();
|
||||
public void setShopConverted(boolean value) {
|
||||
mutateSavedData(() -> {
|
||||
getData().set("VoteShopConverted", value);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -464,21 +793,15 @@ 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) {
|
||||
|
||||
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();
|
||||
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");
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -487,21 +810,20 @@ public class ServerData {
|
||||
* @param count the sign count
|
||||
* @param skullLocation the skull location
|
||||
*/
|
||||
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());
|
||||
}
|
||||
public void setSkullLocation(String count, Location skullLocation) {
|
||||
if (skullLocation == null) return;
|
||||
var coordinates = SignCoordinates.capture(skullLocation);
|
||||
mutateData(() -> coordinates.store(getData(), "Signs." + count + ".Skull"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the version.
|
||||
*/
|
||||
public void setVersion() {
|
||||
getData().set("Version", Bukkit.getVersion());
|
||||
saveData();
|
||||
public void setVersion() {
|
||||
String version = Bukkit.getVersion();
|
||||
mutateSavedData(() -> {
|
||||
getData().set("Version", version);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -509,9 +831,10 @@ public class ServerData {
|
||||
*
|
||||
* @param value the extra required votes
|
||||
*/
|
||||
public void setVotePartyExtraRequired(int value) {
|
||||
getData().set("VotePartyExtraRequired", value);
|
||||
saveData();
|
||||
public void setVotePartyExtraRequired(int value) {
|
||||
mutateSavedData(() -> {
|
||||
getData().set("VotePartyExtraRequired", value);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -520,42 +843,45 @@ public class ServerData {
|
||||
* @param ident the vote shop identifier
|
||||
* @param amount the purchase amount
|
||||
*/
|
||||
public void setVoteShopPurchases(String ident, int amount) {
|
||||
getData().set("VoteShopPurchases." + ident, amount);
|
||||
saveData();
|
||||
public void setVoteShopPurchases(String ident, int amount) {
|
||||
mutateSavedData(() -> {
|
||||
getData().set("VoteShopPurchases." + ident, amount);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the last vote party timestamp to today.
|
||||
*/
|
||||
public void updateLastVoteParty() {
|
||||
getData().set("LastVoteParty", plugin.getTimeChecker().getTime().getDayOfYear());
|
||||
saveData();
|
||||
public void updateLastVoteParty() {
|
||||
int day = plugin.getTimeChecker().getTime().getDayOfYear();
|
||||
setInt("LastVoteParty", day);
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the last vote party week timestamp to this week.
|
||||
*/
|
||||
public void updateLastVotePartyWeek() {
|
||||
getData().set("LastVotePartyWeek",
|
||||
plugin.getTimeChecker().getTime().get(WeekFields.of(Locale.getDefault()).weekOfYear()));
|
||||
saveData();
|
||||
public void updateLastVotePartyWeek() {
|
||||
int week = plugin.getTimeChecker().getTime().get(WeekFields.of(Locale.getDefault()).weekOfYear());
|
||||
setInt("LastVotePartyWeek", week);
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates placeholders to lowercase format.
|
||||
*/
|
||||
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();
|
||||
}
|
||||
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);
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -3,10 +3,8 @@ 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;
|
||||
|
||||
@@ -27,6 +25,7 @@ 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;
|
||||
@@ -40,8 +39,45 @@ public class DiscordHandler {
|
||||
private final VotingPluginMain plugin;
|
||||
@Getter
|
||||
private final HashMap<TopVoter, Long> topVoterMessageIds = new HashMap<TopVoter, Long>();
|
||||
private final Set<TopVoter> recoveringTopVoters = new HashSet<>();
|
||||
/** 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 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.
|
||||
@@ -149,14 +185,347 @@ public class DiscordHandler {
|
||||
* @param top the top voter
|
||||
*/
|
||||
public void updateTopVoterMessageId(TopVoter top) {
|
||||
plugin.extraDebug("Updating Discord Top Voter message for: " + top);
|
||||
prepareTopVoterMessage(top, plugin.getTopVoterDisplayGeneration());
|
||||
}
|
||||
|
||||
long channelId = plugin.getConfigFile().getDiscordSRVTopVoterChannel(top);
|
||||
LinkedHashMap<TopVoterPlayer, Integer> topVoters = plugin.getTopVoter(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); }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
String title = plugin.getConfigFile().getDiscordSRVTopVoterTitle(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;
|
||||
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()) {
|
||||
@@ -187,34 +556,7 @@ public class DiscordHandler {
|
||||
eb.setDescription(sb.toString()).setFooter("Top 10 • Updated");
|
||||
}
|
||||
|
||||
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));
|
||||
}
|
||||
return eb;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -224,41 +566,65 @@ public class DiscordHandler {
|
||||
* condition as recoverable so one deleted message cannot permanently stop
|
||||
* leaderboard updates.
|
||||
*/
|
||||
private void handleMessageUpdateFailure(TopVoter top, TextChannel channel, EmbedBuilder eb, long existingId,
|
||||
Throwable error) {
|
||||
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;
|
||||
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(); }
|
||||
}
|
||||
}
|
||||
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());
|
||||
});
|
||||
} catch (RuntimeException rejected) {
|
||||
try { if (currentGeneration(generation)) warnLeaderboardFailure("worker admission"); }
|
||||
finally { discarded.run(); }
|
||||
}
|
||||
}
|
||||
|
||||
private void handleMessageUpdateFailure(TopVoter top, TextChannel channel, Publication publication,
|
||||
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;
|
||||
}
|
||||
|
||||
plugin.getLogger().warning("Error editing Top Voters " + top + ": " + error.getMessage());
|
||||
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 (again) finish(top, publication);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -13,6 +13,11 @@ import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
public class PlayerPostVoteEvent extends Event {
|
||||
|
||||
/** Original accepted occurrence time; ordinary cooldown/event time remains separate. */
|
||||
@Getter
|
||||
@Setter
|
||||
private Long canonicalOccurrenceTime;
|
||||
|
||||
/** The Constant handlers. */
|
||||
private static final HandlerList handlers = new HandlerList();
|
||||
@@ -77,6 +82,11 @@ public class PlayerPostVoteEvent extends Event {
|
||||
@Setter
|
||||
private UUID voteUUID;
|
||||
|
||||
/** Original explicit proxy transport ID; voteUUID retains the legacy correlation fallback. */
|
||||
@Getter
|
||||
@Setter
|
||||
private UUID proxyVoteId;
|
||||
|
||||
/**
|
||||
* Constructs a new PlayerPostVoteEvent.
|
||||
*
|
||||
|
||||
@@ -2,6 +2,7 @@ package com.bencodez.votingplugin.events;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
import org.bukkit.event.Cancellable;
|
||||
import org.bukkit.event.Event;
|
||||
import org.bukkit.event.HandlerList;
|
||||
|
||||
@@ -12,7 +13,23 @@ import com.bencodez.votingplugin.votesites.VoteSite;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
public class PlayerVoteEvent extends Event {
|
||||
/**
|
||||
* Fired before VotingPlugin processes a player vote.
|
||||
*
|
||||
* <p>Cancellation follows Bukkit's {@code ignoreCancelled} dispatch contract.
|
||||
* Integrations must cancel before the MONITOR vote consumer runs.</p>
|
||||
*/
|
||||
public class PlayerVoteEvent extends Event implements Cancellable {
|
||||
|
||||
/** Stable local receipt identity, separate from proxy transport provenance. */
|
||||
@Getter
|
||||
@Setter
|
||||
private UUID localOccurrenceId;
|
||||
|
||||
/** Original accepted occurrence time; ordinary cooldown/event time remains separate. */
|
||||
@Getter
|
||||
@Setter
|
||||
private Long canonicalOccurrenceTime;
|
||||
|
||||
/** The Constant handlers. */
|
||||
private static final HandlerList handlers = new HandlerList();
|
||||
@@ -38,7 +55,7 @@ public class PlayerVoteEvent extends Event {
|
||||
@Setter
|
||||
private VoteTotalsSnapshot bungeeTextTotals;
|
||||
|
||||
/** Stable identity supplied by a proxy delivery, independent of totals. */
|
||||
/** Original explicit proxy transport ID; null for legacy totals-only correlation. */
|
||||
@Getter
|
||||
@Setter
|
||||
private UUID proxyVoteId;
|
||||
@@ -79,6 +96,20 @@ public class PlayerVoteEvent extends Event {
|
||||
@Setter
|
||||
private boolean wasOnline;
|
||||
|
||||
/** Native receipt ownership is released only after the accepted consumer returns. */
|
||||
@Getter
|
||||
@Setter
|
||||
private boolean nativeProcessingStarted;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
private boolean nativeProcessingCompleted;
|
||||
|
||||
/** Missing date accounting is surfaced after event dispatch so durable proxy envelopes are not acknowledged. */
|
||||
@Getter
|
||||
@Setter
|
||||
private boolean dateMilestoneAccountingFailed;
|
||||
|
||||
/** Whether this is an identified queued proxy delivery. */
|
||||
@Getter
|
||||
@Setter
|
||||
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package com.bencodez.votingplugin.listeners;
|
||||
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.EventPriority;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.inventory.InventoryOpenEvent;
|
||||
import com.bencodez.advancedcore.api.inventory.GUISession;
|
||||
import com.bencodez.votingplugin.commands.gui.player.DateVoteEventsMenu;
|
||||
|
||||
/** Fence the actual platform open, including AdvancedCore's additional scheduling handoff. */
|
||||
public final class DateVoteMenuOpenGuard implements Listener {
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onOpen(InventoryOpenEvent event) {
|
||||
GUISession session = GUISession.extractSession(event.getInventory());
|
||||
if (session != null && !DateVoteEventsMenu.permitsOpen(session.getInventoryGUI(), event.getPlayer()))
|
||||
event.setCancelled(true);
|
||||
}
|
||||
}
|
||||
@@ -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().playerOnline(placeholderUuid(player), player);
|
||||
plugin.getPlaceholderPlayerPresence().captureOnline(placeholderUuid(player), player);
|
||||
}
|
||||
|
||||
private UUID placeholderUuid(Player player) {
|
||||
@@ -83,7 +83,7 @@ public class PlayerJoinEvent implements Listener {
|
||||
|
||||
Player player = event.getPlayer();
|
||||
if (player != null) {
|
||||
plugin.getPlaceholderPlayerPresence().playerOnline(user.getJavaUUID(), player);
|
||||
if (!plugin.getPlaceholderPlayerPresence().updateStorageUuid(user.getJavaUUID(), player)) return;
|
||||
}
|
||||
|
||||
if (player != null && plugin.isYmlError()) {
|
||||
@@ -160,17 +160,19 @@ 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(player.getUniqueId());
|
||||
VotingPluginMain.plugin.getAdvancedTab().remove(serverUuid);
|
||||
|
||||
// Use AdvancedCore UUIDLookup to derive the correct UUID (online/offline aware)
|
||||
String uuid = UuidLookup.getInstance().getUUID(player.getName());
|
||||
String uuid = UuidLookup.getInstance().getUUID(playerName);
|
||||
if (isBlank(uuid)) {
|
||||
// Fallback to online UUID if lookup fails
|
||||
uuid = player.getUniqueId().toString();
|
||||
uuid = serverUuid.toString();
|
||||
}
|
||||
|
||||
VotingPluginUser user = plugin.getVotingPluginUserManager().getVotingPluginUser(uuid);
|
||||
|
||||
+30
-3
@@ -32,7 +32,12 @@ public class PlayerVoteListener implements Listener {
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
|
||||
public void onplayerVote(PlayerVoteEvent event) {
|
||||
SharedVoteProcessor.process(new BukkitOperations(plugin, event));
|
||||
// Keep the production boundary defensive for direct/custom dispatchers
|
||||
// as well as Bukkit's Cancellable-aware event dispatcher.
|
||||
if (event.isCancelled()) return;
|
||||
BukkitOperations operations = new BukkitOperations(plugin, event);
|
||||
SharedVoteProcessor.process(operations);
|
||||
if (event.isNativeProcessingStarted()) event.setNativeProcessingCompleted(true);
|
||||
}
|
||||
|
||||
private static final class BukkitOperations implements SharedVoteProcessor.Operations<VoteSite, VotingPluginUser> {
|
||||
@@ -44,7 +49,11 @@ public class PlayerVoteListener implements Listener {
|
||||
this.event = event;
|
||||
}
|
||||
|
||||
@Override public boolean enabled() { return plugin.isEnabled(); }
|
||||
@Override public boolean enabled() {
|
||||
boolean enabled = plugin.isEnabled();
|
||||
if (enabled) event.setNativeProcessingStarted(true);
|
||||
return enabled;
|
||||
}
|
||||
@Override public String incomingName() { return event.getPlayer(); }
|
||||
@Override public String serviceSite() { return event.getServiceSite(); }
|
||||
@Override public void debug(String message) { plugin.debug(message); }
|
||||
@@ -95,7 +104,7 @@ public class PlayerVoteListener implements Listener {
|
||||
}
|
||||
@Override public boolean siteEnabled(VoteSite site) { return site.isEnabled(); }
|
||||
@Override public String siteKey(VoteSite site) { return site.getKey(); }
|
||||
@Override public String siteDisplayName(VoteSite site) { return site.getDisplayNameForFormatting(); }
|
||||
@Override public String siteDisplayName(VoteSite site) { return site.getDisplayName(); }
|
||||
@Override public VotingPluginUser resolveUser(String name) {
|
||||
if (event.getVotingPluginUser() != null) return event.getVotingPluginUser();
|
||||
Player player = Bukkit.getPlayerExact(name);
|
||||
@@ -128,6 +137,7 @@ public class PlayerVoteListener implements Listener {
|
||||
}
|
||||
@Override public boolean hasProxyTextTotals() { return event.getBungeeTextTotals() != null; }
|
||||
@Override public UUID proxyVoteId() { return resolveProxyVoteId(event); }
|
||||
@Override public UUID localOccurrenceId() { return event.getLocalOccurrenceId(); }
|
||||
@Override public boolean identifiedQueuedProxyVote() { return event.isQueuedProxyVote(); }
|
||||
@Override public boolean proxyQueueClassificationKnown() { return event.isProxyQueueClassificationKnown(); }
|
||||
@Override public boolean proxyDelayValidationKnown() { return event.isProxyDelayValidationKnown(); }
|
||||
@@ -173,6 +183,20 @@ public class PlayerVoteListener implements Listener {
|
||||
plugin.getVoteMilestonesManager().handleVote(user, event.getBungeeTextTotals(), forceProxyRouting,
|
||||
voteId, new HashMap<String, String>());
|
||||
}
|
||||
@Override public void dateMilestones(VotingPluginUser user, VoteSite site, long voteTime, UUID voteId) {
|
||||
long occurrenceTime = event.getCanonicalOccurrenceTime() == null
|
||||
? proxyVote() ? incomingTime() : voteTime : event.getCanonicalOccurrenceTime();
|
||||
if (com.bencodez.votingplugin.util.BukkitCompletionScheduler.isPlatformOwnedThread()) {
|
||||
// An asynchronous event flag does not identify the thread that dispatched it.
|
||||
// A proxy caller cannot acknowledge accounting that has only been admitted.
|
||||
event.setDateMilestoneAccountingFailed(!plugin.getDateVoteMilestones().deferAccepted(user, site.getKey(), voteId, occurrenceTime,
|
||||
realVote(), proxyVote(), event.getProxyVoteId() != null && occurrenceTime > 0,
|
||||
targetedProxyVote(), forceProxyRouting()));
|
||||
return;
|
||||
}
|
||||
if (!plugin.getDateVoteMilestones().accepted(user, site.getKey(), voteId, occurrenceTime, realVote(), proxyVote(),
|
||||
event.getProxyVoteId() != null && occurrenceTime > 0, targetedProxyVote(), forceProxyRouting())) event.setDateMilestoneAccountingFailed(true);
|
||||
}
|
||||
@Override public void cooldown(VotingPluginUser user, VoteSite site) { plugin.getCoolDownCheck().vote(user, site); }
|
||||
@Override public void voteStreak(VotingPluginUser user, long voteTime, UUID voteId) {
|
||||
plugin.getVoteStreakHandler().processVote(user, voteTime, voteId);
|
||||
@@ -181,6 +205,9 @@ public class PlayerVoteListener implements Listener {
|
||||
long voteTime, UUID voteId, boolean cached) {
|
||||
PlayerPostVoteEvent post = new PlayerPostVoteEvent(site, user, event.isRealVote(), event.isForceBungee(),
|
||||
voteTime, cached, site.getServiceSite(), user.getJavaUUID(), playerName, voteId);
|
||||
post.setProxyVoteId(event.getProxyVoteId());
|
||||
post.setCanonicalOccurrenceTime(event.getCanonicalOccurrenceTime() == null
|
||||
? event.isBungee() ? event.getTime() : voteTime : event.getCanonicalOccurrenceTime());
|
||||
plugin.getServer().getPluginManager().callEvent(post);
|
||||
}
|
||||
@Override public boolean placeholderCacheAlways() { return plugin.getConfigFile().getPlaceholderCacheLevel().isCacheAlways(); }
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
package com.bencodez.votingplugin.listeners;
|
||||
|
||||
import java.util.concurrent.RejectedExecutionException;
|
||||
import java.util.UUID;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.EventPriority;
|
||||
@@ -17,16 +20,133 @@ import com.vexsoftware.votifier.model.VotifierEvent;
|
||||
|
||||
public class VotiferEvent implements Listener {
|
||||
|
||||
private VotingPluginMain plugin;
|
||||
private final VotingPluginMain plugin;
|
||||
private final java.util.function.BooleanSupplier ready;
|
||||
private volatile boolean accepting = true;
|
||||
private static final int MAX_CAPTURED = VotifierVoteOverflowQueue.MAX_CAPTURED;
|
||||
private boolean retirementQueued;
|
||||
private final Object captureLock = new Object();
|
||||
// Receipt ownership only. Entries leave at completed processing or confirmed
|
||||
// overflow transfer; STARTED work remains owned until then.
|
||||
private final Map<UUID, CapturedVote> captured = new LinkedHashMap<>();
|
||||
private static final class CapturedVote {
|
||||
final String username, site;
|
||||
final long occurredAt;
|
||||
final UUID id;
|
||||
boolean transferring, transferFailureReported;
|
||||
volatile boolean started, completed, finished, transferred;
|
||||
VotifierVoteOverflowQueue recoveryOwner;
|
||||
CapturedVote(String username, String site, long occurredAt, UUID id) {
|
||||
this.username = username; this.site = site; this.occurredAt = occurredAt; this.id = id;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Instantiates a new votifer event.
|
||||
*
|
||||
* @param plugin the plugin
|
||||
*/
|
||||
public VotiferEvent(VotingPluginMain plugin) {
|
||||
this.plugin = plugin;
|
||||
}
|
||||
public VotiferEvent(VotingPluginMain plugin) { this(plugin, () -> true); }
|
||||
|
||||
public VotiferEvent(VotingPluginMain plugin, java.util.function.BooleanSupplier ready) {
|
||||
this.plugin = plugin; this.ready = ready;
|
||||
}
|
||||
/** Retire admission and reconcile tasks before the vote executor is cancelled. */
|
||||
public void stop() {
|
||||
synchronized (captureLock) {
|
||||
accepting = false;
|
||||
if (retirementQueued) return;
|
||||
retirementQueued = true;
|
||||
var overflow = plugin.getVotifierVoteOverflowQueue();
|
||||
if (overflow == null) {
|
||||
for (CapturedVote vote : java.util.List.copyOf(captured.values())) transferLocked(vote);
|
||||
return;
|
||||
}
|
||||
var snapshot = captured.values().stream().map(vote -> new VotifierVoteOverflowQueue.RetiringCapture(
|
||||
vote.username, vote.site, vote.occurredAt, vote.id,
|
||||
() -> !vote.started || vote.finished && !vote.completed, () -> vote.completed,
|
||||
admitted -> transferred(vote, admitted))).toList();
|
||||
overflow.retireCaptures(snapshot);
|
||||
}
|
||||
}
|
||||
|
||||
public int getPendingCaptureCount() {
|
||||
synchronized (captureLock) { return captured.size(); }
|
||||
}
|
||||
|
||||
private void runCaptured(CapturedVote vote) {
|
||||
synchronized (captureLock) {
|
||||
if (!captured.containsKey(vote.id) || vote.transferring || vote.started) return;
|
||||
if (!accepting || !ready.getAsBoolean()) {
|
||||
if (accepting || !retirementQueued) transferLocked(vote);
|
||||
return;
|
||||
}
|
||||
vote.started = true;
|
||||
}
|
||||
boolean completed = false;
|
||||
try { completed = processCapturedVote(vote.site, vote.username, vote.occurredAt, vote.id)
|
||||
&& !Thread.currentThread().isInterrupted(); }
|
||||
finally {
|
||||
VotifierVoteOverflowQueue acknowledge = null;
|
||||
synchronized (captureLock) {
|
||||
vote.completed = completed;
|
||||
vote.finished = true;
|
||||
if (completed) {
|
||||
captured.remove(vote.id);
|
||||
if (vote.transferred) acknowledge = vote.recoveryOwner;
|
||||
} else if (accepting && !vote.transferred && !vote.transferring) {
|
||||
// Retain the same occurrence and hand it to recovery after
|
||||
// the normal callback has finished, including partial failures.
|
||||
transferLocked(vote);
|
||||
}
|
||||
}
|
||||
if (completed && vote.recoveryOwner != null) vote.recoveryOwner.releaseCapture(vote.id);
|
||||
if (acknowledge != null) acknowledge.acknowledgeOccurrence(vote.id);
|
||||
else if (vote.transferred && vote.recoveryOwner != null) vote.recoveryOwner.resumeTransfers();
|
||||
}
|
||||
}
|
||||
|
||||
private void transferLocked(CapturedVote vote) {
|
||||
if (vote.transferring) return;
|
||||
vote.transferring = true;
|
||||
VotifierVoteOverflowQueue overflow = vote.recoveryOwner != null
|
||||
? vote.recoveryOwner : plugin.getVotifierVoteOverflowQueue();
|
||||
vote.recoveryOwner = overflow;
|
||||
if (overflow == null) { transferred(vote, false); return; }
|
||||
overflow.enqueueAfterInitialization(vote.username, vote.site, vote.occurredAt, vote.id,
|
||||
() -> !vote.started || vote.finished && !vote.completed,
|
||||
accepted -> transferred(vote, accepted));
|
||||
}
|
||||
|
||||
private void transferred(CapturedVote vote, boolean admitted) {
|
||||
boolean completed, retry, reportFailure;
|
||||
synchronized (captureLock) {
|
||||
if (vote.transferred && !admitted) return; // Older failure cannot revoke confirmed queue ownership.
|
||||
vote.transferred = admitted; completed = vote.completed;
|
||||
if (!admitted) vote.transferring = false;
|
||||
if (admitted || completed) captured.remove(vote.id);
|
||||
retry = !admitted && !completed && captured.get(vote.id) == vote;
|
||||
reportFailure = !admitted && !completed && !vote.transferFailureReported;
|
||||
if (reportFailure) vote.transferFailureReported = true;
|
||||
}
|
||||
if (admitted && completed) vote.recoveryOwner.acknowledgeOccurrence(vote.id);
|
||||
if (completed) return; // Current normal processing won; do not leave an ordinary duplicate retry.
|
||||
if (reportFailure) plugin.getLogger().severe("Votifier vote queue unavailable or full; "
|
||||
+ (retry ? "captured receipt retained for retry for " : "vote was not admitted for ")
|
||||
+ MinecraftUsernameValidator.sanitizeForLog(vote.username));
|
||||
else if (admitted) plugin.getLogger().warning("Vote pipeline unavailable or retiring; queued Votifier vote for retry");
|
||||
if (retry && vote.recoveryOwner != null) vote.recoveryOwner.retryCaptureTransfers(this::retryCapturedTransfers);
|
||||
}
|
||||
|
||||
private void retryCapturedTransfers() {
|
||||
synchronized (captureLock) {
|
||||
for (CapturedVote vote : java.util.List.copyOf(captured.values())) {
|
||||
// Ordinary queued/running callbacks retain their original execution.
|
||||
// Only receipts which already attempted a failed handoff need retry.
|
||||
if (vote.transferFailureReported && !vote.transferring) transferLocked(vote);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Processes a validated vote. The overflow queue invokes this callback from
|
||||
@@ -35,7 +155,23 @@ public class VotiferEvent implements Listener {
|
||||
* @param voteSite the validated service site
|
||||
* @param voteUsername the validated player name
|
||||
*/
|
||||
public void processVote(String voteSite, String voteUsername) {
|
||||
public void processVote(String voteSite, String voteUsername) { processVote(voteSite, voteUsername, 0L); }
|
||||
|
||||
public void processVote(String voteSite, String voteUsername, long occurredAt) {
|
||||
processVote(voteSite, voteUsername, occurredAt, UUID.randomUUID());
|
||||
}
|
||||
|
||||
public void processVote(String voteSite, String voteUsername, long occurredAt, UUID localOccurrenceId) {
|
||||
processCapturedVote(voteSite, voteUsername, occurredAt, localOccurrenceId);
|
||||
}
|
||||
|
||||
/** False retains overflow ownership; partial ordinary effects may still have occurred. */
|
||||
public boolean processVoteConfirmed(String voteSite, String voteUsername, long occurredAt, UUID localOccurrenceId) {
|
||||
return processCapturedVote(voteSite, voteUsername, occurredAt, localOccurrenceId);
|
||||
}
|
||||
|
||||
private boolean processCapturedVote(String voteSite, String voteUsername, long occurredAt, UUID localOccurrenceId) {
|
||||
java.util.Objects.requireNonNull(localOccurrenceId, "localOccurrenceId");
|
||||
try {
|
||||
plugin.getServerData().addServiceSite(voteSite);
|
||||
if (plugin.getBungeeSettings().isUseBungeecoord() && !plugin.getBungeeSettings().isVotifierBypass()
|
||||
@@ -46,7 +182,7 @@ public class VotiferEvent implements Listener {
|
||||
|| plugin.getBackendProxyHandler().getMethod().equals(BungeeMethod.REDIS))) {
|
||||
plugin.getLogger().severe(
|
||||
"Ignoring vote from votifier since a proxy vote transport is enabled; receive votes on the proxy or enable VotifierBypass, then check: https://github.com/BenCodez/VotingPlugin/wiki/Bungeecord-Setups");
|
||||
return;
|
||||
return true;
|
||||
}
|
||||
|
||||
String matchSite = "";
|
||||
@@ -77,22 +213,29 @@ public class VotiferEvent implements Listener {
|
||||
if (plugin.getTimeChecker().isActiveProcessing()
|
||||
&& plugin.getConfigFile().isQueueVotesDuringTimeChange()) {
|
||||
plugin.debug("Adding vote to time queue " + voteUsername + "/" + voteSite);
|
||||
plugin.getTimeQueueHandler().addVote(voteUsername, voteSite);
|
||||
return;
|
||||
plugin.getTimeQueueHandler().addVote(voteUsername, voteSite, occurredAt, localOccurrenceId);
|
||||
return true;
|
||||
}
|
||||
|
||||
String voteSiteName = plugin.getVoteSiteManager().getVoteSiteName(true, serviceSite, matchSite);
|
||||
|
||||
PlayerVoteEvent voteEvent = new PlayerVoteEvent(
|
||||
plugin.getVoteSiteManager().getVoteSite(voteSiteName, true), voteUsername, voteSite, true);
|
||||
voteEvent.setLocalOccurrenceId(localOccurrenceId);
|
||||
if (occurredAt > 0) voteEvent.setCanonicalOccurrenceTime(occurredAt);
|
||||
plugin.getServer().getPluginManager().callEvent(voteEvent);
|
||||
|
||||
if (voteEvent.isCancelled()) {
|
||||
plugin.debug("Vote cancelled");
|
||||
}
|
||||
// Bukkit may skip disabled listeners or catch their exceptions while
|
||||
// returning normally. Dispatch alone is not confirmed processing.
|
||||
return voteEvent.isNativeProcessingCompleted()
|
||||
|| voteEvent.isCancelled() && !voteEvent.isNativeProcessingStarted();
|
||||
} catch (Exception e) {
|
||||
plugin.getLogger().severe("Error occured during vote processing");
|
||||
e.printStackTrace();
|
||||
return false; // An exception does not prove ordinary accounting/rewards completed.
|
||||
}
|
||||
}
|
||||
|
||||
@@ -103,6 +246,9 @@ public class VotiferEvent implements Listener {
|
||||
*/
|
||||
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
|
||||
public void onVotiferEvent(VotifierEvent event) {
|
||||
if (!accepting) return;
|
||||
final long occurredAt = System.currentTimeMillis();
|
||||
final UUID localOccurrenceId = UUID.randomUUID();
|
||||
|
||||
Vote vote = event.getVote();
|
||||
String str = vote.getServiceName();
|
||||
@@ -135,16 +281,58 @@ public class VotiferEvent implements Listener {
|
||||
plugin.debug("VoteSite: " + voteSite);
|
||||
plugin.debug("IP: " + IP);
|
||||
|
||||
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 "
|
||||
+ MinecraftUsernameValidator.sanitizeForLog(voteUsername));
|
||||
} else {
|
||||
plugin.getLogger().warning("Vote executor saturated; queued Votifier vote for retry");
|
||||
}
|
||||
}
|
||||
CapturedVote capturedVote = new CapturedVote(voteUsername, voteSite, occurredAt, localOccurrenceId);
|
||||
VotifierVoteOverflowQueue.CaptureAdmission admission;
|
||||
synchronized (captureLock) {
|
||||
if (!accepting) return;
|
||||
var overflow = plugin.getVotifierVoteOverflowQueue();
|
||||
capturedVote.recoveryOwner = overflow;
|
||||
if (captured.size() >= MAX_CAPTURED) {
|
||||
// The overflow owns its independent bounded admission lane.
|
||||
transferLocked(capturedVote);
|
||||
return;
|
||||
}
|
||||
admission = overflow == null ? VotifierVoteOverflowQueue.CaptureAdmission.ACCEPTED
|
||||
: overflow.reserveCapture(localOccurrenceId);
|
||||
if (admission == VotifierVoteOverflowQueue.CaptureAdmission.REJECTED) {
|
||||
plugin.getLogger().severe("Votifier capture capacity unavailable; vote was not admitted");
|
||||
return;
|
||||
}
|
||||
// Reserve known capacity and publish capture ownership together with
|
||||
// respect to stop's snapshot. Unknown capacity remains provisional.
|
||||
captured.put(localOccurrenceId, capturedVote);
|
||||
}
|
||||
if (admission == VotifierVoteOverflowQueue.CaptureAdmission.WAITING_FOR_LOAD) {
|
||||
capturedVote.recoveryOwner.reserveCaptureAfterInitialization(localOccurrenceId,
|
||||
admitted -> admitCaptured(capturedVote, admitted));
|
||||
} else admitCaptured(capturedVote, true);
|
||||
}
|
||||
|
||||
private void admitCaptured(CapturedVote vote, boolean admitted) {
|
||||
synchronized (captureLock) {
|
||||
if (captured.get(vote.id) != vote) {
|
||||
if (admitted && vote.recoveryOwner != null) vote.recoveryOwner.releaseCapture(vote.id);
|
||||
return;
|
||||
}
|
||||
if (!admitted) {
|
||||
captured.remove(vote.id);
|
||||
plugin.getLogger().severe("Votifier capture capacity unavailable; vote was not admitted");
|
||||
return;
|
||||
}
|
||||
if (!accepting) {
|
||||
if (!retirementQueued) transferLocked(vote);
|
||||
return;
|
||||
}
|
||||
}
|
||||
try {
|
||||
var timer = plugin.getVoteTimer();
|
||||
if (timer == null) {
|
||||
synchronized (captureLock) { transferLocked(vote); }
|
||||
return;
|
||||
}
|
||||
timer.submit(() -> runCaptured(vote));
|
||||
} catch (RejectedExecutionException rejected) {
|
||||
synchronized (captureLock) { transferLocked(vote); }
|
||||
}
|
||||
}
|
||||
}
|
||||
+632
-26
@@ -4,6 +4,9 @@ import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.channels.SeekableByteChannel;
|
||||
import java.nio.channels.FileChannel;
|
||||
import java.nio.channels.FileLock;
|
||||
import java.nio.channels.OverlappingFileLockException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.AtomicMoveNotSupportedException;
|
||||
import java.nio.file.Files;
|
||||
@@ -17,10 +20,15 @@ import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.Properties;
|
||||
import java.util.UUID;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.concurrent.RejectedExecutionException;
|
||||
import java.util.concurrent.ScheduledThreadPoolExecutor;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import org.bukkit.configuration.file.YamlConfiguration;
|
||||
|
||||
@@ -37,22 +45,65 @@ import com.bencodez.votingplugin.util.ServiceSiteValidator;
|
||||
public final class VotifierVoteOverflowQueue implements AutoCloseable {
|
||||
/* Keep the overflow bounded independently of the executor's 256 admissions. */
|
||||
private static final int MAX_ENTRIES = 256;
|
||||
public static final int MAX_CAPTURED = 256;
|
||||
private static final int MAX_RETAINED_ENTRIES = MAX_ENTRIES + MAX_CAPTURED;
|
||||
private static final long MAX_FILE_BYTES = 4L * 1024L * 1024L;
|
||||
private static final long RETRY_DELAY_MILLIS = 250L;
|
||||
private static final String QUEUE_FILE = "VotifierVoteQueue.yml";
|
||||
private static final String OWNER_FILE = "VotifierVoteQueue.yml.owner";
|
||||
private static final String SHARED_OWNER_PROPERTY_PREFIX = "com.bencodez.votingplugin.VotifierVoteOverflowQueue.owner.";
|
||||
private static final int MAX_OWNER_RESERVATIONS = 1024;
|
||||
|
||||
private final VotingPluginMain plugin;
|
||||
private final BiConsumer<String, String> processor;
|
||||
@FunctionalInterface
|
||||
public interface VoteProcessor { void process(String serviceSite, String username, long occurredAt); }
|
||||
@FunctionalInterface
|
||||
public interface OccurrenceProcessor {
|
||||
void process(String serviceSite, String username, long occurredAt, UUID localOccurrenceId);
|
||||
/** Legacy callbacks confirm completion by returning normally. */
|
||||
default boolean processConfirmed(String serviceSite, String username, long occurredAt, UUID localOccurrenceId) {
|
||||
process(serviceSite, username, occurredAt, localOccurrenceId);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@FunctionalInterface
|
||||
public interface ConfirmedOccurrenceProcessor {
|
||||
boolean processConfirmed(String serviceSite, String username, long occurredAt, UUID localOccurrenceId);
|
||||
}
|
||||
private final OccurrenceProcessor processor;
|
||||
private final java.util.function.BooleanSupplier processingAllowed;
|
||||
private final Path file;
|
||||
private final Path ownerFile;
|
||||
private FileChannel ownerChannel;
|
||||
private FileLock ownerLock;
|
||||
private String ownerKey;
|
||||
private String ownerToken;
|
||||
private Properties ownerProperties;
|
||||
private final ScheduledThreadPoolExecutor worker;
|
||||
private final Object lock = new Object();
|
||||
private final Object persistenceWriteLock = new Object();
|
||||
private final ArrayDeque<PendingVote> entries = new ArrayDeque<>();
|
||||
private boolean drainScheduled;
|
||||
private boolean drainRetryScheduled;
|
||||
private boolean captureRetryScheduled;
|
||||
private boolean persistenceScheduled;
|
||||
private boolean persistenceDirty;
|
||||
private boolean started;
|
||||
private boolean closed;
|
||||
private boolean closing;
|
||||
private final java.util.concurrent.CompletableFuture<Void> closePublication = new java.util.concurrent.CompletableFuture<>();
|
||||
private boolean closeFailureReported;
|
||||
private volatile boolean loaded;
|
||||
private volatile boolean loadFailed;
|
||||
private int pendingIngress;
|
||||
private int pendingCaptureAdmissions;
|
||||
private int pendingRetirementCaptures;
|
||||
private boolean retirementRequested;
|
||||
private boolean initializationRetryScheduled;
|
||||
private boolean initializationFailureReported;
|
||||
private boolean queueFileObserved;
|
||||
private final Set<UUID> captureReservations = new java.util.HashSet<>();
|
||||
private final boolean asynchronousInitialization;
|
||||
private long stateVersion;
|
||||
private long durableVersion;
|
||||
|
||||
@@ -63,16 +114,56 @@ public final class VotifierVoteOverflowQueue implements AutoCloseable {
|
||||
* @param processor callback receiving service site and player name
|
||||
*/
|
||||
public VotifierVoteOverflowQueue(VotingPluginMain plugin, BiConsumer<String, String> processor) {
|
||||
this(plugin, (site, user, occurredAt, id) -> processor.accept(site, user), () -> true);
|
||||
}
|
||||
|
||||
/** Additive callback retains receipt occurrence and fences a retired startup generation. */
|
||||
public VotifierVoteOverflowQueue(VotingPluginMain plugin, VoteProcessor processor,
|
||||
java.util.function.BooleanSupplier processingAllowed) {
|
||||
this(plugin, (site, user, time, id) -> processor.process(site, user, time), processingAllowed);
|
||||
}
|
||||
|
||||
public VotifierVoteOverflowQueue(VotingPluginMain plugin, OccurrenceProcessor processor,
|
||||
java.util.function.BooleanSupplier processingAllowed) {
|
||||
this(plugin, processor, processingAllowed, false);
|
||||
}
|
||||
|
||||
/** Memory-only construction; all loading and handoffs run on the existing queue worker. */
|
||||
public static VotifierVoteOverflowQueue initializeAsync(VotingPluginMain plugin, OccurrenceProcessor processor,
|
||||
java.util.function.BooleanSupplier processingAllowed) {
|
||||
return new VotifierVoteOverflowQueue(plugin, processor, processingAllowed, true);
|
||||
}
|
||||
|
||||
/** Named factory preserves existing void callback/lambda contracts without ambiguous overloads. */
|
||||
public static VotifierVoteOverflowQueue initializeConfirmedAsync(VotingPluginMain plugin,
|
||||
ConfirmedOccurrenceProcessor processor, java.util.function.BooleanSupplier processingAllowed) {
|
||||
java.util.Objects.requireNonNull(processor, "processor");
|
||||
return initializeAsync(plugin, new OccurrenceProcessor() {
|
||||
@Override public void process(String site, String user, long time, UUID id) {
|
||||
processor.processConfirmed(site, user, time, id);
|
||||
}
|
||||
@Override public boolean processConfirmed(String site, String user, long time, UUID id) {
|
||||
return processor.processConfirmed(site, user, time, id);
|
||||
}
|
||||
}, processingAllowed);
|
||||
}
|
||||
|
||||
private VotifierVoteOverflowQueue(VotingPluginMain plugin, OccurrenceProcessor processor,
|
||||
java.util.function.BooleanSupplier processingAllowed, boolean asynchronousInitialization) {
|
||||
this.asynchronousInitialization = asynchronousInitialization;
|
||||
this.plugin = plugin;
|
||||
this.processor = processor;
|
||||
this.processingAllowed = processingAllowed;
|
||||
this.file = new File(plugin.getDataFolder(), QUEUE_FILE).toPath();
|
||||
this.ownerFile = new File(plugin.getDataFolder(), OWNER_FILE).toPath();
|
||||
this.worker = new ScheduledThreadPoolExecutor(1, runnable -> {
|
||||
Thread thread = new Thread(runnable, "VotingPlugin-Votifier-Overflow");
|
||||
thread.setDaemon(true);
|
||||
return thread;
|
||||
});
|
||||
this.worker.setRemoveOnCancelPolicy(true);
|
||||
load();
|
||||
if (asynchronousInitialization) worker.execute(this::load);
|
||||
else load();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -97,10 +188,88 @@ public final class VotifierVoteOverflowQueue implements AutoCloseable {
|
||||
* @return false when the bounded overflow is full or shutting down
|
||||
*/
|
||||
public boolean enqueue(String username, String serviceSite) {
|
||||
if (username == null || serviceSite == null) return false;
|
||||
return enqueue(username, serviceSite, System.currentTimeMillis());
|
||||
}
|
||||
|
||||
public boolean enqueue(String username, String serviceSite, long occurredAt) {
|
||||
return enqueue(username, serviceSite, occurredAt, UUID.randomUUID());
|
||||
}
|
||||
|
||||
public boolean enqueue(String username, String serviceSite, long occurredAt, UUID localOccurrenceId) {
|
||||
return enqueueStored(username, serviceSite, occurredAt, localOccurrenceId, false);
|
||||
}
|
||||
|
||||
/** Transfer stays behind initial loading and is bounded independently of executor admissions. */
|
||||
public void enqueueAfterInitialization(String username, String serviceSite, long occurredAt, UUID localOccurrenceId,
|
||||
Consumer<Boolean> completion) {
|
||||
enqueueAfterInitialization(username, serviceSite, occurredAt, localOccurrenceId, () -> true, completion);
|
||||
}
|
||||
|
||||
/** A STARTED original callback retains execution ownership until its outcome is known. */
|
||||
public void enqueueAfterInitialization(String username, String serviceSite, long occurredAt, UUID localOccurrenceId,
|
||||
java.util.function.BooleanSupplier executionReleased, Consumer<Boolean> completion) {
|
||||
if (username == null || serviceSite == null || occurredAt <= 0 || localOccurrenceId == null) {
|
||||
completion.accept(false);
|
||||
return;
|
||||
}
|
||||
var finished = new java.util.concurrent.atomic.AtomicBoolean();
|
||||
class Transfer implements Runnable {
|
||||
void finish(boolean accepted) {
|
||||
if (!finished.compareAndSet(false, true)) return;
|
||||
synchronized (lock) { pendingIngress--; }
|
||||
completion.accept(accepted);
|
||||
}
|
||||
@Override public void run() {
|
||||
try {
|
||||
synchronized (lock) {
|
||||
if (!closed && !loaded) {
|
||||
// Admission owns this receipt, including the saturated
|
||||
// path which has no entry in the listener's capture map.
|
||||
scheduleInitializationRetryLocked();
|
||||
worker.schedule(this, RETRY_DELAY_MILLIS, TimeUnit.MILLISECONDS);
|
||||
return;
|
||||
}
|
||||
}
|
||||
} catch (RejectedExecutionException rejected) { finish(false); return; }
|
||||
boolean accepted = false;
|
||||
try { accepted = enqueueStored(username, serviceSite, occurredAt, localOccurrenceId, true, executionReleased); }
|
||||
finally { finish(accepted); }
|
||||
}
|
||||
}
|
||||
boolean submitted = false;
|
||||
synchronized (lock) {
|
||||
if (!closed && !closing && pendingIngress < MAX_ENTRIES) {
|
||||
pendingIngress++;
|
||||
try {
|
||||
worker.execute(new Transfer());
|
||||
submitted = true;
|
||||
} catch (RejectedExecutionException rejected) { pendingIngress--; }
|
||||
}
|
||||
}
|
||||
if (!submitted) completion.accept(false);
|
||||
}
|
||||
|
||||
private boolean enqueueStored(String username, String serviceSite, long occurredAt, UUID localOccurrenceId,
|
||||
boolean admittedTransfer) {
|
||||
return enqueueStored(username, serviceSite, occurredAt, localOccurrenceId, admittedTransfer, () -> true);
|
||||
}
|
||||
|
||||
private boolean enqueueStored(String username, String serviceSite, long occurredAt, UUID localOccurrenceId,
|
||||
boolean admittedTransfer, java.util.function.BooleanSupplier executionReleased) {
|
||||
if (username == null || serviceSite == null || occurredAt <= 0 || localOccurrenceId == null) return false;
|
||||
synchronized (lock) {
|
||||
if (closed || entries.size() >= MAX_ENTRIES) return false;
|
||||
entries.addLast(new PendingVote(username, serviceSite, System.currentTimeMillis()));
|
||||
if (closed || closing && !admittedTransfer || !loaded || loadFailed) return false;
|
||||
var existing = occurrence(localOccurrenceId);
|
||||
if (existing != null) {
|
||||
boolean same = matches(existing, username, serviceSite, occurredAt);
|
||||
if (same) captureReservations.remove(localOccurrenceId);
|
||||
return same;
|
||||
}
|
||||
int entryLimit = closing && admittedTransfer ? MAX_RETAINED_ENTRIES : MAX_ENTRIES;
|
||||
if (entries.size() >= entryLimit || !captureReservations.contains(localOccurrenceId)
|
||||
&& entries.size() + captureReservations.size() >= MAX_RETAINED_ENTRIES) return false;
|
||||
entries.addLast(new PendingVote(username, serviceSite, occurredAt, localOccurrenceId, executionReleased));
|
||||
captureReservations.remove(localOccurrenceId);
|
||||
stateVersion++;
|
||||
requestPersistenceLocked();
|
||||
scheduleDrainLocked();
|
||||
@@ -108,6 +277,162 @@ public final class VotifierVoteOverflowQueue implements AutoCloseable {
|
||||
}
|
||||
}
|
||||
|
||||
public enum CaptureAdmission { ACCEPTED, WAITING_FOR_LOAD, REJECTED }
|
||||
|
||||
/** Reserve final-snapshot capacity before the normal executor owns this receipt. */
|
||||
public CaptureAdmission reserveCapture(UUID id) {
|
||||
java.util.Objects.requireNonNull(id);
|
||||
synchronized (lock) {
|
||||
if (closed || closing || loadFailed) return CaptureAdmission.REJECTED;
|
||||
if (!loaded) return CaptureAdmission.WAITING_FOR_LOAD;
|
||||
if (captureReservations.contains(id)) return CaptureAdmission.ACCEPTED;
|
||||
if (captureReservations.size() >= MAX_CAPTURED
|
||||
|| entries.size() + captureReservations.size() >= MAX_RETAINED_ENTRIES)
|
||||
return CaptureAdmission.REJECTED;
|
||||
captureReservations.add(id);
|
||||
return CaptureAdmission.ACCEPTED;
|
||||
}
|
||||
}
|
||||
|
||||
/** Unknown disk capacity is provisional; keep at most one deferred admission per capture. */
|
||||
public void reserveCaptureAfterInitialization(UUID id, Consumer<Boolean> completion) {
|
||||
java.util.Objects.requireNonNull(id); java.util.Objects.requireNonNull(completion);
|
||||
boolean admitted;
|
||||
synchronized (lock) {
|
||||
admitted = !closed && !closing && pendingCaptureAdmissions < MAX_CAPTURED;
|
||||
if (admitted) pendingCaptureAdmissions++;
|
||||
}
|
||||
if (!admitted) { completion.accept(false); return; }
|
||||
var finished = new java.util.concurrent.atomic.AtomicBoolean();
|
||||
class Admission implements Runnable {
|
||||
void finish(boolean accepted) {
|
||||
if (!finished.compareAndSet(false, true)) return;
|
||||
synchronized (lock) { pendingCaptureAdmissions--; }
|
||||
completion.accept(accepted);
|
||||
}
|
||||
@Override public void run() {
|
||||
var result = reserveCapture(id);
|
||||
if (result != CaptureAdmission.WAITING_FOR_LOAD) {
|
||||
finish(result == CaptureAdmission.ACCEPTED);
|
||||
return;
|
||||
}
|
||||
try { worker.schedule(this, RETRY_DELAY_MILLIS, TimeUnit.MILLISECONDS); }
|
||||
catch (RejectedExecutionException rejected) { finish(false); }
|
||||
}
|
||||
}
|
||||
var admission = new Admission();
|
||||
try { worker.execute(admission); }
|
||||
catch (RejectedExecutionException rejected) { admission.finish(false); }
|
||||
}
|
||||
|
||||
public void releaseCapture(UUID id) {
|
||||
synchronized (lock) { captureReservations.remove(id); }
|
||||
}
|
||||
|
||||
public record RetiringCapture(String username, String serviceSite, long time, UUID id,
|
||||
java.util.function.BooleanSupplier executionReleased,
|
||||
java.util.function.BooleanSupplier completed, Consumer<Boolean> completion) {
|
||||
public RetiringCapture {
|
||||
java.util.Objects.requireNonNull(username); java.util.Objects.requireNonNull(serviceSite);
|
||||
java.util.Objects.requireNonNull(id); java.util.Objects.requireNonNull(executionReleased);
|
||||
java.util.Objects.requireNonNull(completed); java.util.Objects.requireNonNull(completion);
|
||||
if (time <= 0) throw new IllegalArgumentException("capture receipt time must be positive");
|
||||
}
|
||||
}
|
||||
|
||||
/** One FIFO batch, before close's final snapshot; normal overflow admission stays capped at256. */
|
||||
public void retireCaptures(List<RetiringCapture> captures) {
|
||||
var snapshot = List.copyOf(captures);
|
||||
if (snapshot.size() > MAX_CAPTURED) throw new IllegalArgumentException("capture retirement exceeds capacity");
|
||||
if (snapshot.isEmpty()) return;
|
||||
class Transfer implements Runnable {
|
||||
@Override public void run() {
|
||||
synchronized (lock) {
|
||||
if (!closed && (!loaded || loadFailed)) {
|
||||
scheduleInitializationRetryLocked();
|
||||
worker.schedule(this, RETRY_DELAY_MILLIS, TimeUnit.MILLISECONDS);
|
||||
return;
|
||||
}
|
||||
}
|
||||
boolean[] results = new boolean[snapshot.size()];
|
||||
try {
|
||||
for (int index = 0; index < snapshot.size(); index++) {
|
||||
var capture = snapshot.get(index);
|
||||
boolean completed = false;
|
||||
try { completed = capture.completed().getAsBoolean(); }
|
||||
catch (RuntimeException | Error unknown) { /* Retain unconfirmed completion. */ }
|
||||
synchronized (lock) {
|
||||
if (!closed && loaded && !loadFailed) {
|
||||
var existing = occurrence(capture.id());
|
||||
if (completed) {
|
||||
captureReservations.remove(capture.id());
|
||||
results[index] = true;
|
||||
} else if (existing != null) {
|
||||
results[index] = matches(existing, capture.username(), capture.serviceSite(), capture.time());
|
||||
if (results[index]) captureReservations.remove(capture.id());
|
||||
} else if (entries.size() < MAX_RETAINED_ENTRIES
|
||||
&& (captureReservations.contains(capture.id())
|
||||
|| entries.size() + captureReservations.size() < MAX_RETAINED_ENTRIES)) {
|
||||
entries.addLast(new PendingVote(capture.username(), capture.serviceSite(), capture.time(),
|
||||
capture.id(), capture.executionReleased()));
|
||||
captureReservations.remove(capture.id());
|
||||
stateVersion++; requestPersistenceLocked();
|
||||
results[index] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Retain the whole batch before any external completion callback.
|
||||
for (int index = 0; index < snapshot.size(); index++) {
|
||||
try { snapshot.get(index).completion().accept(results[index]); }
|
||||
catch (RuntimeException | Error failure) {
|
||||
try { plugin.getLogger().warning("Votifier retirement callback failed; queue ownership is retained"); }
|
||||
catch (RuntimeException | Error ignored) { }
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
synchronized (lock) { pendingRetirementCaptures -= snapshot.size(); }
|
||||
}
|
||||
}
|
||||
}
|
||||
boolean submitted = false;
|
||||
synchronized (lock) {
|
||||
if (!closed && !closing && pendingRetirementCaptures + snapshot.size() <= MAX_CAPTURED) {
|
||||
pendingRetirementCaptures += snapshot.size();
|
||||
try { worker.execute(new Transfer()); retirementRequested = true; submitted = true; }
|
||||
catch (RejectedExecutionException rejected) { pendingRetirementCaptures -= snapshot.size(); }
|
||||
}
|
||||
}
|
||||
if (!submitted) for (var capture : snapshot) {
|
||||
try { capture.completion().accept(false); }
|
||||
catch (RuntimeException | Error ignored) { /* Reject every bounded caller, including the suffix. */ }
|
||||
}
|
||||
}
|
||||
|
||||
private void scheduleInitializationRetryLocked() {
|
||||
if (closed || initializationRetryScheduled || loaded && !loadFailed) return;
|
||||
initializationRetryScheduled = true;
|
||||
worker.schedule(() -> {
|
||||
synchronized (lock) {
|
||||
initializationRetryScheduled = false;
|
||||
if (closed) return;
|
||||
}
|
||||
load();
|
||||
}, RETRY_DELAY_MILLIS, TimeUnit.MILLISECONDS);
|
||||
}
|
||||
|
||||
private PendingVote occurrence(UUID id) {
|
||||
for (var vote : entries) if (vote.localOccurrenceId.equals(id)) return vote;
|
||||
return null;
|
||||
}
|
||||
|
||||
private static boolean matches(PendingVote vote, String username, String site, long time) {
|
||||
return vote.username.equals(username) && vote.serviceSite.equals(site) && vote.time == time;
|
||||
}
|
||||
|
||||
/** Completion only; transfers separately report load/capacity admission failure. */
|
||||
public boolean isInitializationComplete() { return loaded; }
|
||||
|
||||
/**
|
||||
* Returns the number of votes waiting for admission or completion.
|
||||
*
|
||||
@@ -126,7 +451,7 @@ public final class VotifierVoteOverflowQueue implements AutoCloseable {
|
||||
}
|
||||
|
||||
private void scheduleDrainLocked() {
|
||||
if (closed || !started || drainScheduled) return;
|
||||
if (closed || closing || !loaded || loadFailed || !started || drainScheduled) return;
|
||||
drainScheduled = true;
|
||||
try {
|
||||
worker.schedule(this::drain, 0, TimeUnit.MILLISECONDS);
|
||||
@@ -137,7 +462,14 @@ public final class VotifierVoteOverflowQueue implements AutoCloseable {
|
||||
|
||||
private void drain() {
|
||||
while (true) {
|
||||
// A generation fence parks its receipts instead of repeatedly submitting
|
||||
// callbacks which are forbidden to execute (including inline submitters).
|
||||
if (!processingAllowed.getAsBoolean()) {
|
||||
synchronized (lock) { drainScheduled = false; }
|
||||
return;
|
||||
}
|
||||
synchronized (lock) {
|
||||
if (closed || closing || !loaded || loadFailed) { drainScheduled = false; return; }
|
||||
if (durableVersion != stateVersion) {
|
||||
drainScheduled = false;
|
||||
return;
|
||||
@@ -152,10 +484,23 @@ public final class VotifierVoteOverflowQueue implements AutoCloseable {
|
||||
// Serialize admission with enqueue so the version proven durable
|
||||
// above cannot change in the gap before submit accepts this vote.
|
||||
plugin.getVoteTimer().submit(() -> {
|
||||
boolean attempted = false;
|
||||
boolean completed = false;
|
||||
try {
|
||||
processor.accept(pending.serviceSite, pending.username);
|
||||
if (!processingAllowed.getAsBoolean()) return;
|
||||
synchronized (lock) {
|
||||
if (closed || closing || !entries.contains(pending)) return;
|
||||
}
|
||||
attempted = true;
|
||||
completed = processor.processConfirmed(pending.serviceSite, pending.username,
|
||||
pending.time, pending.localOccurrenceId) && !Thread.currentThread().isInterrupted();
|
||||
} catch (RuntimeException | Error failure) {
|
||||
plugin.getLogger().warning("Queued Votifier processing failed; retained receipt for retry: "
|
||||
+ failure.getClass().getSimpleName());
|
||||
throw failure;
|
||||
} finally {
|
||||
acknowledge(pending);
|
||||
if (completed) acknowledge(pending);
|
||||
else retainFailedAttempt(pending, attempted);
|
||||
}
|
||||
});
|
||||
} catch (RejectedExecutionException rejected) {
|
||||
@@ -168,27 +513,102 @@ public final class VotifierVoteOverflowQueue implements AutoCloseable {
|
||||
// The queue is closing; the persisted entry remains for restart.
|
||||
}
|
||||
return;
|
||||
} catch (RuntimeException | Error failure) {
|
||||
// An inline submitter can expose callback failure on this worker.
|
||||
// Retain retry ownership without leaving drainScheduled stuck true.
|
||||
drainScheduled = false;
|
||||
retainFailedAttempt(pending, true);
|
||||
throw failure;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private PendingVote nextUnsubmittedLocked() {
|
||||
long now = System.nanoTime();
|
||||
boolean retryWaiting = false;
|
||||
for (PendingVote pending : entries) {
|
||||
if (!pending.submitted) return pending;
|
||||
if (pending.submitted || !pending.executionReleased.getAsBoolean()) continue;
|
||||
if (pending.retryNotBeforeNanos != 0 && now - pending.retryNotBeforeNanos < 0) {
|
||||
retryWaiting = true;
|
||||
continue;
|
||||
}
|
||||
return pending;
|
||||
}
|
||||
if (retryWaiting) scheduleDrainRetryLocked();
|
||||
return null;
|
||||
}
|
||||
|
||||
private void retainFailedAttempt(PendingVote pending, boolean attempted) {
|
||||
synchronized (lock) {
|
||||
pending.submitted = false;
|
||||
if (closed || closing || !entries.contains(pending) || !attempted) return;
|
||||
// Inline submitters must not retry this same receipt in the current drain.
|
||||
pending.retryNotBeforeNanos = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(RETRY_DELAY_MILLIS);
|
||||
scheduleDrainRetryLocked();
|
||||
}
|
||||
}
|
||||
|
||||
private void scheduleDrainRetryLocked() {
|
||||
if (closed || closing || !loaded || loadFailed || !started || drainRetryScheduled) return;
|
||||
drainRetryScheduled = true;
|
||||
try {
|
||||
worker.schedule(() -> {
|
||||
synchronized (lock) {
|
||||
drainRetryScheduled = false;
|
||||
scheduleDrainLocked();
|
||||
}
|
||||
}, RETRY_DELAY_MILLIS, TimeUnit.MILLISECONDS);
|
||||
} catch (RejectedExecutionException rejected) { drainRetryScheduled = false; }
|
||||
}
|
||||
|
||||
private void acknowledge(PendingVote pending) {
|
||||
synchronized (lock) {
|
||||
entries.remove(pending);
|
||||
if (closed) {
|
||||
plugin.getLogger().warning("Completed Votifier callback outlived queue shutdown; retained occurrence requires reconciliation");
|
||||
return;
|
||||
}
|
||||
if (!entries.remove(pending)) return;
|
||||
stateVersion++;
|
||||
requestPersistenceLocked();
|
||||
scheduleDrainLocked();
|
||||
}
|
||||
}
|
||||
|
||||
/** Reconcile a receipt whose original normal callback completed during transfer. */
|
||||
public void acknowledgeOccurrence(UUID localOccurrenceId) {
|
||||
synchronized (lock) {
|
||||
if (closed) {
|
||||
// A nonterminating callback outlived the final snapshot. A retired
|
||||
// writer cannot overwrite a successor's queue; retain uncertainty.
|
||||
plugin.getLogger().warning("Completed Votifier callback outlived queue shutdown; retained occurrence requires reconciliation");
|
||||
return;
|
||||
}
|
||||
if (!entries.removeIf(pending -> pending.localOccurrenceId.equals(localOccurrenceId))) return;
|
||||
stateVersion++; requestPersistenceLocked(); scheduleDrainLocked();
|
||||
}
|
||||
}
|
||||
/** Wake the same bounded drain when an original transferred callback finishes uncertainly. */
|
||||
public void resumeTransfers() { scheduleDrain(); }
|
||||
|
||||
/** One wakeup for the ingress listener's bounded failed-transfer captures.
|
||||
* Retry runs outside the queue monitor and never adds another executor or waiter list. */
|
||||
public void retryCaptureTransfers(Runnable retry) {
|
||||
synchronized (lock) {
|
||||
if (closed || closing || captureRetryScheduled) return;
|
||||
captureRetryScheduled = true;
|
||||
try {
|
||||
worker.schedule(() -> {
|
||||
synchronized (lock) {
|
||||
captureRetryScheduled = false;
|
||||
if (closed || closing) return;
|
||||
}
|
||||
retry.run();
|
||||
}, RETRY_DELAY_MILLIS, TimeUnit.MILLISECONDS);
|
||||
} catch (RejectedExecutionException rejected) { captureRetryScheduled = false; }
|
||||
}
|
||||
}
|
||||
|
||||
private void requestPersistenceLocked() {
|
||||
persistenceDirty = true;
|
||||
if (persistenceScheduled) return;
|
||||
@@ -239,18 +659,32 @@ public final class VotifierVoteOverflowQueue implements AutoCloseable {
|
||||
}
|
||||
|
||||
private void load() {
|
||||
ArrayDeque<PendingVote> recovered = new ArrayDeque<>();
|
||||
boolean successful = false;
|
||||
try {
|
||||
if (!Files.exists(file, LinkOption.NOFOLLOW_LINKS)) return;
|
||||
synchronized (lock) { if (closed || loaded && !loadFailed) return; }
|
||||
if (!acquireOwner()) {
|
||||
synchronized (lock) {
|
||||
if (asynchronousInitialization && !closing || pendingRetirementCaptures > 0 || pendingIngress > 0) {
|
||||
scheduleInitializationRetryLocked();
|
||||
return;
|
||||
}
|
||||
}
|
||||
throw new IOException("queue file is owned by another active instance");
|
||||
}
|
||||
if (!Files.exists(file, LinkOption.NOFOLLOW_LINKS)) {
|
||||
if (queueFileObserved) throw new IOException("queue file disappeared before recovery");
|
||||
successful = true;
|
||||
return;
|
||||
}
|
||||
queueFileObserved = true;
|
||||
YamlConfiguration yaml = new YamlConfiguration();
|
||||
yaml.loadFromString(readQueueFile());
|
||||
Object raw = yaml.get("Votes");
|
||||
if (!(raw instanceof List<?> values)) return;
|
||||
if (!(raw instanceof List<?> values)) throw new IOException("queue votes are not a list");
|
||||
if (values.size() > MAX_RETAINED_ENTRIES) throw new IOException("queue exceeds entry capacity");
|
||||
boolean skipped = false;
|
||||
for (Object value : values) {
|
||||
if (entries.size() >= MAX_ENTRIES) {
|
||||
skipped = true;
|
||||
break;
|
||||
}
|
||||
if (!(value instanceof Map<?, ?> map)) {
|
||||
skipped = true;
|
||||
continue;
|
||||
@@ -265,16 +699,111 @@ public final class VotifierVoteOverflowQueue implements AutoCloseable {
|
||||
skipped = true;
|
||||
continue;
|
||||
}
|
||||
entries.addLast(new PendingVote(name, site, timestamp.longValue()));
|
||||
UUID localOccurrenceId;
|
||||
if (!map.containsKey("LocalOccurrenceId")) {
|
||||
localOccurrenceId = UUID.randomUUID();
|
||||
skipped = true; // Publish the migration before admitting any recovered row.
|
||||
} else {
|
||||
Object rawId = map.get("LocalOccurrenceId");
|
||||
try {
|
||||
if (!(rawId instanceof String id)) throw new IllegalArgumentException();
|
||||
localOccurrenceId = UUID.fromString(id);
|
||||
if (!localOccurrenceId.toString().equalsIgnoreCase(id)) throw new IllegalArgumentException();
|
||||
} catch (IllegalArgumentException malformed) {
|
||||
skipped = true;
|
||||
continue; // Explicit corrupt IDs cannot become fresh occurrences.
|
||||
}
|
||||
}
|
||||
recovered.addLast(new PendingVote(name, site, timestamp.longValue(), localOccurrenceId));
|
||||
}
|
||||
synchronized (lock) { entries.clear(); entries.addAll(recovered); }
|
||||
if (skipped) {
|
||||
synchronized (lock) {
|
||||
stateVersion++;
|
||||
requestPersistenceLocked();
|
||||
}
|
||||
}
|
||||
successful = true;
|
||||
} catch (Exception failure) {
|
||||
plugin.getLogger().warning("Unable to load queued Votifier votes: " + failure.getClass().getSimpleName());
|
||||
loadFailed = true;
|
||||
if (!initializationFailureReported) {
|
||||
initializationFailureReported = true;
|
||||
plugin.getLogger().warning("Unable to load queued Votifier votes: " + failure.getClass().getSimpleName());
|
||||
}
|
||||
} finally {
|
||||
if (ownerLock == null && !loadFailed) return;
|
||||
if (successful) loadFailed = false;
|
||||
loaded = true;
|
||||
synchronized (lock) {
|
||||
scheduleDrainLocked();
|
||||
if (loadFailed && pendingRetirementCaptures > 0) scheduleInitializationRetryLocked();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private boolean acquireOwner() throws IOException {
|
||||
if (ownerLock != null && ownerLock.isValid()) return true;
|
||||
Path parent = ownerFile.toAbsolutePath().normalize().getParent();
|
||||
if (parent == null || Files.isSymbolicLink(ownerFile)) throw new IOException("queue ownership file is unsafe");
|
||||
Files.createDirectories(parent);
|
||||
String key = SHARED_OWNER_PROPERTY_PREFIX + hashOwnerPath(parent.toRealPath().resolve(ownerFile.getFileName()));
|
||||
String token = UUID.randomUUID().toString();
|
||||
Properties properties = System.getProperties();
|
||||
synchronized (properties) {
|
||||
if (properties.getProperty(key) != null) return false;
|
||||
int reservations = 0;
|
||||
for (Object property : properties.keySet())
|
||||
if (property instanceof String name && name.startsWith(SHARED_OWNER_PROPERTY_PREFIX)) reservations++;
|
||||
if (reservations >= MAX_OWNER_RESERVATIONS) return false;
|
||||
properties.setProperty(key, token);
|
||||
}
|
||||
try {
|
||||
FileChannel channel = FileChannel.open(ownerFile, StandardOpenOption.CREATE, StandardOpenOption.WRITE,
|
||||
LinkOption.NOFOLLOW_LINKS);
|
||||
try {
|
||||
FileLock acquired;
|
||||
try { acquired = channel.tryLock(); }
|
||||
catch (OverlappingFileLockException busy) { acquired = null; }
|
||||
if (acquired == null) { channel.close(); clearOwnerReservation(properties, key, token); return false; }
|
||||
ownerKey = key; ownerToken = token; ownerProperties = properties; ownerChannel = channel; ownerLock = acquired;
|
||||
return true;
|
||||
} catch (IOException | RuntimeException failure) {
|
||||
channel.close();
|
||||
clearOwnerReservation(properties, key, token);
|
||||
throw failure;
|
||||
}
|
||||
} catch (IOException | RuntimeException failure) {
|
||||
clearOwnerReservation(properties, key, token);
|
||||
throw failure;
|
||||
}
|
||||
}
|
||||
|
||||
private void releaseOwner() {
|
||||
try { if (ownerLock != null) ownerLock.release(); } catch (IOException ignored) { }
|
||||
try { if (ownerChannel != null) ownerChannel.close(); } catch (IOException ignored) { }
|
||||
clearOwnerReservation(ownerProperties, ownerKey, ownerToken);
|
||||
ownerLock = null;
|
||||
ownerChannel = null;
|
||||
ownerKey = null;
|
||||
ownerToken = null;
|
||||
ownerProperties = null;
|
||||
}
|
||||
|
||||
private static void clearOwnerReservation(Properties properties, String key, String token) {
|
||||
if (properties == null || key == null || token == null) return;
|
||||
synchronized (properties) {
|
||||
if (token.equals(properties.getProperty(key))) properties.remove(key);
|
||||
}
|
||||
}
|
||||
|
||||
private static String hashOwnerPath(Path path) throws IOException {
|
||||
try {
|
||||
byte[] digest = MessageDigest.getInstance("SHA-256").digest(path.toString().getBytes(StandardCharsets.UTF_8));
|
||||
StringBuilder result = new StringBuilder(digest.length * 2);
|
||||
for (byte value : digest) result.append(String.format("%02x", value));
|
||||
return result.toString();
|
||||
} catch (NoSuchAlgorithmException impossible) {
|
||||
throw new IOException("SHA-256 unavailable", impossible);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -298,6 +827,8 @@ public final class VotifierVoteOverflowQueue implements AutoCloseable {
|
||||
}
|
||||
|
||||
private void writeSnapshotLocked(List<PendingVote> snapshot) throws IOException {
|
||||
if (ownerLock == null || !ownerLock.isValid()) throw new IOException("queue file ownership is unavailable");
|
||||
if (snapshot.size() > MAX_RETAINED_ENTRIES) throw new IOException("queue snapshot exceeds entry capacity");
|
||||
YamlConfiguration yaml = new YamlConfiguration();
|
||||
List<Map<String, Object>> values = new ArrayList<>();
|
||||
for (PendingVote pending : snapshot) {
|
||||
@@ -305,6 +836,7 @@ public final class VotifierVoteOverflowQueue implements AutoCloseable {
|
||||
value.put("Username", pending.username);
|
||||
value.put("ServiceSite", pending.serviceSite);
|
||||
value.put("Time", pending.time);
|
||||
value.put("LocalOccurrenceId", pending.localOccurrenceId.toString());
|
||||
values.add(value);
|
||||
}
|
||||
yaml.set("Votes", values);
|
||||
@@ -330,21 +862,26 @@ public final class VotifierVoteOverflowQueue implements AutoCloseable {
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
List<PendingVote> snapshot;
|
||||
List<PendingVote> snapshot = null;
|
||||
boolean initializedWorker;
|
||||
synchronized (lock) {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
// At-least-once delivery: retain any unacknowledged callback. A callback
|
||||
// interrupted during shutdown must be replayed rather than silently lost.
|
||||
snapshot = new ArrayList<>(entries);
|
||||
persistenceScheduled = false;
|
||||
initializedWorker = asynchronousInitialization || retirementRequested || pendingIngress > 0;
|
||||
if (!initializedWorker) {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
// Legacy callers keep their existing close path until retirement admission.
|
||||
snapshot = new ArrayList<>(entries);
|
||||
persistenceScheduled = false;
|
||||
}
|
||||
}
|
||||
if (initializedWorker) { closeInitializedWorker(); return; }
|
||||
worker.shutdownNow();
|
||||
try {
|
||||
worker.awaitTermination(1, TimeUnit.SECONDS);
|
||||
} catch (InterruptedException interrupted) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
if (loadFailed) { releaseOwner(); return; }
|
||||
try {
|
||||
synchronized (persistenceWriteLock) {
|
||||
writeSnapshotLocked(snapshot);
|
||||
@@ -353,18 +890,87 @@ public final class VotifierVoteOverflowQueue implements AutoCloseable {
|
||||
plugin.getLogger().warning("Unable to persist queued Votifier votes during shutdown: "
|
||||
+ failure.getClass().getSimpleName());
|
||||
}
|
||||
releaseOwner();
|
||||
}
|
||||
|
||||
private void closeInitializedWorker() {
|
||||
synchronized (lock) {
|
||||
if (!closing && !closed) {
|
||||
closing = true;
|
||||
// Keep the existing worker and file owner through failed final publication.
|
||||
worker.execute(this::finishClosePublication);
|
||||
}
|
||||
}
|
||||
try { closePublication.get(1, TimeUnit.SECONDS); }
|
||||
catch (java.util.concurrent.TimeoutException pending) {
|
||||
plugin.getLogger().warning("Votifier queue shutdown publication is still pending on its worker; recovery is unconfirmed");
|
||||
} catch (InterruptedException interrupted) { Thread.currentThread().interrupt(); }
|
||||
catch (java.util.concurrent.ExecutionException failure) {
|
||||
throw new IllegalStateException("Votifier queue shutdown publication failed", failure.getCause());
|
||||
}
|
||||
}
|
||||
|
||||
private void finishClosePublication() {
|
||||
List<PendingVote> snapshot;
|
||||
long version;
|
||||
synchronized (lock) {
|
||||
if (closed) return;
|
||||
if (pendingRetirementCaptures > 0 || pendingIngress > 0) {
|
||||
if (!loaded || loadFailed) scheduleInitializationRetryLocked();
|
||||
worker.schedule(this::finishClosePublication, RETRY_DELAY_MILLIS, TimeUnit.MILLISECONDS);
|
||||
return;
|
||||
}
|
||||
snapshot = new ArrayList<>(entries);
|
||||
version = stateVersion;
|
||||
}
|
||||
if (loadFailed || !loaded) {
|
||||
// Unreadable/unowned storage is unknown; never replace it with an empty guess.
|
||||
synchronized (lock) { closed = true; }
|
||||
releaseOwner(); worker.shutdown(); closePublication.complete(null);
|
||||
return;
|
||||
}
|
||||
try { synchronized (persistenceWriteLock) { writeSnapshotLocked(snapshot); } }
|
||||
catch (IOException failure) {
|
||||
if (!closeFailureReported) {
|
||||
closeFailureReported = true;
|
||||
try { plugin.getLogger().warning("Unable to publish final Votifier queue; its worker retains ownership for retry"); }
|
||||
catch (RuntimeException | Error ignored) { }
|
||||
}
|
||||
worker.schedule(this::finishClosePublication, RETRY_DELAY_MILLIS, TimeUnit.MILLISECONDS);
|
||||
return;
|
||||
}
|
||||
synchronized (lock) {
|
||||
// A confirmed original callback may have removed a receipt during IO.
|
||||
if (version != stateVersion) {
|
||||
worker.execute(this::finishClosePublication);
|
||||
return;
|
||||
}
|
||||
closed = true;
|
||||
durableVersion = version;
|
||||
}
|
||||
releaseOwner(); worker.shutdown(); closePublication.complete(null);
|
||||
}
|
||||
|
||||
private static final class PendingVote {
|
||||
private final String username;
|
||||
private final String serviceSite;
|
||||
private final long time;
|
||||
private final UUID localOccurrenceId;
|
||||
private final java.util.function.BooleanSupplier executionReleased;
|
||||
private boolean submitted;
|
||||
private long retryNotBeforeNanos;
|
||||
|
||||
private PendingVote(String username, String serviceSite, long time) {
|
||||
private PendingVote(String username, String serviceSite, long time, UUID localOccurrenceId) {
|
||||
this(username, serviceSite, time, localOccurrenceId, () -> true);
|
||||
}
|
||||
|
||||
private PendingVote(String username, String serviceSite, long time, UUID localOccurrenceId,
|
||||
java.util.function.BooleanSupplier executionReleased) {
|
||||
this.username = username;
|
||||
this.serviceSite = serviceSite;
|
||||
this.time = time;
|
||||
this.localOccurrenceId = localOccurrenceId;
|
||||
this.executionReleased = java.util.Objects.requireNonNull(executionReleased);
|
||||
}
|
||||
}
|
||||
}
|
||||
+212
@@ -0,0 +1,212 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
+240
@@ -0,0 +1,240 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
+267
-34
@@ -67,6 +67,8 @@ 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;
|
||||
@@ -130,6 +132,8 @@ public class PlaceHolders {
|
||||
public String getPlaceHolder(OfflinePlayer p, String identifier1, boolean javascript) {
|
||||
boolean forceProcess = false;
|
||||
boolean useCache = true;
|
||||
if (identifier1.regionMatches(true, 0, "DateVoteMilestones_", 0, "DateVoteMilestones_".length()))
|
||||
return getPlaceholderValue(p, identifier1, false, true, false);
|
||||
String identifier = identifier1.toLowerCase();
|
||||
boolean custom = false;
|
||||
if (identifier.endsWith("_process")
|
||||
@@ -168,7 +172,9 @@ public class PlaceHolders {
|
||||
* @param identifier the placeholder identifier
|
||||
* @return the placeholder value
|
||||
*/
|
||||
public String getPlaceHolder(Player p, String identifier) {
|
||||
public String getPlaceHolder(Player p, String identifier) {
|
||||
if (identifier.regionMatches(true, 0, "DateVoteMilestones_", 0, "DateVoteMilestones_".length()))
|
||||
return getPlaceholderValue(p, identifier, false, true, false);
|
||||
if (plugin.getConfigFile().isUseJavascriptPlaceholders()) {
|
||||
identifier = PlaceholderUtils.replaceJavascript(p, identifier);
|
||||
}
|
||||
@@ -185,7 +191,118 @@ 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) {
|
||||
// This family owns a bounded snapshot cache and preserves case-sensitive event IDs.
|
||||
// Bypass legacy cache enrollment/name resolution, which can perform storage work.
|
||||
String datePrefix = "DateVoteMilestones_";
|
||||
if (identifier.regionMatches(true, 0, datePrefix, 0, datePrefix.length())) {
|
||||
if (p == null) return "no player";
|
||||
var manager = plugin.getDateVoteMilestones();
|
||||
if (manager == null) return "unavailable";
|
||||
if (p instanceof Player online) {
|
||||
UUID storageId = plugin.getPlaceholderPlayerPresence().storageUuid(online);
|
||||
return storageId == null ? "unavailable" : manager.placeholder(storageId, identifier.substring(datePrefix.length()));
|
||||
}
|
||||
UUID playerId = p.getUniqueId();
|
||||
return playerId == null ? "unavailable" : manager.placeholder(playerId, p::getName, identifier.substring(datePrefix.length()));
|
||||
}
|
||||
if (plugin.getConfigFile().isUseJavascriptPlaceholders() && javascript && p != null) {
|
||||
identifier = PlaceholderUtils.replaceJavascript(p, identifier);
|
||||
}
|
||||
@@ -205,6 +322,12 @@ 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)) {
|
||||
@@ -420,6 +543,14 @@ public class PlaceHolders {
|
||||
}
|
||||
}.withDescription("Best monthly total").updateDataKey("HighestMonthlyTotal"));
|
||||
|
||||
placeholders.add(new PlaceHolder<VotingPluginUser>("DateVoteMilestones_") {
|
||||
@Override public String placeholderRequest(VotingPluginUser user, String identifier) {
|
||||
var manager = plugin.getDateVoteMilestones();
|
||||
return manager == null || user == null ? "unavailable"
|
||||
: manager.placeholder(user.getJavaUUID(), identifier.substring("DateVoteMilestones_".length()));
|
||||
}
|
||||
}.withDescription("Date event votes/next/status/award snapshots; loading and unavailable are distinct").useStartsWith());
|
||||
|
||||
placeholders.add(new PlaceHolder<VotingPluginUser>("DailyVoteStreak") {
|
||||
|
||||
@Override
|
||||
@@ -492,7 +623,8 @@ public class PlaceHolders {
|
||||
|
||||
@Override
|
||||
public String placeholderRequest(VotingPluginUser user, String identifier) {
|
||||
return Integer.toString(user.getPoints());
|
||||
Integer points = pointBalance(user);
|
||||
return points == null ? "..." : Integer.toString(points);
|
||||
}
|
||||
}.withDescription("User points").updateDataKey("Points"));
|
||||
|
||||
@@ -501,7 +633,8 @@ public class PlaceHolders {
|
||||
@Override
|
||||
public String placeholderRequest(VotingPluginUser user, String identifier) {
|
||||
NumberFormat numberFormat = NumberFormat.getNumberInstance(Locale.US);
|
||||
return numberFormat.format(user.getPoints());
|
||||
Integer points = pointBalance(user);
|
||||
return points == null ? "..." : numberFormat.format(points);
|
||||
}
|
||||
}.withDescription("User points").updateDataKey("Points"));
|
||||
|
||||
@@ -609,7 +742,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.getTopVoter(TopVoter.AllTime).entrySet()) {
|
||||
for (Entry<TopVoterPlayer, Integer> entry : plugin.getTopVoterDisplay(TopVoter.AllTime).entrySet()) {
|
||||
if (entry.getKey().getUuid().equals(toMatch)) {
|
||||
return "" + num;
|
||||
}
|
||||
@@ -627,7 +760,9 @@ public class PlaceHolders {
|
||||
return "invalid";
|
||||
}
|
||||
int number = Integer.parseInt(identifier.split("_")[1]);
|
||||
if (user.getPoints() >= number) {
|
||||
Integer points = pointBalance(user);
|
||||
if (points == null) return "...";
|
||||
if (points >= number) {
|
||||
return "true";
|
||||
}
|
||||
return "false";
|
||||
@@ -705,7 +840,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.getTopVoter(TopVoter.AllTime).entrySet()) {
|
||||
for (Entry<TopVoterPlayer, Integer> entry : plugin.getTopVoterDisplay(TopVoter.AllTime).entrySet()) {
|
||||
if (num == number) {
|
||||
return "" + entry.getValue().intValue();
|
||||
}
|
||||
@@ -724,7 +859,7 @@ public class PlaceHolders {
|
||||
}
|
||||
int num = 1;
|
||||
int number = Integer.parseInt(identifier.split("_")[2]);
|
||||
for (Entry<TopVoterPlayer, Integer> entry : plugin.getTopVoter(TopVoter.AllTime).entrySet()) {
|
||||
for (Entry<TopVoterPlayer, Integer> entry : plugin.getTopVoterDisplay(TopVoter.AllTime).entrySet()) {
|
||||
if (num == number) {
|
||||
return entry.getKey().getPlayerName();
|
||||
}
|
||||
@@ -740,7 +875,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.getTopVoter(TopVoter.Monthly).entrySet()) {
|
||||
for (Entry<TopVoterPlayer, Integer> entry : plugin.getTopVoterDisplay(TopVoter.Monthly).entrySet()) {
|
||||
if (entry.getKey().getUuid().equals(toMatch)) {
|
||||
return "" + num;
|
||||
}
|
||||
@@ -757,7 +892,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.getLastMonthTopVoter().entrySet()) {
|
||||
for (Entry<TopVoterPlayer, Integer> entry : plugin.getLastMonthTopVoterDisplay().entrySet()) {
|
||||
if (entry.getKey().getUuid().equals(toMatch)) {
|
||||
return "" + num;
|
||||
}
|
||||
@@ -775,7 +910,7 @@ public class PlaceHolders {
|
||||
}
|
||||
int num = 1;
|
||||
int number = Integer.parseInt(identifier.split("_")[2]);
|
||||
for (Entry<TopVoterPlayer, Integer> entry : plugin.getLastMonthTopVoter().entrySet()) {
|
||||
for (Entry<TopVoterPlayer, Integer> entry : plugin.getLastMonthTopVoterDisplay().entrySet()) {
|
||||
if (num == number) {
|
||||
return entry.getKey().getPlayerName();
|
||||
}
|
||||
@@ -791,7 +926,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.getLastMonthTopVoter().entrySet()) {
|
||||
for (Entry<TopVoterPlayer, Integer> entry : plugin.getLastMonthTopVoterDisplay().entrySet()) {
|
||||
if (num == number) {
|
||||
return "" + entry.getValue().intValue();
|
||||
}
|
||||
@@ -812,7 +947,7 @@ public class PlaceHolders {
|
||||
}
|
||||
int num = 1;
|
||||
int number = Integer.parseInt(identifier.split("_")[2]);
|
||||
for (Entry<TopVoterPlayer, Integer> entry : plugin.getTopVoter(TopVoter.Monthly).entrySet()) {
|
||||
for (Entry<TopVoterPlayer, Integer> entry : plugin.getTopVoterDisplay(TopVoter.Monthly).entrySet()) {
|
||||
if (num == number) {
|
||||
return entry.getKey().getPlayerName();
|
||||
}
|
||||
@@ -828,7 +963,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.getTopVoter(TopVoter.Monthly).entrySet()) {
|
||||
for (Entry<TopVoterPlayer, Integer> entry : plugin.getTopVoterDisplay(TopVoter.Monthly).entrySet()) {
|
||||
if (num == number) {
|
||||
return "" + entry.getValue().intValue();
|
||||
}
|
||||
@@ -844,7 +979,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.getTopVoter(TopVoter.Weekly).entrySet()) {
|
||||
for (Entry<TopVoterPlayer, Integer> entry : plugin.getTopVoterDisplay(TopVoter.Weekly).entrySet()) {
|
||||
if (entry.getKey().getUuid().equals(toMatch)) {
|
||||
return "" + num;
|
||||
}
|
||||
@@ -863,7 +998,7 @@ public class PlaceHolders {
|
||||
}
|
||||
int num = 1;
|
||||
int number = Integer.parseInt(identifier.split("_")[2]);
|
||||
for (Entry<TopVoterPlayer, Integer> entry : plugin.getTopVoter(TopVoter.Weekly).entrySet()) {
|
||||
for (Entry<TopVoterPlayer, Integer> entry : plugin.getTopVoterDisplay(TopVoter.Weekly).entrySet()) {
|
||||
if (num == number) {
|
||||
return entry.getKey().getPlayerName();
|
||||
}
|
||||
@@ -879,7 +1014,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.getTopVoter(TopVoter.Weekly).entrySet()) {
|
||||
for (Entry<TopVoterPlayer, Integer> entry : plugin.getTopVoterDisplay(TopVoter.Weekly).entrySet()) {
|
||||
if (num == number) {
|
||||
return "" + entry.getValue().intValue();
|
||||
}
|
||||
@@ -895,7 +1030,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.getTopVoter(TopVoter.Daily).entrySet()) {
|
||||
for (Entry<TopVoterPlayer, Integer> entry : plugin.getTopVoterDisplay(TopVoter.Daily).entrySet()) {
|
||||
if (entry.getKey().getUuid().equals(toMatch)) {
|
||||
return "" + num;
|
||||
}
|
||||
@@ -914,7 +1049,7 @@ public class PlaceHolders {
|
||||
}
|
||||
int num = 1;
|
||||
int number = Integer.parseInt(identifier.split("_")[2]);
|
||||
for (Entry<TopVoterPlayer, Integer> entry : plugin.getTopVoter(TopVoter.Daily).entrySet()) {
|
||||
for (Entry<TopVoterPlayer, Integer> entry : plugin.getTopVoterDisplay(TopVoter.Daily).entrySet()) {
|
||||
if (num == number) {
|
||||
return entry.getKey().getPlayerName();
|
||||
}
|
||||
@@ -938,7 +1073,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.getTopVoter(TopVoter.Daily).entrySet()) {
|
||||
for (Entry<TopVoterPlayer, Integer> entry : plugin.getTopVoterDisplay(TopVoter.Daily).entrySet()) {
|
||||
if (num == number) {
|
||||
return "" + entry.getValue().intValue();
|
||||
}
|
||||
@@ -954,7 +1089,7 @@ public class PlaceHolders {
|
||||
|
||||
@Override
|
||||
public String placeholderRequest(String identifier) {
|
||||
return Integer.toString(plugin.getVoteParty().getTotalVotes());
|
||||
return Integer.toString(plugin.getServerData().getVotePartyDisplay().total());
|
||||
}
|
||||
}.withDescription("Current amount of voteparty votes"));
|
||||
|
||||
@@ -962,7 +1097,8 @@ public class PlaceHolders {
|
||||
|
||||
@Override
|
||||
public String placeholderRequest(String identifier) {
|
||||
return Integer.toString(plugin.getVoteParty().getNeededVotes());
|
||||
return Integer.toString(plugin.getServerData().getVotePartyDisplay()
|
||||
.needed(plugin.getSpecialRewardsConfig().getVotePartyVotesRequired()));
|
||||
}
|
||||
}.withDescription("Voteparty votes needed"));
|
||||
|
||||
@@ -970,7 +1106,8 @@ public class PlaceHolders {
|
||||
|
||||
@Override
|
||||
public String placeholderRequest(String identifier) {
|
||||
return Integer.toString(plugin.getVoteParty().getVotesRequired());
|
||||
return Integer.toString(plugin.getServerData().getVotePartyDisplay()
|
||||
.required(plugin.getSpecialRewardsConfig().getVotePartyVotesRequired()));
|
||||
}
|
||||
}.withDescription("Amount of votes needed for voteparty"));
|
||||
|
||||
@@ -1407,6 +1544,13 @@ 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;
|
||||
@@ -1427,7 +1571,11 @@ public class PlaceHolders {
|
||||
}
|
||||
} else {
|
||||
String value = placeholder.placeholderRequest(user, ident);
|
||||
values.put(uuid, value);
|
||||
if ("Points".equalsIgnoreCase(placeholder.getUpdateDataKey())) {
|
||||
pointFence.publish(uuid, pointGeneration, () -> {
|
||||
if (plugin.isEnabled()) values.put(uuid, value);
|
||||
});
|
||||
} else values.put(uuid, value);
|
||||
if (getCacheLevel().onlineOnly() && !plugin.getPlaceholderPlayerPresence().isOnline(uuid)) {
|
||||
values.remove(uuid);
|
||||
continue;
|
||||
@@ -1436,6 +1584,9 @@ public class PlaceHolders {
|
||||
+ matchingKey(placeholder, keys) + " with " + value);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
pointFence.release(uuid);
|
||||
}
|
||||
}
|
||||
|
||||
private void publishCachedValue(PlaceHolder<VotingPluginUser> placeholder, VotingPluginUser user, UUID uuid,
|
||||
@@ -1460,6 +1611,52 @@ 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
|
||||
@@ -1505,11 +1702,12 @@ public class PlaceHolders {
|
||||
/**
|
||||
* Update placeholders for specific user.
|
||||
* @param user the voting plugin user
|
||||
* @param login whether this is a login update
|
||||
* @param login whether to include uncached entries, such as a login or worker warmup
|
||||
*/
|
||||
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<>();
|
||||
@@ -1551,6 +1749,8 @@ public class PlaceHolders {
|
||||
* Reload placeholders.
|
||||
*/
|
||||
public void reload() {
|
||||
pointFence.invalidateLifecycle();
|
||||
pointRecoveryWorkers.clear();
|
||||
platformUpdateGenerations.clear();
|
||||
plugin.refreshPlaceholderPlayerPresence();
|
||||
cacheLevel = plugin.getConfigFile().getPlaceholderCacheLevel();
|
||||
@@ -1584,14 +1784,47 @@ public class PlaceHolders {
|
||||
* Schedule placeholder check for user.
|
||||
* @param user the voting plugin user
|
||||
*/
|
||||
public void schedulePlaceholderCheck(VotingPluginUser user) {
|
||||
plugin.getTimer().execute(new Runnable() {
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
checkNonCachedPlaceholders();
|
||||
onUpdate(user, plugin.getPlaceholderPlayerPresence().isOnline(user.getJavaUUID()));
|
||||
}
|
||||
});
|
||||
}
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
+106
-2
@@ -7,6 +7,8 @@ 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;
|
||||
@@ -19,6 +21,97 @@ 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);
|
||||
@@ -46,24 +139,31 @@ 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();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -71,11 +171,13 @@ 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;
|
||||
}
|
||||
}
|
||||
@@ -113,6 +215,8 @@ public final class PlaceholderPlayerPresence {
|
||||
}
|
||||
}
|
||||
onlinePlayers.set(Map.copyOf(next));
|
||||
refreshReservations.clear();
|
||||
retainCurrentIdentities();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -122,11 +226,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)); }
|
||||
synchronized (lifecycleLock) { onlinePlayers.set(Map.copyOf(next)); refreshReservations.clear(); retainCurrentIdentities(); }
|
||||
}
|
||||
|
||||
public void clear() {
|
||||
synchronized (lifecycleLock) { onlinePlayers.set(Map.of()); }
|
||||
synchronized (lifecycleLock) { onlinePlayers.set(Map.of()); identities.clear(); refreshReservations.clear(); }
|
||||
}
|
||||
|
||||
/** Publish an offline-only result atomically with player lifecycle capture. */
|
||||
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -40,6 +40,19 @@ public class OfflineBungeeVote {
|
||||
@Getter
|
||||
@Setter
|
||||
private String text;
|
||||
|
||||
public long getCanonicalOccurrenceTime() {
|
||||
Long original = VoteOccurrenceMetadata.read(text);
|
||||
return original == null ? 0L : original;
|
||||
}
|
||||
|
||||
public void setCanonicalOccurrenceTime(long occurredAt) {
|
||||
text = VoteOccurrenceMetadata.store(text, occurredAt);
|
||||
}
|
||||
|
||||
public void setText(String updated) {
|
||||
text = VoteOccurrenceMetadata.preserve(text, updated);
|
||||
}
|
||||
@Getter
|
||||
private long time;
|
||||
@Getter
|
||||
@@ -82,6 +95,48 @@ public class OfflineBungeeVote {
|
||||
private final Map<String, String> httpDeliveryIds;
|
||||
/** Stable HTTP standalone-broadcast IDs, separate from reward delivery IDs. */
|
||||
private final Map<String, String> httpBroadcastDeliveryIds;
|
||||
/** Original cached replay position, retained when only part of a batch is sent. */
|
||||
@Getter
|
||||
private int cachedBatchNumber;
|
||||
@Getter
|
||||
private int cachedBatchSize;
|
||||
/** SQL row whose batch metadata is journaled in the JSON emergency store. */
|
||||
@Getter
|
||||
@Setter
|
||||
private int cachedBatchSourceRowId;
|
||||
@Getter
|
||||
@Setter
|
||||
private boolean cachedBatchDurable;
|
||||
|
||||
public void setCachedVoteBatch(int number, int size) {
|
||||
cachedBatchNumber = number;
|
||||
cachedBatchSize = size;
|
||||
cachedBatchDurable = false;
|
||||
}
|
||||
|
||||
public boolean hasCachedVoteBatch() {
|
||||
return cachedBatchNumber > 0 && cachedBatchNumber <= cachedBatchSize;
|
||||
}
|
||||
|
||||
public boolean isCachedVoteBatchValid() {
|
||||
return cachedBatchSourceRowId >= 0 && (cachedBatchNumber == 0 && cachedBatchSize == 0
|
||||
|| hasCachedVoteBatch());
|
||||
}
|
||||
|
||||
/** Copies only replay metadata, leaving this cache lane's ownership unchanged. */
|
||||
public void copyCachedVoteBatch(OfflineBungeeVote source) {
|
||||
cachedBatchNumber = source.cachedBatchNumber;
|
||||
cachedBatchSize = source.cachedBatchSize;
|
||||
cachedBatchSourceRowId = source.cachedBatchSourceRowId;
|
||||
cachedBatchDurable = source.cachedBatchDurable;
|
||||
}
|
||||
|
||||
/** Assigns a legacy replay ID after its journal owner has been persisted. */
|
||||
public void assignCachedVoteId(UUID identity) {
|
||||
if (identity == null || voteId != null && !voteId.equals(identity))
|
||||
throw new IllegalArgumentException("A cached vote identity cannot be replaced");
|
||||
voteId = identity;
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructor with UUID voteId.
|
||||
@@ -356,7 +411,13 @@ public class OfflineBungeeVote {
|
||||
|
||||
/** Returns whether any reward or standalone HTTP delivery is still pending. */
|
||||
public boolean hasPendingHttpDeliveryIds() {
|
||||
return !httpDeliveryIds.isEmpty() || !httpBroadcastDeliveryIds.isEmpty();
|
||||
return !httpDeliveryIds.isEmpty() || hasPendingHttpBroadcastDeliveryIds();
|
||||
}
|
||||
|
||||
/** Returns whether standalone HTTP broadcasts, rather than internal markers, remain. */
|
||||
public boolean hasPendingHttpBroadcastDeliveryIds() {
|
||||
return httpBroadcastDeliveryIds.keySet().stream().anyMatch(key -> !key.startsWith(
|
||||
VotingPluginWire.REWARD_QUEUE_METADATA_PREFIX));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+16
@@ -79,11 +79,20 @@ public final class PendingIncomingVoteJournal {
|
||||
vote.setWasOnline(value.has("wasOnline") && value.get("wasOnline").getAsBoolean());
|
||||
}
|
||||
vote.setTotals(optional(value, "totals", 4096));
|
||||
vote.setProxyBroadcastHandled(value.has("proxyBroadcastHandled") && value.get("proxyBroadcastHandled").getAsBoolean());
|
||||
String targets = optional(value, "broadcastTargets", 16384);
|
||||
vote.getBroadcastTargets().addAll(VoteTimeQueue.decodeBroadcastForwardedServers(targets));
|
||||
if (!targets.equals(vote.encodeBroadcastTargets())) throw new IOException("Invalid pending broadcast plan");
|
||||
vote.setVotePartyApplied(value.has("votePartyApplied")
|
||||
&& value.get("votePartyApplied").getAsBoolean());
|
||||
vote.setTotalsApplied(value.has("totalsApplied") && value.get("totalsApplied").getAsBoolean());
|
||||
vote.getBroadcastForwardedServers().addAll(VoteTimeQueue.decodeBroadcastForwardedServers(
|
||||
optional(value, "broadcastForwardedServers", 16384)));
|
||||
String deliveryIds = optional(value, "httpBroadcastDeliveryIds", 16384);
|
||||
VoteTimeQueue.decodeHttpBroadcastDeliveryIds(deliveryIds).forEach(vote::setHttpBroadcastDeliveryId);
|
||||
if (!deliveryIds.equals(vote.encodeHttpBroadcastDeliveryIds())) {
|
||||
throw new IOException("Pending vote journal contains invalid delivery metadata");
|
||||
}
|
||||
vote.setMultiProxyForwardingHandled(value.has("multiProxyForwardingHandled")
|
||||
&& value.get("multiProxyForwardingHandled").getAsBoolean());
|
||||
if (value.has("delayValidationKnown") && value.get("delayValidationKnown").getAsBoolean()) {
|
||||
@@ -131,9 +140,12 @@ public final class PendingIncomingVoteJournal {
|
||||
value.addProperty("wasOnline", vote.isWasOnline());
|
||||
value.addProperty("wasOnlineKnown", vote.isWasOnlineKnown());
|
||||
value.addProperty("totals", vote.getTotals());
|
||||
value.addProperty("proxyBroadcastHandled", vote.isProxyBroadcastHandled());
|
||||
value.addProperty("broadcastTargets", vote.encodeBroadcastTargets());
|
||||
value.addProperty("votePartyApplied", vote.isVotePartyApplied());
|
||||
value.addProperty("totalsApplied", vote.isTotalsApplied());
|
||||
value.addProperty("broadcastForwardedServers", vote.encodeBroadcastForwardedServers());
|
||||
value.addProperty("httpBroadcastDeliveryIds", vote.encodeHttpBroadcastDeliveryIds());
|
||||
value.addProperty("multiProxyForwardingHandled", vote.isMultiProxyForwardingHandled());
|
||||
value.addProperty("delayValidated", vote.isDelayValidated());
|
||||
value.addProperty("delayValidationKnown", vote.isDelayValidationKnown());
|
||||
@@ -160,6 +172,10 @@ public final class PendingIncomingVoteJournal {
|
||||
}
|
||||
if (vote.getUuid() != null && vote.getUuid().length() > 36) throw new IOException("Invalid UUID field");
|
||||
if (vote.getTotals() != null && vote.getTotals().length() > 4096) throw new IOException("Invalid totals field");
|
||||
if (vote.encodeBroadcastTargets().length() > 16384) throw new IOException("Invalid pending broadcast plan");
|
||||
if (vote.encodeHttpBroadcastDeliveryIds().length() > 16384) {
|
||||
throw new IOException("Invalid delivery metadata");
|
||||
}
|
||||
if (vote.encodeBroadcastForwardedServers().length() > 16384) {
|
||||
throw new IOException("Invalid forwarded-server state");
|
||||
}
|
||||
|
||||
+346
@@ -0,0 +1,346 @@
|
||||
package com.bencodez.votingplugin.proxy;
|
||||
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.ScheduledFuture;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.function.BooleanSupplier;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.LongSupplier;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
/** Paces handoffs; durable vote queues, rather than this dispatcher, own votes. */
|
||||
final class PluginMessageDispatcher {
|
||||
static final long INTERVAL = TimeUnit.MILLISECONDS.toNanos(20);
|
||||
static final long FAILURE_DELAY = TimeUnit.SECONDS.toNanos(1);
|
||||
static final long RETRY_DELAY = TimeUnit.SECONDS.toNanos(10);
|
||||
static final long METADATA_LIFETIME = TimeUnit.SECONDS.toNanos(30);
|
||||
static final int MAX_BACKENDS = 256;
|
||||
static final int MAX_CONTROLS = 2048;
|
||||
static final int MAX_LANE_CONTROLS = 256;
|
||||
static final int MAX_BYTES = 4 * 1024 * 1024;
|
||||
static final int MAX_IN_FLIGHT = 32;
|
||||
private final LongSupplier clock;
|
||||
private final Supplier<ScheduledExecutorService> executor;
|
||||
private final Consumer<String> replay;
|
||||
private final Map<String, Lane> lanes = new LinkedHashMap<>();
|
||||
private final ThreadLocal<Lane> replaying = new ThreadLocal<>();
|
||||
private int controls;
|
||||
private int bytes;
|
||||
private boolean closed;
|
||||
|
||||
private static final class Lane {
|
||||
final String server;
|
||||
final ArrayDeque<Control> controls = new ArrayDeque<>();
|
||||
final Map<String, Attempt> attempts = new HashMap<>();
|
||||
ScheduledFuture<?> wake;
|
||||
long generation;
|
||||
long next;
|
||||
long ownerDue;
|
||||
long wakeDue;
|
||||
int inFlight;
|
||||
boolean sending;
|
||||
boolean ownerPending;
|
||||
boolean ownerRunning;
|
||||
boolean controlTurn;
|
||||
int ownerTurn;
|
||||
int onlineTurn;
|
||||
int broadcastTurn;
|
||||
Lane(String server, long now) { this.server = server; next = now; }
|
||||
}
|
||||
private record Attempt(long due, boolean receipt) { }
|
||||
private record Control(int bytes, long due, boolean blocksReplacement, BooleanSupplier handoff) { }
|
||||
|
||||
PluginMessageDispatcher(LongSupplier clock, Supplier<ScheduledExecutorService> executor,
|
||||
Consumer<String> replay) {
|
||||
this.clock = clock;
|
||||
this.executor = executor;
|
||||
this.replay = replay;
|
||||
}
|
||||
|
||||
private synchronized Lane lane(String server) {
|
||||
if (closed || server == null || server.isBlank()) return null;
|
||||
String key = server.trim().toLowerCase(Locale.ROOT);
|
||||
Lane lane = lanes.get(key);
|
||||
if (lane == null) {
|
||||
long now = clock.getAsLong();
|
||||
if (lanes.size() >= MAX_BACKENDS) {
|
||||
lanes.values().removeIf(old -> !old.sending && !old.ownerRunning && !old.ownerPending
|
||||
&& old.controls.isEmpty() && old.attempts.isEmpty() && now - old.next >= 0);
|
||||
}
|
||||
if (lanes.size() >= MAX_BACKENDS) return null;
|
||||
lane = new Lane(server, now);
|
||||
lanes.put(key, lane);
|
||||
}
|
||||
return lane;
|
||||
}
|
||||
|
||||
synchronized boolean hasBudget(String server, String key, boolean receipt) {
|
||||
Lane lane = lane(server);
|
||||
if (lane == null) return false;
|
||||
long now = clock.getAsLong();
|
||||
Attempt previous = key == null ? null : lane.attempts.get(key);
|
||||
if (!unavailable(lane, key, receipt, previous, now)) return true;
|
||||
defer(lane, key, receipt, previous, now);
|
||||
return false;
|
||||
}
|
||||
|
||||
private boolean unavailable(Lane lane, String key, boolean receipt, Attempt previous, long now) {
|
||||
return lane.sending || now - lane.next < 0
|
||||
|| replaying.get() != lane && (lane.ownerRunning || !lane.controls.isEmpty())
|
||||
|| previous != null && now - previous.due() < 0
|
||||
|| key != null && previous == null && (lane.attempts.size() >= 256
|
||||
|| !receipt && lane.inFlight >= MAX_IN_FLIGHT);
|
||||
}
|
||||
|
||||
private void defer(Lane lane, String key, boolean receipt, Attempt previous, long now) {
|
||||
long due = previous != null && now - previous.due() < 0 ? previous.due()
|
||||
: key != null && previous == null && !receipt && lane.inFlight >= MAX_IN_FLIGHT
|
||||
? lane.attempts.values().stream().mapToLong(Attempt::due).min().orElse(now + RETRY_DELAY)
|
||||
: Math.max(now + INTERVAL, lane.next);
|
||||
requestOwner(lane, due);
|
||||
schedule(lane);
|
||||
}
|
||||
|
||||
boolean trySend(String server, BooleanSupplier handoff) {
|
||||
return trySend(server, null, false, handoff);
|
||||
}
|
||||
|
||||
boolean trySend(String server, String key, boolean receipt, BooleanSupplier handoff) {
|
||||
Lane lane;
|
||||
boolean firstAttempt;
|
||||
synchronized (this) {
|
||||
lane = lane(server);
|
||||
if (lane == null) return false;
|
||||
long now = clock.getAsLong();
|
||||
Attempt previous = key == null ? null : lane.attempts.get(key);
|
||||
if (unavailable(lane, key, receipt, previous, now)) {
|
||||
defer(lane, key, receipt, previous, now);
|
||||
return false;
|
||||
}
|
||||
firstAttempt = previous == null;
|
||||
// Reserve before calling transport: acknowledgements may be reentrant.
|
||||
if (key != null) {
|
||||
lane.attempts.put(key, new Attempt(now + RETRY_DELAY, receipt));
|
||||
if (previous == null && !receipt) lane.inFlight++;
|
||||
}
|
||||
lane.sending = true;
|
||||
}
|
||||
boolean accepted = false;
|
||||
try {
|
||||
accepted = handoff.getAsBoolean();
|
||||
return accepted;
|
||||
} finally {
|
||||
synchronized (this) {
|
||||
lane.next = clock.getAsLong() + (accepted ? INTERVAL : FAILURE_DELAY);
|
||||
lane.sending = false;
|
||||
if (key != null && !accepted && firstAttempt) removeAttempt(lane, key);
|
||||
if (key != null && lane.attempts.containsKey(key)) {
|
||||
lane.attempts.put(key, new Attempt(clock.getAsLong() + RETRY_DELAY, receipt));
|
||||
}
|
||||
if (!closed) requestOwner(lane, lane.next);
|
||||
schedule(lane);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
synchronized void acknowledge(String server, String key) {
|
||||
Lane lane = lanes.get(server.trim().toLowerCase(Locale.ROOT));
|
||||
if (lane != null) {
|
||||
removeAttempt(lane, key);
|
||||
requestOwner(lane, clock.getAsLong() + INTERVAL);
|
||||
schedule(lane);
|
||||
}
|
||||
}
|
||||
|
||||
private void removeAttempt(Lane lane, String key) {
|
||||
Attempt old = lane.attempts.remove(key);
|
||||
if (old != null && !old.receipt()) lane.inFlight--;
|
||||
}
|
||||
|
||||
private void requestOwner(Lane lane, long due) {
|
||||
if (closed) return;
|
||||
lane.ownerDue = lane.ownerPending ? Math.min(lane.ownerDue, due) : due;
|
||||
lane.ownerPending = true;
|
||||
}
|
||||
|
||||
synchronized int ownerTurn(String server, int families) {
|
||||
Lane lane = lane(server);
|
||||
return lane == null ? 0 : Math.floorMod(lane.ownerTurn++, families);
|
||||
}
|
||||
|
||||
final class Batch {
|
||||
private final Map<Lane, Control> retained = new LinkedHashMap<>();
|
||||
private volatile boolean active;
|
||||
private volatile boolean cancelled;
|
||||
void activate() { active = true; }
|
||||
void cancel() {
|
||||
synchronized (PluginMessageDispatcher.this) {
|
||||
cancelled = true;
|
||||
if (closed) return;
|
||||
for (Map.Entry<Lane, Control> entry : retained.entrySet()) {
|
||||
if (entry.getKey().controls.remove(entry.getValue())) { controls--; bytes -= entry.getValue().bytes(); }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Reserves a complete control batch before its owner consumes an activation. */
|
||||
synchronized Batch reserveBatch(Map<String, BooleanSupplier> handoffs, int size) {
|
||||
if (closed || handoffs.size() > MAX_BACKENDS || size < 0 || size > MAX_BYTES || controls + (long) handoffs.size() > MAX_CONTROLS
|
||||
|| bytes + (long) size * handoffs.size() > MAX_BYTES) return null;
|
||||
Batch batch = new Batch();
|
||||
for (Map.Entry<String, BooleanSupplier> entry : handoffs.entrySet()) {
|
||||
Lane lane = lane(entry.getKey());
|
||||
if (lane == null || lane.controls.size() >= MAX_LANE_CONTROLS || batch.retained.containsKey(lane)) return null;
|
||||
batch.retained.put(lane, new Control(size, clock.getAsLong(), true,
|
||||
() -> batch.cancelled || batch.active && entry.getValue().getAsBoolean()));
|
||||
}
|
||||
if (!lanes.values().containsAll(batch.retained.keySet())) return null;
|
||||
for (Map.Entry<Lane, Control> entry : batch.retained.entrySet()) {
|
||||
entry.getKey().controls.addLast(entry.getValue()); controls++; bytes += size;
|
||||
}
|
||||
for (Lane lane : batch.retained.keySet()) {
|
||||
if (!schedule(lane)) { batch.cancel(); return null; }
|
||||
}
|
||||
return batch;
|
||||
}
|
||||
|
||||
synchronized int cacheTurn(String server, boolean broadcast, int size) {
|
||||
Lane lane = lane(server);
|
||||
if (lane == null || size == 0) return 0;
|
||||
return Math.floorMod(broadcast ? lane.broadcastTurn++ : lane.onlineTurn++, size);
|
||||
}
|
||||
|
||||
synchronized boolean enqueue(String server, int size, long delay, BooleanSupplier handoff) {
|
||||
return enqueue(server, size, delay, true, handoff);
|
||||
}
|
||||
|
||||
synchronized boolean enqueue(String server, int size, long delay, boolean blocksReplacement, BooleanSupplier handoff) {
|
||||
Lane lane = lane(server);
|
||||
if (lane == null || size < 0 || size > MAX_BYTES || controls >= MAX_CONTROLS
|
||||
|| lane.controls.size() >= MAX_LANE_CONTROLS || bytes > MAX_BYTES - size) return false;
|
||||
Control control = new Control(size, clock.getAsLong() + Math.max(0, delay), blocksReplacement, handoff);
|
||||
lane.controls.addLast(control);
|
||||
controls++;
|
||||
bytes += size;
|
||||
if (!schedule(lane)) {
|
||||
lane.controls.remove(control);
|
||||
controls--;
|
||||
bytes -= size;
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private boolean schedule(Lane lane) {
|
||||
if (closed) return false;
|
||||
if (lane.sending || lane.ownerRunning) return true;
|
||||
long due = Long.MAX_VALUE;
|
||||
if (lane.ownerPending) due = lane.ownerDue;
|
||||
for (Control control : lane.controls) due = Math.min(due, control.due());
|
||||
if (due == Long.MAX_VALUE) return true;
|
||||
long now = clock.getAsLong();
|
||||
due = Math.max(Math.max(due, lane.next), now + INTERVAL);
|
||||
if (lane.wake != null && !lane.wake.isDone() && !lane.wake.isCancelled() && lane.wakeDue <= due) return true;
|
||||
// Generation fencing also invalidates a callback whose cancellation fails.
|
||||
if (lane.wake != null) {
|
||||
try { lane.wake.cancel(false); } catch (RuntimeException ignored) { }
|
||||
}
|
||||
long ticket = ++lane.generation;
|
||||
try {
|
||||
ScheduledExecutorService service = executor.get();
|
||||
if (service == null || service.isShutdown()) { lane.wake = null; return false; }
|
||||
lane.wakeDue = due;
|
||||
lane.wake = service.schedule(() -> drain(lane, ticket), due - now, TimeUnit.NANOSECONDS);
|
||||
return true;
|
||||
} catch (RuntimeException rejected) {
|
||||
lane.wake = null;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private void drain(Lane lane, long ticket) {
|
||||
Control control = null;
|
||||
boolean owner = false;
|
||||
synchronized (this) {
|
||||
if (closed || ticket != lane.generation) return;
|
||||
lane.wake = null;
|
||||
long now = clock.getAsLong();
|
||||
// Probes are regenerated periodically. An absent carrier must not
|
||||
// retain stale metadata forever; effect-bearing controls stay owned.
|
||||
for (var iterator = lane.controls.iterator(); iterator.hasNext();) {
|
||||
Control candidate = iterator.next();
|
||||
if (!candidate.blocksReplacement() && now - candidate.due() >= METADATA_LIFETIME) {
|
||||
iterator.remove();
|
||||
controls--;
|
||||
bytes -= candidate.bytes();
|
||||
}
|
||||
}
|
||||
if (lane.sending || now - lane.next < 0) { schedule(lane); return; }
|
||||
// A delayed control must not block an unrelated ready message.
|
||||
for (Control candidate : lane.controls) {
|
||||
if (now - candidate.due() >= 0) { control = candidate; break; }
|
||||
}
|
||||
if (lane.ownerPending && now - lane.ownerDue >= 0 && (control == null || !lane.controlTurn)) {
|
||||
owner = true;
|
||||
control = null;
|
||||
lane.ownerPending = false;
|
||||
lane.ownerRunning = true;
|
||||
lane.controlTurn = true;
|
||||
} else if (control != null) {
|
||||
lane.sending = true;
|
||||
lane.controlTurn = false;
|
||||
}
|
||||
}
|
||||
if (owner) {
|
||||
try {
|
||||
replaying.set(lane);
|
||||
replay.accept(lane.server);
|
||||
} catch (RuntimeException failure) {
|
||||
synchronized (this) { requestOwner(lane, clock.getAsLong() + FAILURE_DELAY); lane.next = clock.getAsLong() + FAILURE_DELAY; }
|
||||
} finally {
|
||||
replaying.remove();
|
||||
synchronized (this) { lane.ownerRunning = false; schedule(lane); }
|
||||
}
|
||||
} else if (control != null) {
|
||||
boolean accepted = false;
|
||||
try { accepted = control.handoff().getAsBoolean(); }
|
||||
catch (RuntimeException failure) { /* Retain for a later handoff. */ }
|
||||
finally {
|
||||
synchronized (this) {
|
||||
lane.sending = false;
|
||||
lane.next = clock.getAsLong() + (accepted ? INTERVAL : FAILURE_DELAY);
|
||||
if (!closed && accepted && lane.controls.remove(control)) { controls--; bytes -= control.bytes(); }
|
||||
schedule(lane);
|
||||
}
|
||||
}
|
||||
} else synchronized (this) { schedule(lane); }
|
||||
}
|
||||
|
||||
synchronized int pendingControls() { return controls; }
|
||||
|
||||
/** Includes selected controls until their handoff has completed. */
|
||||
synchronized boolean hasPendingEffects() {
|
||||
for (Lane lane : lanes.values())
|
||||
for (Control control : lane.controls)
|
||||
if (control.blocksReplacement()) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
synchronized void close() {
|
||||
closed = true;
|
||||
for (Lane lane : lanes.values()) {
|
||||
lane.generation++;
|
||||
if (lane.wake != null) {
|
||||
try { lane.wake.cancel(false); } catch (RuntimeException ignored) { }
|
||||
}
|
||||
}
|
||||
lanes.clear();
|
||||
controls = bytes = 0;
|
||||
}
|
||||
}
|
||||
+103
-24
@@ -21,9 +21,13 @@ import com.bencodez.votingplugin.util.DurableFiles;
|
||||
/** Durable proxy outbox for reward-bearing votes awaiting backend completion. */
|
||||
final class ReliableVoteDeliveryOutbox {
|
||||
static final int MAX_ENTRIES = 4096;
|
||||
static final int MAX_UPDATE_ENTRIES = 1024;
|
||||
static final int MAX_DEFERRED_UPDATE_ENTRIES = 4096;
|
||||
private static final long MAX_FILE_BYTES = 16L * 1024L * 1024L;
|
||||
private static final String HEADER = "VP-VOTE-OUTBOX-2";
|
||||
private static final String ADD = "A";
|
||||
private static final String DEFERRED = "D";
|
||||
private static final String READY = "P";
|
||||
private static final String COMPLETED = "C";
|
||||
private static final String REMOVE = "R";
|
||||
private static final String LEGACY_FENCED = "F";
|
||||
@@ -31,7 +35,11 @@ final class ReliableVoteDeliveryOutbox {
|
||||
private static final String LEGACY_REJECTED = "J";
|
||||
|
||||
record Entry(String server, JsonEnvelope envelope, boolean awaitingReceiptRelease, boolean legacyDeliveryFenced,
|
||||
boolean legacyDeliveryRejected) { }
|
||||
boolean legacyDeliveryRejected, boolean deferredUpdate) {
|
||||
Entry(String server, JsonEnvelope envelope, boolean release, boolean fenced, boolean rejected) {
|
||||
this(server, envelope, release, fenced, rejected, false);
|
||||
}
|
||||
}
|
||||
|
||||
private final Path file;
|
||||
private final LinkedHashMap<String, Entry> entries = new LinkedHashMap<>();
|
||||
@@ -44,24 +52,76 @@ final class ReliableVoteDeliveryOutbox {
|
||||
}
|
||||
|
||||
synchronized boolean offer(String server, JsonEnvelope envelope) {
|
||||
String key = key(server, envelope);
|
||||
if (key == null) return false;
|
||||
if (entries.containsKey(key)) return true;
|
||||
if (entries.size() >= MAX_ENTRIES) return false;
|
||||
String record = addRecord(server, envelope);
|
||||
Entry entry = new Entry(server, envelope, false, false, false);
|
||||
long remainingReserve = terminalRecordReserve() + terminalRecordReserve(entry);
|
||||
if (!prepareAppend(record, remainingReserve) || !append(record)) return false;
|
||||
entries.put(key, entry);
|
||||
journalRecords++;
|
||||
return true;
|
||||
}
|
||||
return offer(server, envelope, false);
|
||||
}
|
||||
|
||||
/** Retains an update independently of its current ready-window or carrier availability. */
|
||||
synchronized boolean retainUpdate(String server, JsonEnvelope envelope, boolean carrierAvailable) {
|
||||
if (key(server, envelope) == null || !VotingPluginWire.SUB_VOTE_UPDATE.equals(envelope.getSubChannel())) return false;
|
||||
boolean deferred = !carrierAvailable || readyUpdates() >= MAX_UPDATE_ENTRIES
|
||||
|| entries.values().stream().anyMatch(entry -> entry.deferredUpdate()
|
||||
&& normalized(entry.server()).equals(normalized(server)));
|
||||
return offer(server, envelope, deferred);
|
||||
}
|
||||
|
||||
private boolean offer(String server, JsonEnvelope envelope, boolean deferred) {
|
||||
String key = key(server, envelope);
|
||||
if (key == null) return false;
|
||||
if (entries.containsKey(key)) return true;
|
||||
boolean update = VotingPluginWire.SUB_VOTE_UPDATE.equals(envelope.getSubChannel());
|
||||
long updates = entries.values().stream().filter(entry ->
|
||||
VotingPluginWire.SUB_VOTE_UPDATE.equals(entry.envelope().getSubChannel())).count();
|
||||
long deferredCount = entries.values().stream().filter(Entry::deferredUpdate).count();
|
||||
if (deferred ? !update || deferredCount >= MAX_DEFERRED_UPDATE_ENTRIES
|
||||
: update ? readyUpdates() >= MAX_UPDATE_ENTRIES : entries.size() - updates >= MAX_ENTRIES) return false;
|
||||
String record = addRecord(server, envelope, deferred);
|
||||
Entry entry = new Entry(server, envelope, false, false, false, deferred);
|
||||
long remainingReserve = terminalRecordReserve() + terminalRecordReserve(entry);
|
||||
if (!prepareAppend(record, remainingReserve) || !append(record)) return false;
|
||||
entries.put(key, entry);
|
||||
journalRecords++;
|
||||
return true;
|
||||
}
|
||||
|
||||
private long readyUpdates() {
|
||||
return entries.values().stream().filter(entry -> !entry.deferredUpdate()
|
||||
&& VotingPluginWire.SUB_VOTE_UPDATE.equals(entry.envelope().getSubChannel())).count();
|
||||
}
|
||||
|
||||
synchronized boolean setUpdateReady(String server, UUID voteId, boolean ready) {
|
||||
if (server == null || voteId == null) return false;
|
||||
String key = normalized(server) + '|' + VotingPluginWire.SUB_VOTE_UPDATE + '|' + voteId;
|
||||
Entry entry = entries.get(key);
|
||||
if (entry == null || entry.legacyDeliveryFenced() || entry.awaitingReceiptRelease()) return false;
|
||||
if (entry.deferredUpdate() == !ready) return true;
|
||||
if (ready ? readyUpdates() >= MAX_UPDATE_ENTRIES
|
||||
: entries.values().stream().filter(Entry::deferredUpdate).count() >= MAX_DEFERRED_UPDATE_ENTRIES) return false;
|
||||
String record = (ready ? READY : DEFERRED) + '\t' + encode(key) + '\n';
|
||||
Entry replacement = new Entry(entry.server(), entry.envelope(), false, false,
|
||||
false, !ready);
|
||||
long reserve = terminalRecordReserve() - terminalRecordReserve(entry) + terminalRecordReserve(replacement);
|
||||
if (!prepareAppend(record, reserve) || !append(record)) return false;
|
||||
entries.put(key, replacement);
|
||||
journalRecords++;
|
||||
return true;
|
||||
}
|
||||
|
||||
synchronized boolean isFirstPendingUpdate(String server, UUID voteId) {
|
||||
if (server == null || voteId == null) return false;
|
||||
for (Entry entry : entries.values()) {
|
||||
if (VotingPluginWire.SUB_VOTE_UPDATE.equals(entry.envelope().getSubChannel())
|
||||
&& normalized(entry.server()).equals(normalized(server))) {
|
||||
return voteId.equals(UUID.fromString(entry.envelope().getFields().get(VotingPluginWire.K_VOTE_ID)));
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
synchronized boolean acknowledgeCompletion(String server, UUID voteId, String subChannel) {
|
||||
if (voteId == null || server == null || subChannel == null) return false;
|
||||
String key = normalized(server) + '|' + subChannel + '|' + voteId;
|
||||
Entry entry = entries.get(key);
|
||||
if (entry == null) return false;
|
||||
if (entry == null || entry.deferredUpdate()) return false;
|
||||
if (entry.awaitingReceiptRelease()) return true;
|
||||
String record = completionRecord(key);
|
||||
Entry completed = new Entry(entry.server(), entry.envelope(), true, false, false);
|
||||
@@ -85,7 +145,7 @@ final class ReliableVoteDeliveryOutbox {
|
||||
if (voteId == null || server == null || subChannel == null) return false;
|
||||
String key = normalized(server) + '|' + subChannel + '|' + voteId;
|
||||
Entry entry = entries.get(key);
|
||||
if (entry == null || entry.awaitingReceiptRelease()) return false;
|
||||
if (entry == null || entry.awaitingReceiptRelease() || entry.deferredUpdate()) return false;
|
||||
boolean fenced = LEGACY_FENCED.equals(transition);
|
||||
boolean rejected = LEGACY_REJECTED.equals(transition);
|
||||
if (entry.legacyDeliveryFenced() == fenced && entry.legacyDeliveryRejected() == rejected) return true;
|
||||
@@ -176,23 +236,34 @@ final class ReliableVoteDeliveryOutbox {
|
||||
if (lines[index].isBlank()) continue;
|
||||
String[] parts = lines[index].split("\\t", 3);
|
||||
try {
|
||||
if (parts.length == 3 && ADD.equals(parts[0])) {
|
||||
if (parts.length == 3 && (ADD.equals(parts[0]) || DEFERRED.equals(parts[0]))) {
|
||||
String server = decode(parts[1]);
|
||||
JsonEnvelope envelope = JsonEnvelopeCodec.decode(decode(parts[2]));
|
||||
String key = key(server, envelope);
|
||||
if (key == null) throw new IllegalArgumentException("Invalid vote envelope");
|
||||
entries.put(key, new Entry(server, envelope, false, false, false));
|
||||
} else if (parts.length == 2 && COMPLETED.equals(parts[0])) {
|
||||
boolean deferred = DEFERRED.equals(parts[0]);
|
||||
if (deferred && !VotingPluginWire.SUB_VOTE_UPDATE.equals(envelope.getSubChannel()))
|
||||
throw new IllegalArgumentException("Only updates may be deferred");
|
||||
entries.put(key, new Entry(server, envelope, false, false, false, deferred));
|
||||
} else if (parts.length == 2 && (DEFERRED.equals(parts[0]) || READY.equals(parts[0]))) {
|
||||
String key = decode(parts[1]);
|
||||
Entry entry = entries.get(key);
|
||||
if (entry == null || !VotingPluginWire.SUB_VOTE_UPDATE.equals(entry.envelope().getSubChannel())
|
||||
|| entry.legacyDeliveryFenced() || entry.awaitingReceiptRelease())
|
||||
throw new IllegalArgumentException("Invalid deferred update transition");
|
||||
entries.put(key, new Entry(entry.server(), entry.envelope(), false, false,
|
||||
false, DEFERRED.equals(parts[0])));
|
||||
} else if (parts.length == 2 && COMPLETED.equals(parts[0])) {
|
||||
String key = decode(parts[1]);
|
||||
Entry entry = entries.get(key);
|
||||
if (entry == null) throw new IllegalArgumentException("Completion without vote");
|
||||
if (entry == null || entry.deferredUpdate()) throw new IllegalArgumentException("Completion without ready vote");
|
||||
entries.put(key, new Entry(entry.server(), entry.envelope(), true, false, false));
|
||||
} else if (parts.length == 2
|
||||
&& (LEGACY_FENCED.equals(parts[0]) || LEGACY_UNFENCED.equals(parts[0])
|
||||
|| LEGACY_REJECTED.equals(parts[0]))) {
|
||||
String key = decode(parts[1]);
|
||||
Entry entry = entries.get(key);
|
||||
if (entry == null || entry.awaitingReceiptRelease()) {
|
||||
if (entry == null || entry.awaitingReceiptRelease() || entry.deferredUpdate()) {
|
||||
throw new IllegalArgumentException("Legacy transition without pending vote");
|
||||
}
|
||||
entries.put(key, new Entry(entry.server(), entry.envelope(), false,
|
||||
@@ -204,8 +275,14 @@ final class ReliableVoteDeliveryOutbox {
|
||||
throw new IOException("Malformed vote delivery outbox entry", malformed);
|
||||
}
|
||||
journalRecords++;
|
||||
if (entries.size() > MAX_ENTRIES) throw new IOException("Vote delivery outbox exceeds entry limit");
|
||||
if (entries.size() > MAX_ENTRIES + MAX_UPDATE_ENTRIES + MAX_DEFERRED_UPDATE_ENTRIES)
|
||||
throw new IOException("Vote delivery outbox exceeds entry limit");
|
||||
}
|
||||
long deferred = entries.values().stream().filter(Entry::deferredUpdate).count();
|
||||
long updates = entries.values().stream().filter(entry ->
|
||||
VotingPluginWire.SUB_VOTE_UPDATE.equals(entry.envelope().getSubChannel())).count();
|
||||
if (deferred > MAX_DEFERRED_UPDATE_ENTRIES || updates - deferred > MAX_UPDATE_ENTRIES
|
||||
|| entries.size() - updates > MAX_ENTRIES) throw new IOException("Vote delivery outbox exceeds lane limit");
|
||||
if (unterminatedTail && !compact()) throw new IOException("Unable to repair vote delivery outbox");
|
||||
}
|
||||
|
||||
@@ -237,6 +314,7 @@ final class ReliableVoteDeliveryOutbox {
|
||||
private long terminalRecordReserve(Entry entry) {
|
||||
String key = key(entry.server(), entry.envelope());
|
||||
long reserve = utf8Length(removalRecord(key));
|
||||
if (entry.deferredUpdate()) reserve += utf8Length(READY + '\t' + encode(key) + '\n');
|
||||
if (!entry.awaitingReceiptRelease()) {
|
||||
reserve += utf8Length(completionRecord(key));
|
||||
String fence = legacyFenceRecord(key, true);
|
||||
@@ -270,7 +348,7 @@ final class ReliableVoteDeliveryOutbox {
|
||||
try {
|
||||
StringBuilder text = new StringBuilder(HEADER).append('\n');
|
||||
for (Entry entry : entries.values()) {
|
||||
text.append(addRecord(entry.server(), entry.envelope()));
|
||||
text.append(addRecord(entry.server(), entry.envelope(), entry.deferredUpdate()));
|
||||
if (entry.awaitingReceiptRelease()) {
|
||||
text.append(COMPLETED).append('\t').append(encode(key(entry.server(), entry.envelope()))).append('\n');
|
||||
} else if (entry.legacyDeliveryFenced()) {
|
||||
@@ -293,8 +371,8 @@ final class ReliableVoteDeliveryOutbox {
|
||||
}
|
||||
}
|
||||
|
||||
private static String addRecord(String server, JsonEnvelope envelope) {
|
||||
return ADD + '\t' + encode(server) + '\t' + encode(JsonEnvelopeCodec.encode(envelope)) + '\n';
|
||||
private static String addRecord(String server, JsonEnvelope envelope, boolean deferred) {
|
||||
return (deferred ? DEFERRED : ADD) + '\t' + encode(server) + '\t' + encode(JsonEnvelopeCodec.encode(envelope)) + '\n';
|
||||
}
|
||||
|
||||
private static String completionRecord(String key) {
|
||||
@@ -322,6 +400,7 @@ final class ReliableVoteDeliveryOutbox {
|
||||
String subChannel = envelope.getSubChannel();
|
||||
if (!VotingPluginWire.SUB_VOTE.equals(subChannel)
|
||||
&& !VotingPluginWire.SUB_VOTE_ONLINE.equals(subChannel)
|
||||
&& !VotingPluginWire.SUB_VOTE_UPDATE.equals(subChannel)
|
||||
&& !VotingPluginWire.SUB_VOTE_DELAY_REJECTED.equals(subChannel)) return null;
|
||||
String voteId = envelope.getFields().get(VotingPluginWire.K_VOTE_ID);
|
||||
try {
|
||||
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
package com.bencodez.votingplugin.proxy;
|
||||
|
||||
/** Optional occurrence metadata in existing opaque cache payloads, separate from cooldown time. */
|
||||
public final class VoteOccurrenceMetadata {
|
||||
private static final String MARKER = "//vp-occurrence-time:";
|
||||
|
||||
private VoteOccurrenceMetadata() { }
|
||||
|
||||
/** Null means an older payload without metadata; -1 means explicitly invalid metadata. */
|
||||
public static Long read(String payload) {
|
||||
if (payload == null) return null;
|
||||
int marker = payload.lastIndexOf(MARKER);
|
||||
if (marker < 0) return null;
|
||||
if (marker != payload.indexOf(MARKER)) return -1L;
|
||||
return parse(payload.substring(marker + MARKER.length(),
|
||||
Math.min(payload.length(), marker + MARKER.length() + 21)));
|
||||
}
|
||||
|
||||
public static long parse(String raw) {
|
||||
if (raw == null || raw.isEmpty() || raw.length() > 20) return -1L;
|
||||
try {
|
||||
long time = Long.parseLong(raw);
|
||||
return time > 0 ? time : -1L;
|
||||
} catch (NumberFormatException invalid) {
|
||||
return -1L;
|
||||
}
|
||||
}
|
||||
|
||||
/** Existing v1/v2 totals parsers ignore this tagged trailing token. */
|
||||
public static String store(String payload, long occurredAt) {
|
||||
String text = payload == null ? "" : payload;
|
||||
int marker = text.indexOf(MARKER);
|
||||
if (marker >= 0) text = text.substring(0, marker);
|
||||
return text + MARKER + (occurredAt > 0 ? occurredAt : -1L);
|
||||
}
|
||||
|
||||
/** An occurrence tag alone does not represent a processed totals snapshot. */
|
||||
public static boolean hasPayload(String payload) {
|
||||
return payload != null && !payload.isEmpty() && !payload.startsWith(MARKER);
|
||||
}
|
||||
|
||||
public static String preserve(String oldPayload, String updatedPayload) {
|
||||
Long original = read(oldPayload);
|
||||
return original == null ? updatedPayload : store(updatedPayload, original);
|
||||
}
|
||||
}
|
||||
+1021
-180
File diff suppressed because it is too large.
Load diff
@@ -34,6 +34,7 @@ public final class VotingPluginWire {
|
||||
}
|
||||
|
||||
public static final int SCHEMA_VERSION = 1;
|
||||
public static final String K_CANONICAL_OCCURRENCE_TIME = "canonicalOccurrenceTime";
|
||||
|
||||
// =========================
|
||||
// Subchannels (canonical)
|
||||
@@ -41,6 +42,11 @@ public final class VotingPluginWire {
|
||||
public static final String SUB_VOTE = "Vote";
|
||||
public static final String SUB_VOTE_ONLINE = "VoteOnline";
|
||||
public static final String SUB_VOTE_UPDATE = "VoteUpdate";
|
||||
/** Internal queue metadata; never a backend delivery target. */
|
||||
public static final String REWARD_QUEUE_METADATA_PREFIX = "__vp_reward\0";
|
||||
public static final String ACCEPTED_REWARD_TARGET_PREFIX = REWARD_QUEUE_METADATA_PREFIX + "accepted:";
|
||||
public static final String REWARD_ROUTING_MODE_KEY = REWARD_QUEUE_METADATA_PREFIX + "routing";
|
||||
public static final String PLANNED_REWARD_TARGET_PREFIX = REWARD_QUEUE_METADATA_PREFIX + "target:";
|
||||
public static final String SUB_VOTE_DELAY_REJECTED = "VoteDelayRejected";
|
||||
public static final String SUB_VOTE_BROADCAST = "VoteBroadcast";
|
||||
public static final String SUB_VOTE_DELIVERY_ACK = "VoteDeliveryAck";
|
||||
@@ -177,13 +183,16 @@ public final class VotingPluginWire {
|
||||
private static JsonEnvelope.Builder voteBuilder(String subChannel, String player, String uuid, String service,
|
||||
long time, boolean wasOnline, boolean realVote, String totals, UUID voteId, boolean manageTotals,
|
||||
boolean bungeeBroadcast, int num, int numberOfVotes) {
|
||||
return base(subChannel).put(K_PLAYER, safe(player)).put(K_UUID, safe(uuid)).put(K_SERVICE, safe(service))
|
||||
JsonEnvelope.Builder builder = base(subChannel).put(K_PLAYER, safe(player)).put(K_UUID, safe(uuid)).put(K_SERVICE, safe(service))
|
||||
.put(K_TIME, time).put(K_WAS_ONLINE, wasOnline).put(K_WAS_ONLINE_KNOWN, true)
|
||||
.put(K_REAL_VOTE, realVote).put(K_TOTALS, safe(totals))
|
||||
.put(K_VOTE_ID, voteId == null ? "" : voteId.toString()).put(K_SET_TOTALS, true)
|
||||
.put(K_MANAGE_TOTALS, manageTotals).put(K_QUEUED_DELIVERY, false)
|
||||
.put(K_BUNGEE_BROADCAST, bungeeBroadcast).put(K_NUM, num)
|
||||
.put(K_NUMBER_OF_VOTES, numberOfVotes);
|
||||
Long occurrence = VoteOccurrenceMetadata.read(totals);
|
||||
builder.put(K_CANONICAL_OCCURRENCE_TIME, occurrence == null ? time : occurrence);
|
||||
return builder;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -209,12 +218,15 @@ public final class VotingPluginWire {
|
||||
private static JsonEnvelope.Builder multiProxyVoteBuilder(String subChannel, String player, String uuid,
|
||||
String service, long time, boolean wasOnline, boolean realVote, String totals, UUID voteId,
|
||||
boolean manageTotals, boolean bungeeBroadcast, int num, int numberOfVotes, String origin) {
|
||||
return base(subChannel).put(K_PLAYER, safe(player)).put(K_UUID, safe(uuid)).put(K_SERVICE, safe(service))
|
||||
JsonEnvelope.Builder builder = base(subChannel).put(K_PLAYER, safe(player)).put(K_UUID, safe(uuid)).put(K_SERVICE, safe(service))
|
||||
.put(K_TIME, time).put(K_WAS_ONLINE, wasOnline).put(K_WAS_ONLINE_KNOWN, true).put(K_REAL_VOTE, realVote).put(K_TOTALS, safe(totals))
|
||||
.put(K_VOTE_ID, voteId == null ? "" : voteId.toString()).put(K_SET_TOTALS, true)
|
||||
.put(K_MANAGE_TOTALS, manageTotals).put(K_QUEUED_DELIVERY, false)
|
||||
.put(K_BUNGEE_BROADCAST, bungeeBroadcast).put(K_NUM, num)
|
||||
.put(K_NUMBER_OF_VOTES, numberOfVotes).put(K_MULTI_PROXY_ORIGIN, safe(origin));
|
||||
Long occurrence = VoteOccurrenceMetadata.read(totals);
|
||||
builder.put(K_CANONICAL_OCCURRENCE_TIME, occurrence == null ? time : occurrence);
|
||||
return builder;
|
||||
}
|
||||
|
||||
/** Reliable multi-proxy variant of {@link #voteOnline}. */
|
||||
@@ -633,6 +645,7 @@ public final class VotingPluginWire {
|
||||
public final String uuid;
|
||||
public final String service;
|
||||
public final long time;
|
||||
public final long canonicalOccurrenceTime;
|
||||
|
||||
public final boolean wasOnline;
|
||||
public final boolean wasOnlineKnown;
|
||||
@@ -654,12 +667,13 @@ public final class VotingPluginWire {
|
||||
boolean wasOnlineKnown, boolean realVote, String totals, UUID voteId, boolean setTotals,
|
||||
boolean manageTotals, boolean delayValidated, boolean delayValidationKnown, boolean queuedDelivery,
|
||||
boolean queuedDeliveryKnown,
|
||||
boolean broadcast, int num, int numberOfVotes) {
|
||||
boolean broadcast, int num, int numberOfVotes, long canonicalOccurrenceTime) {
|
||||
this.subChannel = subChannel;
|
||||
this.player = player;
|
||||
this.uuid = uuid;
|
||||
this.service = service;
|
||||
this.time = time;
|
||||
this.canonicalOccurrenceTime = canonicalOccurrenceTime;
|
||||
this.wasOnline = wasOnline;
|
||||
this.wasOnlineKnown = wasOnlineKnown;
|
||||
this.realVote = realVote;
|
||||
@@ -690,6 +704,13 @@ public final class VotingPluginWire {
|
||||
final boolean wasOnlineKnown = readBool(f, K_WAS_ONLINE_KNOWN, false);
|
||||
final boolean realVote = readBool(f, K_REAL_VOTE, false);
|
||||
final String totals = safe(f.get(K_TOTALS));
|
||||
Long cachedOccurrence = VoteOccurrenceMetadata.read(totals);
|
||||
// Missing or malformed provenance excludes only date accounting. An older
|
||||
// intermediate proxy may have replaced ordinary time with its receipt time.
|
||||
long occurrence = f.containsKey(K_CANONICAL_OCCURRENCE_TIME)
|
||||
? VoteOccurrenceMetadata.parse(f.get(K_CANONICAL_OCCURRENCE_TIME))
|
||||
: cachedOccurrence == null ? -1L : cachedOccurrence;
|
||||
if (cachedOccurrence != null && (cachedOccurrence <= 0 || cachedOccurrence != occurrence)) occurrence = -1L;
|
||||
final UUID voteId = readUuid(f, K_VOTE_ID);
|
||||
|
||||
final boolean setTotals = readBool(f, K_SET_TOTALS, true);
|
||||
@@ -706,7 +727,7 @@ public final class VotingPluginWire {
|
||||
|
||||
return new Vote(sub, player, uuid, service, time, wasOnline, wasOnlineKnown, realVote, totals, voteId,
|
||||
setTotals, manageTotals, delayValidated, delayValidationKnown, queuedDelivery, queuedDeliveryKnown,
|
||||
broadcast, num, numberOfVotes);
|
||||
broadcast, num, numberOfVotes, occurrence);
|
||||
}
|
||||
|
||||
public static final class VoteDelayRejected {
|
||||
|
||||
+120
-43
@@ -1,6 +1,7 @@
|
||||
package com.bencodez.votingplugin.proxy.bungee;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.File;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
@@ -15,7 +16,9 @@ import com.bencodez.votingplugin.proxy.OfflineBungeeVote;
|
||||
import com.bencodez.votingplugin.proxy.cache.DataNode;
|
||||
import com.bencodez.votingplugin.proxy.cache.GsonDataNode;
|
||||
import com.bencodez.votingplugin.proxy.cache.IVoteCache;
|
||||
import com.bencodez.votingplugin.proxy.cache.VoteCacheDurability;
|
||||
import com.bencodez.votingplugin.proxy.cache.PendingVotePartyProxyEffects;
|
||||
import com.bencodez.votingplugin.proxy.cache.PendingPluginMessageVotePartyRewards;
|
||||
import com.bencodez.votingplugin.timequeue.VoteTimeQueue;
|
||||
import com.bencodez.votingplugin.util.DurableFiles;
|
||||
import com.google.gson.GsonBuilder;
|
||||
@@ -24,7 +27,9 @@ import com.google.gson.GsonBuilder;
|
||||
* JSON file-based vote cache for Bungee.
|
||||
*/
|
||||
public class BungeeJsonVoteCache extends BungeeJsonFile implements IVoteCache {
|
||||
private VotingPluginBungee bungee;
|
||||
private VotingPluginBungee bungee;
|
||||
private boolean writesPaused;
|
||||
private boolean journalLoaded;
|
||||
|
||||
/**
|
||||
* Constructs a new BungeeJsonVoteCache.
|
||||
@@ -45,7 +50,7 @@ public class BungeeJsonVoteCache extends BungeeJsonFile implements IVoteCache {
|
||||
reload();
|
||||
}
|
||||
|
||||
public void addTimedVote(int num, VoteTimeQueue voteTimedQueue) {
|
||||
public synchronized void addTimedVote(int num, VoteTimeQueue voteTimedQueue) {
|
||||
String path = "TimedVoteCache." + num;
|
||||
setString(path + ".Name", voteTimedQueue.getName());
|
||||
setString(path + ".Service", voteTimedQueue.getService());
|
||||
@@ -78,13 +83,60 @@ public class BungeeJsonVoteCache extends BungeeJsonFile implements IVoteCache {
|
||||
}
|
||||
|
||||
@Override
|
||||
public java.nio.file.Path getStoragePath() {
|
||||
public synchronized java.nio.file.Path getStoragePath() {
|
||||
return getFile().toPath();
|
||||
}
|
||||
|
||||
/** Routine saves use the same atomic publication and reload failure fence as journal writes. */
|
||||
@Override
|
||||
public synchronized void save() {
|
||||
if (writesPaused) return;
|
||||
try {
|
||||
saveDurably();
|
||||
} catch (IOException failure) {
|
||||
java.util.logging.Logger.getLogger(getClass().getName())
|
||||
.log(java.util.logging.Level.WARNING, "Unable to save the vote cache", failure);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized void reload() {
|
||||
try {
|
||||
var loaded = VoteCacheDurability.readJournal(getStoragePath());
|
||||
PendingPluginMessageVotePartyRewards.fromCacheJson(loaded);
|
||||
super.setConf(loaded);
|
||||
writesPaused = false;
|
||||
journalLoaded = true;
|
||||
} catch (IOException failure) {
|
||||
writesPaused = true;
|
||||
throw new UncheckedIOException("Unable to reload the vote cache", failure);
|
||||
} catch (RuntimeException failure) {
|
||||
writesPaused = true;
|
||||
throw failure;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized com.google.gson.JsonObject getConf() { return super.getConf(); }
|
||||
|
||||
@Override
|
||||
public synchronized void setConf(com.google.gson.JsonObject conf) { super.setConf(conf); }
|
||||
|
||||
@Override
|
||||
public synchronized void saveDurably() throws IOException {
|
||||
if (writesPaused) throw new IOException("Vote cache writes require a successful reload");
|
||||
Path target = getStoragePath().toAbsolutePath().normalize();
|
||||
com.google.gson.JsonObject previous = null;
|
||||
if (journalLoaded) {
|
||||
try {
|
||||
previous = VoteCacheDurability.readJournal(target);
|
||||
PendingPluginMessageVotePartyRewards.fromCacheJson(previous);
|
||||
}
|
||||
catch (IOException | RuntimeException failure) {
|
||||
writesPaused = true;
|
||||
throw new IOException("Vote cache is unreadable; reload is required before saving", failure);
|
||||
}
|
||||
}
|
||||
Path parent = target.getParent();
|
||||
if (parent == null) throw new IOException("Vote cache has no parent directory");
|
||||
Files.createDirectories(parent);
|
||||
@@ -92,13 +144,18 @@ public class BungeeJsonVoteCache extends BungeeJsonFile implements IVoteCache {
|
||||
try {
|
||||
Files.writeString(staged, new GsonBuilder().setPrettyPrinting().create().toJson(getConf()),
|
||||
StandardCharsets.UTF_8);
|
||||
var candidate = VoteCacheDurability.readJournal(staged);
|
||||
if (previous != null && hasEmergencyJournalMarker()
|
||||
&& VoteCacheDurability.preserveUnresolvedCacheRows(previous, candidate))
|
||||
Files.writeString(staged, candidate.toString(), StandardCharsets.UTF_8);
|
||||
PendingPluginMessageVotePartyRewards.fromCacheJson(VoteCacheDurability.readJournal(staged));
|
||||
DurableFiles.publishStagedFile(staged, target);
|
||||
} finally {
|
||||
Files.deleteIfExists(staged);
|
||||
}
|
||||
}
|
||||
|
||||
public void addVote(String server, int num, OfflineBungeeVote voteData) {
|
||||
public synchronized void addVote(String server, int num, OfflineBungeeVote voteData) {
|
||||
String path = "VoteCache." + server + "." + num;
|
||||
setString(path + ".Name", voteData.getPlayerName());
|
||||
setString(path + ".Service", voteData.getService());
|
||||
@@ -117,10 +174,13 @@ public class BungeeJsonVoteCache extends BungeeJsonFile implements IVoteCache {
|
||||
setString(path + ".BroadcastForwardedServers", voteData.encodeBroadcastForwardedServers());
|
||||
setBoolean(path + ".RewardDelivered", voteData.isRewardDelivered());
|
||||
setString(path + ".HttpDeliveryIds", voteData.encodeHttpDeliveryIds());
|
||||
setInt(path + ".CachedBatchNumber", voteData.getCachedBatchNumber());
|
||||
setInt(path + ".CachedBatchSize", voteData.getCachedBatchSize());
|
||||
setInt(path + ".CachedBatchSourceRowId", voteData.getCachedBatchSourceRowId());
|
||||
setString(path + ".HttpBroadcastDeliveryIds", voteData.encodeHttpBroadcastDeliveryIds());
|
||||
}
|
||||
|
||||
public void addVoteOnline(String player, int num, OfflineBungeeVote voteData) {
|
||||
public synchronized void addVoteOnline(String player, int num, OfflineBungeeVote voteData) {
|
||||
String path = "OnlineCache." + player + "." + num;
|
||||
setString(path + ".Name", voteData.getPlayerName());
|
||||
setString(path + ".Service", voteData.getService());
|
||||
@@ -139,59 +199,82 @@ public class BungeeJsonVoteCache extends BungeeJsonFile implements IVoteCache {
|
||||
setString(path + ".BroadcastForwardedServers", voteData.encodeBroadcastForwardedServers());
|
||||
setBoolean(path + ".RewardDelivered", voteData.isRewardDelivered());
|
||||
setString(path + ".HttpDeliveryIds", voteData.encodeHttpDeliveryIds());
|
||||
setInt(path + ".CachedBatchNumber", voteData.getCachedBatchNumber());
|
||||
setInt(path + ".CachedBatchSize", voteData.getCachedBatchSize());
|
||||
setInt(path + ".CachedBatchSourceRowId", voteData.getCachedBatchSourceRowId());
|
||||
setString(path + ".HttpBroadcastDeliveryIds", voteData.encodeHttpBroadcastDeliveryIds());
|
||||
}
|
||||
|
||||
public void clearData() {
|
||||
public synchronized void clearData() {
|
||||
setString("VoteCache", null);
|
||||
setString("OnlineCache", null);
|
||||
setString("TimedVoteCache", null);
|
||||
save();
|
||||
}
|
||||
|
||||
public Collection<String> getOnlineVotes(String name) {
|
||||
public synchronized Collection<String> getOnlineVotes(String name) {
|
||||
return getKeys("OnlineCache." + name);
|
||||
}
|
||||
|
||||
public GsonDataNode getOnlineVotes(String name, String num) {
|
||||
public synchronized GsonDataNode getOnlineVotes(String name, String num) {
|
||||
return new GsonDataNode(getNode("OnlineCache." + name + "." + num));
|
||||
}
|
||||
|
||||
public Collection<String> getPlayers() {
|
||||
public synchronized Collection<String> getPlayers() {
|
||||
return getKeys("OnlineCache");
|
||||
}
|
||||
|
||||
public Collection<String> getServers() {
|
||||
public synchronized Collection<String> getServers() {
|
||||
return getKeys("VoteCache");
|
||||
}
|
||||
|
||||
public Collection<String> getServerVotes(String server) {
|
||||
public synchronized Collection<String> getServerVotes(String server) {
|
||||
return getKeys("VoteCache." + server);
|
||||
}
|
||||
|
||||
public GsonDataNode getServerVotes(String server, String num) {
|
||||
public synchronized GsonDataNode getServerVotes(String server, String num) {
|
||||
return new GsonDataNode(getNode("VoteCache." + server + "." + num));
|
||||
}
|
||||
|
||||
public Collection<String> getTimedVoteCache() {
|
||||
public synchronized Collection<String> getTimedVoteCache() {
|
||||
return getKeys("TimedVoteCache");
|
||||
}
|
||||
|
||||
public DataNode getTimedVoteCache(String key) {
|
||||
public synchronized DataNode getTimedVoteCache(String key) {
|
||||
return new GsonDataNode(getNode("TimedVoteCache." + key));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeTimedVotes() {
|
||||
public synchronized void removeTimedVotes() {
|
||||
setString("TimedVoteCache", null);
|
||||
}
|
||||
|
||||
public int getVotePartyCache(String server) {
|
||||
public synchronized int getVotePartyCache(String server) {
|
||||
return getInt("VoteParty.Cache." + server, 0);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<String> getPendingVotePartyRewardServers() {
|
||||
public synchronized PendingPluginMessageVotePartyRewards getPluginMessageVotePartyRewards() {
|
||||
return PendingPluginMessageVotePartyRewards.fromCacheJson(getConf());
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized void setPluginMessageVotePartyRewards(PendingPluginMessageVotePartyRewards rewards) {
|
||||
if (rewards == null) throw new IllegalArgumentException("Missing plugin-message vote-party backlog");
|
||||
com.google.gson.JsonElement current = getConf().get("VoteParty");
|
||||
com.google.gson.JsonObject party;
|
||||
if (current == null || current.isJsonNull()) {
|
||||
if (rewards.deliveries().isEmpty()) return;
|
||||
party = new com.google.gson.JsonObject();
|
||||
getConf().add("VoteParty", party);
|
||||
} else if (current.isJsonObject()) party = current.getAsJsonObject();
|
||||
else throw new IllegalArgumentException("Invalid vote-party cache");
|
||||
if (rewards.deliveries().isEmpty()) party.remove("PluginMessageRewards");
|
||||
else party.add("PluginMessageRewards", rewards.toJson());
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized Collection<String> getPendingVotePartyRewardServers() {
|
||||
Collection<String> encoded = getKeys("VoteParty.PendingRewards");
|
||||
Collection<String> servers = new ArrayList<>();
|
||||
if (encoded != null) for (String key : encoded) try {
|
||||
@@ -203,36 +286,36 @@ public class BungeeJsonVoteCache extends BungeeJsonFile implements IVoteCache {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<String> getPendingVotePartyRewardIds(String server) {
|
||||
public synchronized Collection<String> getPendingVotePartyRewardIds(String server) {
|
||||
return getKeys("VoteParty.PendingRewards." + encodeServerKey(server));
|
||||
}
|
||||
|
||||
@Override
|
||||
public PendingVotePartyProxyEffects getPendingVotePartyProxyEffects() {
|
||||
public synchronized PendingVotePartyProxyEffects getPendingVotePartyProxyEffects() {
|
||||
return new PendingVotePartyProxyEffects(getString("VoteParty.PendingProxyEffects.Broadcast", ""),
|
||||
getStringList("VoteParty.PendingProxyEffects.Commands", java.util.List.of()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public PendingVotePartyProxyEffects getQuarantinedVotePartyProxyEffects() {
|
||||
public synchronized PendingVotePartyProxyEffects getQuarantinedVotePartyProxyEffects() {
|
||||
return new PendingVotePartyProxyEffects(getString("VoteParty.QuarantinedProxyEffects.Broadcast", ""),
|
||||
getStringList("VoteParty.QuarantinedProxyEffects.Commands", java.util.List.of()));
|
||||
}
|
||||
|
||||
public int getVotePartyCurrentVotes() {
|
||||
public synchronized int getVotePartyCurrentVotes() {
|
||||
return getInt("VoteParty.CurrentVotes", 0);
|
||||
}
|
||||
|
||||
public int getVotePartyInreaseVotesRequired() {
|
||||
public synchronized int getVotePartyInreaseVotesRequired() {
|
||||
return getInt("VoteParty.IncreaseVotes", 0);
|
||||
}
|
||||
|
||||
public void setVotePartyCache(String server, int amount) {
|
||||
public synchronized void setVotePartyCache(String server, int amount) {
|
||||
setInt("VoteParty.Cache." + server, amount);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setPendingVotePartyReward(String server, String deliveryId, boolean pending) {
|
||||
public synchronized void setPendingVotePartyReward(String server, String deliveryId, boolean pending) {
|
||||
String serverPath = "VoteParty.PendingRewards." + encodeServerKey(server);
|
||||
String path = serverPath + "." + deliveryId;
|
||||
if (pending) setBoolean(path, true);
|
||||
@@ -244,7 +327,7 @@ public class BungeeJsonVoteCache extends BungeeJsonFile implements IVoteCache {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setPendingVotePartyProxyEffects(PendingVotePartyProxyEffects effects) {
|
||||
public synchronized void setPendingVotePartyProxyEffects(PendingVotePartyProxyEffects effects) {
|
||||
if (effects.isEmpty()) {
|
||||
remove("VoteParty.PendingProxyEffects");
|
||||
return;
|
||||
@@ -254,7 +337,7 @@ public class BungeeJsonVoteCache extends BungeeJsonFile implements IVoteCache {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setQuarantinedVotePartyProxyEffects(PendingVotePartyProxyEffects effects) {
|
||||
public synchronized void setQuarantinedVotePartyProxyEffects(PendingVotePartyProxyEffects effects) {
|
||||
if (effects.isEmpty()) {
|
||||
remove("VoteParty.QuarantinedProxyEffects");
|
||||
return;
|
||||
@@ -272,36 +355,30 @@ public class BungeeJsonVoteCache extends BungeeJsonFile implements IVoteCache {
|
||||
return new String(Base64.getUrlDecoder().decode(server), StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
public void setVotePartyCurrentVotes(int amount) {
|
||||
public synchronized void setVotePartyCurrentVotes(int amount) {
|
||||
setInt("VoteParty.CurrentVotes", amount);
|
||||
}
|
||||
|
||||
public void setVotePartyInreaseVotesRequired(int amount) {
|
||||
public synchronized void setVotePartyInreaseVotesRequired(int amount) {
|
||||
setInt("VoteParty.IncreaseVotes", amount);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void save() {
|
||||
super.save();
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
public void reload() {
|
||||
super.reload();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeOnlineVotes(String player) {
|
||||
public synchronized void removeOnlineVotes(String player) {
|
||||
setString("OnlineCache." + player, null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeServerVotes(String server) {
|
||||
public synchronized void removeServerVotes(String server) {
|
||||
setString("VoteCache." + server, null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeServerVote(String server, String uuid) {
|
||||
public synchronized void removeServerVote(String server, String uuid) {
|
||||
Collection<String> votes = getServerVotes(server);
|
||||
if (votes == null) {
|
||||
return;
|
||||
@@ -324,7 +401,7 @@ public class BungeeJsonVoteCache extends BungeeJsonFile implements IVoteCache {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeVote(String server, OfflineBungeeVote vote) {
|
||||
public synchronized void removeVote(String server, OfflineBungeeVote vote) {
|
||||
if (vote.getServerVoteCacheJsonKey() != null) {
|
||||
setString("VoteCache." + server + "." + vote.getServerVoteCacheJsonKey(), null);
|
||||
return;
|
||||
@@ -363,7 +440,7 @@ public class BungeeJsonVoteCache extends BungeeJsonFile implements IVoteCache {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeOnlineVote(OfflineBungeeVote vote) {
|
||||
public synchronized void removeOnlineVote(OfflineBungeeVote vote) {
|
||||
if (vote.getOnlineVoteCacheJsonKey() != null && vote.getUuid() != null) {
|
||||
setString("OnlineCache." + vote.getUuid() + "." + vote.getOnlineVoteCacheJsonKey(), null);
|
||||
return;
|
||||
|
||||
+15
-2
@@ -36,6 +36,7 @@ import com.bencodez.votingplugin.proxy.VotingPluginProxy;
|
||||
import com.bencodez.votingplugin.proxy.VotingPluginProxyConfig;
|
||||
import com.bencodez.votingplugin.proxy.VotingPluginProxy.VoteRetryException;
|
||||
import com.bencodez.votingplugin.util.MinecraftUsernameValidator;
|
||||
import com.bencodez.votingplugin.util.ServiceSiteValidator;
|
||||
import com.bencodez.votingplugin.timequeue.VoteTimeQueue;
|
||||
|
||||
import lombok.Getter;
|
||||
@@ -613,6 +614,18 @@ public class VotingPluginBungee extends Plugin implements Listener {
|
||||
}
|
||||
}
|
||||
|
||||
/** Captured ingress survives scheduler/reload/identity-resolution delays. */
|
||||
public IncomingVoteRuntimeResult processIncomingVote(String player, String service, UUID voteId, long occurredAt) {
|
||||
if (reloading) return IncomingVoteRuntimeResult.RETRY_AFTER_RELOAD;
|
||||
synchronized (reloadLock) {
|
||||
if (reloading) return IncomingVoteRuntimeResult.RETRY_AFTER_RELOAD;
|
||||
VotingPluginProxy runtime = votingPluginProxy;
|
||||
if (!runtimeOperational || runtime == null) return IncomingVoteRuntimeResult.RUNTIME_UNAVAILABLE;
|
||||
runtime.vote(player, service, true, true, 0, null, null, voteId, occurredAt);
|
||||
return IncomingVoteRuntimeResult.PROCESSED;
|
||||
}
|
||||
}
|
||||
|
||||
/** Owns a Votifier event before any fallible scheduler handoff. */
|
||||
public void acceptIncomingVote(String player, String service) {
|
||||
PendingIncomingVote pending = pendingIncomingVotes.admit(player, service);
|
||||
@@ -671,12 +684,12 @@ public class VotingPluginBungee extends Plugin implements Listener {
|
||||
try {
|
||||
IncomingVoteRuntimeResult result;
|
||||
synchronized (reloadLock) {
|
||||
result = processIncomingVote(pending.getPlayer(), pending.getService(), pending.getVoteId());
|
||||
result = processIncomingVote(pending.getPlayer(), pending.getService(), pending.getVoteId(), pending.getAcceptedAt());
|
||||
if (result == IncomingVoteRuntimeResult.PROCESSED) pendingIncomingVotes.complete(pending);
|
||||
}
|
||||
if (result == IncomingVoteRuntimeResult.PROCESSED) {
|
||||
getLogger().info("Vote received " + MinecraftUsernameValidator.sanitizeForLog(pending.getPlayer())
|
||||
+ " from service site " + MinecraftUsernameValidator.sanitizeForLog(pending.getService()));
|
||||
+ " from service site " + ServiceSiteValidator.sanitizeForLog(pending.getService()));
|
||||
return;
|
||||
}
|
||||
if (result == IncomingVoteRuntimeResult.RETRY_AFTER_RELOAD) {
|
||||
|
||||
+12
@@ -225,6 +225,18 @@ public interface IVoteCache {
|
||||
|
||||
PendingVotePartyProxyEffects getQuarantinedVotePartyProxyEffects();
|
||||
|
||||
/** Legacy storage implementations have no plugin-message party backlog. */
|
||||
default PendingPluginMessageVotePartyRewards getPluginMessageVotePartyRewards() {
|
||||
return PendingPluginMessageVotePartyRewards.empty();
|
||||
}
|
||||
|
||||
/** Unsupported storage must never accept ownership of a nonempty backlog. */
|
||||
default void setPluginMessageVotePartyRewards(PendingPluginMessageVotePartyRewards rewards) {
|
||||
if (rewards == null) throw new IllegalArgumentException("Missing plugin-message vote-party backlog");
|
||||
if (!rewards.deliveries().isEmpty())
|
||||
throw new UnsupportedOperationException("Storage does not support plugin-message vote-party rewards");
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the current vote party votes.
|
||||
*
|
||||
|
||||
+189
@@ -0,0 +1,189 @@
|
||||
package com.bencodez.votingplugin.proxy.cache;
|
||||
|
||||
import java.nio.CharBuffer;
|
||||
import java.nio.charset.CharacterCodingException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.GsonBuilder;
|
||||
import com.google.gson.JsonArray;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
|
||||
/** Immutable, bounded ownership of plugin-message vote-party handoffs. */
|
||||
public record PendingPluginMessageVotePartyRewards(List<Delivery> deliveries) {
|
||||
|
||||
public static final int MAX_DELIVERIES = 1_024;
|
||||
public static final int MAX_SERVERS = 256;
|
||||
public static final int MAX_PER_SERVER = 64;
|
||||
public static final int MAX_SERVER_BYTES = 256;
|
||||
public static final int MAX_SERIALIZED_BYTES = 512 * 1_024;
|
||||
private static final Gson JSON = new GsonBuilder().setPrettyPrinting().create();
|
||||
private static final Set<String> FIELDS = Set.of("batchId", "deliveryId", "server", "state");
|
||||
private static final PendingPluginMessageVotePartyRewards EMPTY =
|
||||
new PendingPluginMessageVotePartyRewards(List.of());
|
||||
|
||||
public enum State { READY, HANDOFF_FENCED }
|
||||
|
||||
public record Delivery(UUID batchId, UUID deliveryId, String server, State state) {
|
||||
public Delivery {
|
||||
if (batchId == null || deliveryId == null || state == null || server == null)
|
||||
throw new IllegalArgumentException("Missing plugin-message vote-party delivery field");
|
||||
// Keep the configured routing name exact; capacity keys are normalized separately.
|
||||
if (server.trim().isEmpty() || server.codePoints().anyMatch(Character::isISOControl)
|
||||
|| utf8Size(server) > MAX_SERVER_BYTES)
|
||||
throw new IllegalArgumentException("Invalid plugin-message vote-party server");
|
||||
}
|
||||
}
|
||||
|
||||
public PendingPluginMessageVotePartyRewards {
|
||||
if (deliveries == null || deliveries.size() > MAX_DELIVERIES)
|
||||
throw new IllegalArgumentException("Invalid plugin-message vote-party delivery count");
|
||||
List<Delivery> copied = new ArrayList<>(deliveries.size());
|
||||
Set<UUID> ids = new HashSet<>();
|
||||
Map<String, Integer> servers = new HashMap<>();
|
||||
for (Delivery delivery : deliveries) {
|
||||
if (delivery == null || !ids.add(delivery.deliveryId()))
|
||||
throw new IllegalArgumentException("Duplicate or missing plugin-message vote-party delivery");
|
||||
if (servers.merge(delivery.server().toLowerCase(Locale.ROOT), 1, Integer::sum) > MAX_PER_SERVER
|
||||
|| servers.size() > MAX_SERVERS)
|
||||
throw new IllegalArgumentException("Plugin-message vote-party server backlog exceeds limit");
|
||||
copied.add(delivery);
|
||||
}
|
||||
deliveries = List.copyOf(copied);
|
||||
JsonObject party = new JsonObject();
|
||||
party.add("PluginMessageRewards", encode(deliveries));
|
||||
JsonObject namespace = new JsonObject();
|
||||
namespace.add("VoteParty", party);
|
||||
if (utf8Size(JSON.toJson(namespace)) > MAX_SERIALIZED_BYTES)
|
||||
throw new IllegalArgumentException("Plugin-message vote-party backlog exceeds byte limit");
|
||||
}
|
||||
|
||||
public static PendingPluginMessageVotePartyRewards empty() { return EMPTY; }
|
||||
|
||||
public Optional<Delivery> find(UUID deliveryId) {
|
||||
if (deliveryId == null) throw new IllegalArgumentException("Missing delivery ID");
|
||||
return deliveries.stream().filter(delivery -> delivery.deliveryId().equals(deliveryId)).findFirst();
|
||||
}
|
||||
|
||||
/** Replaces only the state of an existing identity, without changing its position. */
|
||||
public PendingPluginMessageVotePartyRewards with(Delivery delivery) {
|
||||
if (delivery == null) throw new IllegalArgumentException("Missing delivery");
|
||||
List<Delivery> changed = new ArrayList<>(deliveries);
|
||||
for (int index = 0; index < changed.size(); index++) {
|
||||
Delivery existing = changed.get(index);
|
||||
if (!existing.deliveryId().equals(delivery.deliveryId())) continue;
|
||||
if (!existing.batchId().equals(delivery.batchId()) || !existing.server().equals(delivery.server()))
|
||||
throw new IllegalArgumentException("Conflicting plugin-message vote-party delivery identity");
|
||||
changed.set(index, delivery);
|
||||
return new PendingPluginMessageVotePartyRewards(changed);
|
||||
}
|
||||
changed.add(delivery);
|
||||
return new PendingPluginMessageVotePartyRewards(changed);
|
||||
}
|
||||
|
||||
public PendingPluginMessageVotePartyRewards without(UUID deliveryId) {
|
||||
if (deliveryId == null) throw new IllegalArgumentException("Missing delivery ID");
|
||||
List<Delivery> changed = deliveries.stream()
|
||||
.filter(delivery -> !delivery.deliveryId().equals(deliveryId)).toList();
|
||||
return changed.size() == deliveries.size() ? this : new PendingPluginMessageVotePartyRewards(changed);
|
||||
}
|
||||
|
||||
public PendingPluginMessageVotePartyRewards withState(UUID deliveryId, State state) {
|
||||
Delivery delivery = find(deliveryId)
|
||||
.orElseThrow(() -> new IllegalArgumentException("Unknown plugin-message vote-party delivery"));
|
||||
return with(new Delivery(delivery.batchId(), delivery.deliveryId(), delivery.server(), state));
|
||||
}
|
||||
|
||||
/** Returns a fresh JSON array; callers cannot mutate the retained snapshot. */
|
||||
public JsonArray toJson() { return encode(deliveries); }
|
||||
|
||||
/** Uses plain JSON-compatible values for the Configurate adapter. */
|
||||
public List<Map<String, String>> toStorageValue() {
|
||||
List<Map<String, String>> result = new ArrayList<>(deliveries.size());
|
||||
for (Delivery delivery : deliveries) {
|
||||
Map<String, String> fields = new LinkedHashMap<>();
|
||||
fields.put("batchId", delivery.batchId().toString());
|
||||
fields.put("deliveryId", delivery.deliveryId().toString());
|
||||
fields.put("server", delivery.server());
|
||||
fields.put("state", delivery.state().name());
|
||||
result.add(fields);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/** A missing namespace is legacy empty state; an explicit null is invalid. */
|
||||
public static PendingPluginMessageVotePartyRewards fromJson(JsonElement encoded) {
|
||||
if (encoded == null) return empty();
|
||||
if (!encoded.isJsonArray() || encoded.getAsJsonArray().size() > MAX_DELIVERIES)
|
||||
throw new IllegalArgumentException("Invalid plugin-message vote-party backlog");
|
||||
List<Delivery> deliveries = new ArrayList<>();
|
||||
for (JsonElement element : encoded.getAsJsonArray()) {
|
||||
if (!element.isJsonObject() || !element.getAsJsonObject().keySet().equals(FIELDS))
|
||||
throw new IllegalArgumentException("Invalid plugin-message vote-party delivery fields");
|
||||
JsonObject fields = element.getAsJsonObject();
|
||||
deliveries.add(new Delivery(uuid(fields, "batchId"), uuid(fields, "deliveryId"),
|
||||
string(fields, "server"), State.valueOf(string(fields, "state"))));
|
||||
}
|
||||
return new PendingPluginMessageVotePartyRewards(deliveries);
|
||||
}
|
||||
|
||||
/** Validates the new namespace without changing existing cache sections. */
|
||||
public static PendingPluginMessageVotePartyRewards fromCacheJson(JsonObject root) {
|
||||
if (root == null) throw new IllegalArgumentException("Missing vote cache");
|
||||
JsonElement party = root.get("VoteParty");
|
||||
if (party == null || party.isJsonNull()) return empty();
|
||||
if (!party.isJsonObject()) throw new IllegalArgumentException("Invalid vote-party cache");
|
||||
return fromJson(party.getAsJsonObject().get("PluginMessageRewards"));
|
||||
}
|
||||
|
||||
/** Converts the Configurate adapter's already-validated JSON-compatible values. */
|
||||
public static PendingPluginMessageVotePartyRewards fromStorageValue(Object value) {
|
||||
return value == null ? empty() : fromJson(JSON.toJsonTree(value));
|
||||
}
|
||||
|
||||
private static UUID uuid(JsonObject object, String field) {
|
||||
String value = string(object, field);
|
||||
if (value.length() != 36) throw new IllegalArgumentException("Invalid vote-party UUID");
|
||||
UUID parsed = UUID.fromString(value);
|
||||
if (!parsed.toString().equals(value)) throw new IllegalArgumentException("Noncanonical vote-party UUID");
|
||||
return parsed;
|
||||
}
|
||||
|
||||
private static String string(JsonObject object, String field) {
|
||||
JsonElement value = object.get(field);
|
||||
if (value == null || !value.isJsonPrimitive() || !value.getAsJsonPrimitive().isString())
|
||||
throw new IllegalArgumentException("Invalid plugin-message vote-party field type");
|
||||
return value.getAsString();
|
||||
}
|
||||
|
||||
private static JsonArray encode(List<Delivery> deliveries) {
|
||||
JsonArray result = new JsonArray();
|
||||
for (Delivery delivery : deliveries) {
|
||||
JsonObject fields = new JsonObject();
|
||||
fields.addProperty("batchId", delivery.batchId().toString());
|
||||
fields.addProperty("deliveryId", delivery.deliveryId().toString());
|
||||
fields.addProperty("server", delivery.server());
|
||||
fields.addProperty("state", delivery.state().name());
|
||||
result.add(fields);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static int utf8Size(String value) {
|
||||
try { return StandardCharsets.UTF_8.newEncoder().encode(CharBuffer.wrap(value)).remaining(); }
|
||||
catch (CharacterCodingException invalid) {
|
||||
throw new IllegalArgumentException("Invalid vote-party Unicode", invalid);
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
+28
@@ -132,6 +132,8 @@ public abstract class ProxyOnlineVoteCacheTable extends AbstractSqlTable {
|
||||
return;
|
||||
}
|
||||
|
||||
newText = com.bencodez.votingplugin.proxy.VoteOccurrenceMetadata.preserve(vote.getText(), newText);
|
||||
|
||||
String sql = "UPDATE " + qi(getTableName()) + " SET " + qi("text") + " = ?" + " WHERE " + qi("uuid")
|
||||
+ " = ? AND " + qi("service") + " = ? AND " + qi("time") + " = ?;";
|
||||
|
||||
@@ -440,6 +442,11 @@ public abstract class ProxyOnlineVoteCacheTable extends AbstractSqlTable {
|
||||
return selectVotes("SELECT * FROM " + qi(getTableName()) + ";", null);
|
||||
}
|
||||
|
||||
/** Reads the complete cache snapshot, preserving SQL failures for callers that need certainty. */
|
||||
public List<VoteRow> getAllVotesChecked() throws SQLException {
|
||||
return selectVotesChecked("SELECT * FROM " + qi(getTableName()) + ";", null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets all votes for a specific UUID.
|
||||
* @param uuid the player UUID
|
||||
@@ -552,6 +559,27 @@ public abstract class ProxyOnlineVoteCacheTable extends AbstractSqlTable {
|
||||
return list;
|
||||
}
|
||||
|
||||
private List<VoteRow> selectVotesChecked(String sql, Object[] params) throws SQLException {
|
||||
List<VoteRow> list = new ArrayList<>();
|
||||
try (Connection conn = mysql.getConnectionManager().getConnection();
|
||||
PreparedStatement ps = conn.prepareStatement(sql)) {
|
||||
if (params != null) for (int i = 0; i < params.length; i++) ps.setObject(i + 1, params[i]);
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
while (rs.next()) {
|
||||
list.add(new VoteRow(rs.getInt("id"), rs.getString("voteid"), rs.getString("uuid"),
|
||||
rs.getString("playerName"), rs.getString("service"), rs.getLong("time"),
|
||||
(getDbType() == DbType.POSTGRESQL ? rs.getBoolean("realVote") : rs.getInt("realVote") == 1),
|
||||
rs.getBoolean("wasOnline"), rs.getBoolean("wasOnlineKnown"), rs.getInt("delayValidation"),
|
||||
rs.getString("text"), rs.getBoolean("broadcastForwarded"), rs.getBoolean("proxyBroadcastHandled"),
|
||||
rs.getString("broadcastTargets"), rs.getString("broadcastForwardedServers"),
|
||||
rs.getBoolean("rewardDelivered"), rs.getString("httpDeliveryIds"),
|
||||
rs.getString("httpBroadcastDeliveryIds")));
|
||||
}
|
||||
}
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
/**
|
||||
* Represents a row in the online vote cache table.
|
||||
*/
|
||||
|
||||
Vendored
+27
@@ -458,6 +458,11 @@ public abstract class ProxyTimedVoteCacheTable extends AbstractSqlTable {
|
||||
return selectVotes("SELECT * FROM " + qi(getTableName()) + ";", null);
|
||||
}
|
||||
|
||||
/** Reads the complete cache snapshot, preserving SQL failures for callers that need certainty. */
|
||||
public List<TimedVoteRow> getAllVotesChecked() throws SQLException {
|
||||
return selectVotesChecked("SELECT * FROM " + qi(getTableName()) + ";", null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets expired votes before a given time.
|
||||
* @param now the current time in milliseconds
|
||||
@@ -592,6 +597,28 @@ public abstract class ProxyTimedVoteCacheTable extends AbstractSqlTable {
|
||||
return list;
|
||||
}
|
||||
|
||||
private List<TimedVoteRow> selectVotesChecked(String sql, Object[] params) throws SQLException {
|
||||
List<TimedVoteRow> list = new ArrayList<>();
|
||||
try (Connection conn = mysql.getConnectionManager().getConnection();
|
||||
PreparedStatement ps = conn.prepareStatement(sql)) {
|
||||
if (params != null) for (int i = 0; i < params.length; i++) ps.setObject(i + 1, params[i]);
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
while (rs.next()) list.add(new TimedVoteRow(rs.getInt("id"), rs.getString("playerName"),
|
||||
rs.getString("service"), rs.getLong("time"), parseUuid(rs.getString("voteId")),
|
||||
rs.getString("uuid"), rs.getBoolean("proxyBroadcastHandled"), rs.getString("broadcastTargets"),
|
||||
rs.getString("broadcastForwardedServers"), rs.getString("totals"), rs.getBoolean("processed"),
|
||||
rs.getBoolean("multiProxyForwardingHandled"), rs.getBoolean("multiProxyForwardingRequired"),
|
||||
rs.getBoolean("multiProxyCapabilityDiscoveryPending"), rs.getBoolean("realVote"),
|
||||
rs.getString("multiProxyOrigin"), rs.getBoolean("multiProxyCompletionPending"),
|
||||
rs.getString("multiProxyRecipients"), rs.getString("multiProxyAcknowledgedServers"),
|
||||
rs.getString("httpBroadcastDeliveryIds"), rs.getString("multiProxyLegacyPendingRecipients"),
|
||||
rs.getBoolean("wasOnline"), rs.getBoolean("wasOnlineKnown"), rs.getInt("delayValidation"),
|
||||
rs.getBoolean("votePartyApplied"), rs.getBoolean("totalsApplied")));
|
||||
}
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
private UUID parseUuid(String value) {
|
||||
if (value == null || value.isEmpty()) {
|
||||
return null;
|
||||
|
||||
+28
@@ -97,6 +97,8 @@ public abstract class ProxyVoteCacheTable extends AbstractSqlTable {
|
||||
return;
|
||||
}
|
||||
|
||||
newText = com.bencodez.votingplugin.proxy.VoteOccurrenceMetadata.preserve(vote.getText(), newText);
|
||||
|
||||
String sql = "UPDATE " + qi(getTableName()) + " SET " + qi("text") + " = ?" + " WHERE " + qi("uuid")
|
||||
+ " = ? AND " + qi("service") + " = ? AND " + qi("time") + " = ? AND " + qi("server") + " = ?;";
|
||||
|
||||
@@ -460,6 +462,11 @@ public abstract class ProxyVoteCacheTable extends AbstractSqlTable {
|
||||
return selectVotes("SELECT * FROM " + qi(getTableName()) + ";", null);
|
||||
}
|
||||
|
||||
/** Reads the complete cache snapshot, preserving SQL failures for callers that need certainty. */
|
||||
public List<VoteRow> getAllVotesChecked() throws SQLException {
|
||||
return selectVotesChecked("SELECT * FROM " + qi(getTableName()) + ";", null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets all votes for a specific server.
|
||||
* @param server the server name
|
||||
@@ -675,6 +682,27 @@ public abstract class ProxyVoteCacheTable extends AbstractSqlTable {
|
||||
return list;
|
||||
}
|
||||
|
||||
private List<VoteRow> selectVotesChecked(String sql, Object[] params) throws SQLException {
|
||||
List<VoteRow> list = new ArrayList<>();
|
||||
try (Connection conn = mysql.getConnectionManager().getConnection();
|
||||
PreparedStatement ps = conn.prepareStatement(sql)) {
|
||||
if (params != null) for (int i = 0; i < params.length; i++) ps.setObject(i + 1, params[i]);
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
while (rs.next()) {
|
||||
list.add(new VoteRow(rs.getInt("id"), rs.getString("voteid"), rs.getString("uuid"),
|
||||
rs.getString("playerName"), rs.getString("service"), rs.getLong("time"),
|
||||
(getDbType() == DbType.POSTGRESQL ? rs.getBoolean("realVote") : rs.getInt("realVote") == 1),
|
||||
rs.getBoolean("wasOnline"), rs.getBoolean("wasOnlineKnown"), rs.getInt("delayValidation"),
|
||||
rs.getString("text"), rs.getBoolean("broadcastForwarded"), rs.getBoolean("proxyBroadcastHandled"),
|
||||
rs.getString("broadcastTargets"), rs.getString("broadcastForwardedServers"),
|
||||
rs.getBoolean("rewardDelivered"), rs.getString("httpDeliveryIds"),
|
||||
rs.getString("httpBroadcastDeliveryIds"), rs.getString("server")));
|
||||
}
|
||||
}
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
/**
|
||||
* Represents a row in the vote cache table.
|
||||
*/
|
||||
|
||||
+381
-35
@@ -1,8 +1,21 @@
|
||||
package com.bencodez.votingplugin.proxy.cache;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.io.IOException;
|
||||
import java.util.Collection;
|
||||
import java.util.Objects;
|
||||
import java.util.function.BooleanSupplier;
|
||||
|
||||
import com.google.gson.JsonArray;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonNull;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonPrimitive;
|
||||
import com.google.gson.stream.JsonReader;
|
||||
import com.google.gson.stream.JsonToken;
|
||||
|
||||
import com.bencodez.votingplugin.proxy.OfflineBungeeVote;
|
||||
import com.bencodez.votingplugin.timequeue.VoteTimeQueue;
|
||||
import com.bencodez.votingplugin.util.DurableFiles;
|
||||
@@ -20,6 +33,351 @@ public final class VoteCacheDurability {
|
||||
|
||||
private VoteCacheDurability() { }
|
||||
|
||||
/** Reads a complete strict JSON object without silently recovering a partial journal. */
|
||||
public static JsonObject readJournal(Path path) throws IOException {
|
||||
try (JsonReader reader = new JsonReader(new StrictJsonInput(
|
||||
Files.newBufferedReader(path, StandardCharsets.UTF_8)))) {
|
||||
reader.setLenient(false);
|
||||
JsonElement document = readValue(reader, 0);
|
||||
if (!document.isJsonObject() || reader.peek() != JsonToken.END_DOCUMENT)
|
||||
throw new IOException("Vote cache must contain one JSON object");
|
||||
JsonObject journal = document.getAsJsonObject();
|
||||
validateTimedRows(journal);
|
||||
return journal;
|
||||
}
|
||||
}
|
||||
|
||||
/** Rejects timed recovery evidence that queue reconstruction cannot safely retain. */
|
||||
private static void validateTimedRows(JsonObject journal) throws IOException {
|
||||
if (!journal.has("TimedVoteCache")) return;
|
||||
JsonElement timed = journal.get("TimedVoteCache");
|
||||
if (!timed.isJsonObject()) throw new IOException("Invalid timed vote cache structure");
|
||||
for (var entry : timed.getAsJsonObject().entrySet()) {
|
||||
// Queue rewrites address rows by integer index. Aliases or out-of-range
|
||||
// keys cannot retain distinct durable owners through that representation.
|
||||
if (!entry.getKey().matches("0|[1-9][0-9]*"))
|
||||
throw new IOException("Timed vote cache key requires recovery");
|
||||
try { Integer.parseInt(entry.getKey()); }
|
||||
catch (NumberFormatException invalid) { throw new IOException("Timed vote cache key requires recovery"); }
|
||||
JsonElement row = entry.getValue();
|
||||
if (!row.isJsonObject()) throw new IOException("Timed vote cache entry requires recovery");
|
||||
JsonObject fields = row.getAsJsonObject();
|
||||
boolean readable = false;
|
||||
for (String name : new String[] {"Name", "UUID", "Service", "Time", "VoteId"})
|
||||
if (fields.has(name) && fields.get(name).isJsonPrimitive()) readable = true;
|
||||
if (!readable) throw new IOException("Timed vote cache entry requires recovery");
|
||||
try {
|
||||
// Check the fields consumed by timed reconstruction, including optional
|
||||
// progress. Unknown values and inactive conditional fields remain legacy data.
|
||||
for (String name : new String[] {"Name", "UUID", "Service", "Time", "VoteId",
|
||||
"ProxyBroadcastHandled", "BroadcastForwardedServers", "BroadcastTargets", "Totals",
|
||||
"Processed", "VotePartyApplied", "TotalsApplied", "MultiProxyForwardingHandled",
|
||||
"HttpBroadcastDeliveryIds", "MultiProxyForwardingRequired", "MultiProxyCapabilityDiscoveryPending",
|
||||
"RealVote", "WasOnlineKnown", "DelayValidationKnown", "MultiProxyOrigin",
|
||||
"MultiProxyCompletionPending", "MultiProxyRecipients", "MultiProxyAcknowledgedServers",
|
||||
"MultiProxyLegacyPendingRecipients"})
|
||||
if (fields.has(name) && !fields.get(name).isJsonPrimitive())
|
||||
throw new IOException("Timed vote cache entry requires recovery");
|
||||
if (fields.has("Time")) fields.get("Time").getAsLong();
|
||||
if (fields.has("VoteId") && !fields.get("VoteId").getAsString().isEmpty())
|
||||
java.util.UUID.fromString(fields.get("VoteId").getAsString());
|
||||
if (fields.has("WasOnlineKnown") && fields.get("WasOnlineKnown").getAsBoolean()
|
||||
&& (!fields.has("WasOnline") || !fields.get("WasOnline").isJsonPrimitive()))
|
||||
throw new IOException("Timed vote cache entry requires recovery");
|
||||
if (fields.has("DelayValidationKnown") && fields.get("DelayValidationKnown").getAsBoolean()
|
||||
&& fields.has("DelayValidated") && !fields.get("DelayValidated").isJsonPrimitive())
|
||||
throw new IOException("Timed vote cache entry requires recovery");
|
||||
} catch (RuntimeException invalid) {
|
||||
throw new IOException("Timed vote cache entry requires recovery");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Retains opaque recovery records while an unrelated healthy vote is updated or removed. */
|
||||
public static boolean preserveUnresolvedCacheRows(JsonObject previous, JsonObject candidate) {
|
||||
boolean changed = false;
|
||||
// JSON adapters may omit null/empty children. Successful updates of healthy votes
|
||||
// must not erase another record's unresolved recovery evidence.
|
||||
for (String lane : new String[] {"VoteCache", "OnlineCache"}) {
|
||||
if (!previous.has(lane)) continue;
|
||||
JsonElement owners = previous.get(lane);
|
||||
if (!owners.isJsonObject()) { changed |= preserveValue(candidate, lane, owners); continue; }
|
||||
for (var owner : owners.getAsJsonObject().entrySet()) {
|
||||
if (!owner.getValue().isJsonObject()) {
|
||||
changed |= preserveValue(objectChild(candidate, lane), owner.getKey(), owner.getValue());
|
||||
continue;
|
||||
}
|
||||
for (var row : owner.getValue().getAsJsonObject().entrySet())
|
||||
if (unresolvedRow(row.getValue()))
|
||||
changed |= preserveValue(objectChild(objectChild(candidate, lane), owner.getKey()),
|
||||
row.getKey(), row.getValue());
|
||||
}
|
||||
}
|
||||
return changed;
|
||||
}
|
||||
|
||||
private static JsonObject objectChild(JsonObject parent, String key) {
|
||||
if (!parent.has(key) || !parent.get(key).isJsonObject()) parent.add(key, new JsonObject());
|
||||
return parent.getAsJsonObject(key);
|
||||
}
|
||||
|
||||
private static boolean unresolvedRow(JsonElement row) {
|
||||
if (!row.isJsonObject()) return true;
|
||||
JsonObject data = row.getAsJsonObject();
|
||||
if (isOpaqueRecoveryRow(new GsonDataNode(data)) || hasUndecodableVoteFields(data)) return true;
|
||||
if (!data.has("CachedBatchNumber") && !data.has("CachedBatchSize")
|
||||
&& !data.has("CachedBatchSourceRowId")) return false;
|
||||
try {
|
||||
for (String field : new String[] {"Name", "UUID", "Service", "Text"})
|
||||
if (!data.has(field) || !data.get(field).isJsonPrimitive()
|
||||
|| !data.getAsJsonPrimitive(field).isString()) return true;
|
||||
if (!data.has("Real") || !data.get("Real").isJsonPrimitive()
|
||||
|| !data.getAsJsonPrimitive("Real").isBoolean()
|
||||
|| !data.has("Time") || !data.get("Time").isJsonPrimitive()
|
||||
|| !data.getAsJsonPrimitive("Time").isNumber()) return true;
|
||||
new java.math.BigDecimal(data.get("Time").getAsString()).longValueExact();
|
||||
int[] values = new int[3];
|
||||
String[] fields = {"CachedBatchNumber", "CachedBatchSize", "CachedBatchSourceRowId"};
|
||||
for (int i = 0; i < fields.length; i++) {
|
||||
if (!data.has(fields[i]) || !data.get(fields[i]).isJsonPrimitive()
|
||||
|| !data.getAsJsonPrimitive(fields[i]).isNumber()) return true;
|
||||
values[i] = new java.math.BigDecimal(data.get(fields[i]).getAsString()).intValueExact();
|
||||
}
|
||||
return values[2] < 0 || !(values[0] == 0 && values[1] == 0
|
||||
|| values[0] > 0 && values[0] <= values[1]);
|
||||
} catch (RuntimeException invalid) { return true; }
|
||||
}
|
||||
|
||||
/** Shares opaque-row ownership classification between reconstruction and persistence. */
|
||||
static boolean isOpaqueRecoveryRow(DataNode data) {
|
||||
for (String field : new String[] {"Name", "UUID", "Service", "Time", "Real", "Text", "VoteId", "VoteID"}) {
|
||||
if (data.has(field)) {
|
||||
DataNode value = data.get(field);
|
||||
if (value != null && value.isPrimitive()) return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static boolean hasUndecodableVoteFields(JsonObject data) {
|
||||
// Match fields which recovery actually reads, including optional delivery state.
|
||||
// Do not classify unused/unknown null fields as broken legacy ownership.
|
||||
for (String field : new String[] {"Name", "UUID", "Service", "Time", "Real", "Text",
|
||||
"BroadcastForwarded", "ProxyBroadcastHandled", "BroadcastTargets", "BroadcastForwardedServers",
|
||||
"HttpDeliveryIds", "HttpBroadcastDeliveryIds", "RewardDelivered", "WasOnlineKnown",
|
||||
"DelayValidationKnown"})
|
||||
if (data.has(field) && !data.get(field).isJsonPrimitive()) return true;
|
||||
String idField = data.has("VoteId") ? "VoteId" : "VoteID";
|
||||
if (data.has(idField)) {
|
||||
if (!data.get(idField).isJsonPrimitive()) return true;
|
||||
String id = data.get(idField).getAsString();
|
||||
try { if (!id.isEmpty()) java.util.UUID.fromString(id); }
|
||||
catch (IllegalArgumentException invalid) { return true; }
|
||||
}
|
||||
if (data.has("WasOnlineKnown") && data.get("WasOnlineKnown").getAsBoolean()
|
||||
&& data.has("WasOnline") && !data.get("WasOnline").isJsonPrimitive()) return true;
|
||||
return data.has("DelayValidationKnown") && data.get("DelayValidationKnown").getAsBoolean()
|
||||
&& data.has("DelayValidated") && !data.get("DelayValidated").isJsonPrimitive();
|
||||
}
|
||||
|
||||
private static boolean preserveValue(JsonObject parent, String key, JsonElement value) {
|
||||
JsonElement current = parent.get(key);
|
||||
JsonElement retained = value.deepCopy();
|
||||
if (sameRecoveryOwner(value, current)) {
|
||||
// Keep corrupt identity/position evidence, but persist actual completion
|
||||
// progress of the same owner instead of silently reverting that update.
|
||||
JsonObject original = retained.getAsJsonObject(), updated = current.getAsJsonObject();
|
||||
for (String field : new String[] {"BroadcastForwarded", "ProxyBroadcastHandled", "BroadcastTargets",
|
||||
"BroadcastForwardedServers", "HttpDeliveryIds", "HttpBroadcastDeliveryIds", "RewardDelivered",
|
||||
"WasOnlineKnown", "WasOnline", "DelayValidationKnown", "DelayValidated"})
|
||||
if (updated.has(field)) original.add(field, updated.get(field).deepCopy());
|
||||
}
|
||||
if (retained.equals(current)) return false;
|
||||
parent.add(key, retained);
|
||||
return true;
|
||||
}
|
||||
|
||||
private static boolean sameRecoveryOwner(JsonElement previous, JsonElement candidate) {
|
||||
if (candidate == null || !previous.isJsonObject() || !candidate.isJsonObject()) return false;
|
||||
JsonObject left = previous.getAsJsonObject(), right = candidate.getAsJsonObject();
|
||||
try {
|
||||
java.util.UUID leftId = recoveryVoteId(left), rightId = recoveryVoteId(right);
|
||||
if (leftId != null || rightId != null) return leftId != null && leftId.equals(rightId);
|
||||
if (!left.has("CachedBatchSourceRowId") || !right.has("CachedBatchSourceRowId")
|
||||
|| !left.get("CachedBatchSourceRowId").isJsonPrimitive()
|
||||
|| !right.get("CachedBatchSourceRowId").isJsonPrimitive()
|
||||
|| !left.getAsJsonPrimitive("CachedBatchSourceRowId").isNumber()
|
||||
|| !right.getAsJsonPrimitive("CachedBatchSourceRowId").isNumber()) return false;
|
||||
int source = new java.math.BigDecimal(left.get("CachedBatchSourceRowId").getAsString()).intValueExact();
|
||||
if (source <= 0 || source != new java.math.BigDecimal(right.get("CachedBatchSourceRowId")
|
||||
.getAsString()).intValueExact()) return false;
|
||||
for (String field : new String[] {"Name", "UUID", "Service", "Text"})
|
||||
if (!left.has(field) || !right.has(field) || !left.get(field).isJsonPrimitive()
|
||||
|| !right.get(field).isJsonPrimitive() || !left.getAsJsonPrimitive(field).isString()
|
||||
|| !right.getAsJsonPrimitive(field).isString() || !left.get(field).equals(right.get(field))) return false;
|
||||
return left.has("Real") && right.has("Real") && left.get("Real").isJsonPrimitive()
|
||||
&& right.get("Real").isJsonPrimitive() && left.getAsJsonPrimitive("Real").isBoolean()
|
||||
&& right.getAsJsonPrimitive("Real").isBoolean() && left.get("Real").equals(right.get("Real"))
|
||||
&& left.has("Time") && right.has("Time") && left.get("Time").isJsonPrimitive()
|
||||
&& right.get("Time").isJsonPrimitive() && left.getAsJsonPrimitive("Time").isNumber()
|
||||
&& right.getAsJsonPrimitive("Time").isNumber()
|
||||
&& new java.math.BigDecimal(left.get("Time").getAsString()).longValueExact()
|
||||
== new java.math.BigDecimal(right.get("Time").getAsString()).longValueExact();
|
||||
} catch (RuntimeException invalid) { return false; }
|
||||
}
|
||||
|
||||
private static java.util.UUID recoveryVoteId(JsonObject data) {
|
||||
String field = data.has("VoteId") ? "VoteId" : "VoteID";
|
||||
if (!data.has(field)) return null;
|
||||
if (!data.get(field).isJsonPrimitive() || !data.getAsJsonPrimitive(field).isString())
|
||||
throw new IllegalArgumentException("Invalid persisted vote identity");
|
||||
String value = data.get(field).getAsString();
|
||||
return value.isEmpty() ? null : java.util.UUID.fromString(value);
|
||||
}
|
||||
|
||||
/** Enforces JSON lexical rules which older Gson non-lenient readers leave permissive. */
|
||||
private static final class StrictJsonInput extends java.io.FilterReader {
|
||||
private boolean firstCharacter = true;
|
||||
private boolean quoted;
|
||||
private boolean escaped;
|
||||
private int unicode;
|
||||
private final StringBuilder token = new StringBuilder();
|
||||
|
||||
StrictJsonInput(java.io.Reader input) { super(input); }
|
||||
|
||||
@Override
|
||||
public int read(char[] buffer, int offset, int length) throws IOException {
|
||||
int count = super.read(buffer, offset, length);
|
||||
if (count < 0) finish();
|
||||
else for (int i = offset; i < offset + count; i++) validate(buffer[i]);
|
||||
return count;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int read() throws IOException {
|
||||
int character = super.read();
|
||||
if (character < 0) finish(); else validate((char) character);
|
||||
return character;
|
||||
}
|
||||
|
||||
private void validate(char character) throws IOException {
|
||||
if (firstCharacter) {
|
||||
firstCharacter = false;
|
||||
// Legacy Gson readers consume a single BOM at the start of a UTF-8 file.
|
||||
if (character == '\uFEFF') return;
|
||||
}
|
||||
if (quoted) {
|
||||
if (unicode > 0) {
|
||||
if (Character.digit(character, 16) < 0 || character > 127) invalid();
|
||||
unicode--;
|
||||
} else if (escaped) {
|
||||
escaped = false;
|
||||
if (character == 'u') unicode = 4;
|
||||
else if ("\"\\/bfnrt".indexOf(character) < 0) invalid();
|
||||
} else if (character == '\\') escaped = true;
|
||||
else if (character == '"') quoted = false;
|
||||
else if (character < 32) invalid();
|
||||
} else if (character == '"') {
|
||||
finishToken(); quoted = true;
|
||||
} else if ("{}[],: \t\r\n".indexOf(character) >= 0) finishToken();
|
||||
else {
|
||||
if (token.length() >= 4096) invalid();
|
||||
token.append(character);
|
||||
}
|
||||
}
|
||||
|
||||
private void finishToken() throws IOException {
|
||||
if (token.length() == 0) return;
|
||||
String value = token.toString(); token.setLength(0);
|
||||
if (!value.equals("true") && !value.equals("false") && !value.equals("null")
|
||||
&& !value.matches("-?(0|[1-9][0-9]*)(\\.[0-9]+)?([eE][+-]?[0-9]+)?")) invalid();
|
||||
}
|
||||
|
||||
private void finish() throws IOException {
|
||||
if (quoted || escaped || unicode > 0) invalid();
|
||||
finishToken();
|
||||
}
|
||||
|
||||
private void invalid() throws IOException { throw new IOException("Invalid vote cache JSON syntax"); }
|
||||
}
|
||||
|
||||
private static JsonElement readValue(JsonReader reader, int depth) throws IOException {
|
||||
if (depth > 64) throw new IOException("Vote cache JSON nesting exceeds the supported depth");
|
||||
switch (reader.peek()) {
|
||||
case BEGIN_OBJECT:
|
||||
JsonObject object = new JsonObject();
|
||||
reader.beginObject();
|
||||
while (reader.hasNext()) {
|
||||
String name = reader.nextName();
|
||||
if (object.has(name)) throw new IOException("Duplicate field in vote cache JSON");
|
||||
object.add(name, readValue(reader, depth + 1));
|
||||
}
|
||||
reader.endObject();
|
||||
return object;
|
||||
case BEGIN_ARRAY:
|
||||
JsonArray array = new JsonArray();
|
||||
reader.beginArray();
|
||||
while (reader.hasNext()) array.add(readValue(reader, depth + 1));
|
||||
reader.endArray();
|
||||
return array;
|
||||
case STRING: return new JsonPrimitive(reader.nextString());
|
||||
case NUMBER: return new JsonPrimitive(new java.math.BigDecimal(reader.nextString()));
|
||||
case BOOLEAN: return new JsonPrimitive(reader.nextBoolean());
|
||||
case NULL: reader.nextNull(); return JsonNull.INSTANCE;
|
||||
default: throw new IOException("Incomplete vote cache JSON");
|
||||
}
|
||||
}
|
||||
|
||||
/** Commits all replay positions together and verifies their exact journal owners. */
|
||||
public static boolean saveAndVerifyCachedBatch(IVoteCache cache, String owner, boolean online,
|
||||
Collection<OfflineBungeeVote> expected) {
|
||||
return saveAndVerify(cache, () -> {
|
||||
for (OfflineBungeeVote vote : expected) {
|
||||
DataNode stored = online ? cache.getOnlineVotes(owner, vote.getOnlineVoteCacheJsonKey())
|
||||
: cache.getServerVotes(owner, vote.getServerVoteCacheJsonKey());
|
||||
if (!matches(stored, vote) || !sameField(stored, "Name", vote.getPlayerName())
|
||||
|| !sameField(stored, "Text", vote.getText()) || !stored.has("Real")
|
||||
|| stored.get("Real").asBoolean() != vote.isRealVote()
|
||||
|| !sameBoolean(stored, "WasOnline", vote.isWasOnline())
|
||||
|| !sameBoolean(stored, "WasOnlineKnown", vote.isWasOnlineKnown())
|
||||
|| !sameBoolean(stored, "DelayValidated", vote.isDelayValidated())
|
||||
|| !sameBoolean(stored, "DelayValidationKnown", vote.isQueueClassificationKnown())
|
||||
|| !sameBoolean(stored, "BroadcastForwarded", vote.isBroadcastForwarded())
|
||||
|| !sameBoolean(stored, "ProxyBroadcastHandled", vote.isProxyBroadcastHandled())
|
||||
|| !sameBoolean(stored, "RewardDelivered", vote.isRewardDelivered())
|
||||
|| !sameField(stored, "BroadcastTargets", vote.encodeBroadcastTargets())
|
||||
|| !sameField(stored, "BroadcastForwardedServers", vote.encodeBroadcastForwardedServers())
|
||||
|| !sameField(stored, "HttpDeliveryIds", vote.encodeHttpDeliveryIds())
|
||||
|| !sameField(stored, "HttpBroadcastDeliveryIds", vote.encodeHttpBroadcastDeliveryIds())
|
||||
|| !sameInteger(stored, "CachedBatchNumber", vote.getCachedBatchNumber())
|
||||
|| !sameInteger(stored, "CachedBatchSize", vote.getCachedBatchSize())
|
||||
|| !sameInteger(stored, "CachedBatchSourceRowId", vote.getCachedBatchSourceRowId()))
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
private static boolean sameField(DataNode data, String field, String expected) {
|
||||
return data.has(field) && Objects.equals(data.get(field).asString(), expected);
|
||||
}
|
||||
|
||||
private static boolean sameBoolean(DataNode data, String field, boolean expected) {
|
||||
return data.has(field) && data.get(field).isPrimitive()
|
||||
&& data.get(field).asPrimitive() instanceof Boolean && data.get(field).asBoolean() == expected;
|
||||
}
|
||||
|
||||
private static boolean sameInteger(DataNode data, String field, int expected) {
|
||||
if (!data.has(field) || !data.get(field).isPrimitive()
|
||||
|| !(data.get(field).asPrimitive() instanceof Number)) return false;
|
||||
try { return new java.math.BigDecimal(data.get(field).asString()).intValueExact() == expected; }
|
||||
catch (RuntimeException invalid) { return false; }
|
||||
}
|
||||
|
||||
private static boolean saveAndVerify(IVoteCache cache, BooleanSupplier verify) {
|
||||
return saveAndVerify(cache, () -> null, ignored -> verify.getAsBoolean());
|
||||
}
|
||||
|
||||
public static boolean saveAndVerifyServerVote(IVoteCache cache, String server, int index,
|
||||
OfflineBungeeVote expected) {
|
||||
return saveAndVerify(cache, () -> cache.getServerVotes(server, String.valueOf(index)), expected);
|
||||
@@ -37,23 +395,8 @@ public final class VoteCacheDurability {
|
||||
|
||||
/** Publishes a cache deletion and verifies the removed identity remains absent after reload. */
|
||||
public static boolean saveAndVerifyRemoval(IVoteCache cache, BooleanSupplier isAbsent) {
|
||||
if (cache == null || isAbsent == null || cache.getStoragePath() == null) return false;
|
||||
try {
|
||||
try {
|
||||
cache.saveDurably();
|
||||
} catch (DurableFiles.PublishedException published) {
|
||||
// The replacement is active; verification below determines the result.
|
||||
}
|
||||
cache.reload();
|
||||
return isAbsent.getAsBoolean();
|
||||
} catch (RuntimeException | java.io.IOException failure) {
|
||||
try {
|
||||
cache.reload();
|
||||
} catch (RuntimeException reloadFailure) {
|
||||
throw new ReloadFailedException(failure, reloadFailure);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if (isAbsent == null) return false;
|
||||
return saveAndVerify(cache, isAbsent);
|
||||
}
|
||||
|
||||
private static boolean saveAndVerify(IVoteCache cache, java.util.function.Supplier<DataNode> read,
|
||||
@@ -66,25 +409,28 @@ public final class VoteCacheDurability {
|
||||
if (cache == null || verify == null) return false;
|
||||
Path path = cache.getStoragePath();
|
||||
if (path == null) return false;
|
||||
try {
|
||||
try {
|
||||
cache.saveDurably();
|
||||
} catch (DurableFiles.PublishedException published) {
|
||||
// The new file is already active. Verify and keep its matching in-memory
|
||||
// state rather than rolling back and later overwriting the publication.
|
||||
}
|
||||
cache.reload();
|
||||
return verify.test(read.get());
|
||||
} catch (RuntimeException | java.io.IOException failure) {
|
||||
// addVote* mutates the JSON object before saveDurably runs. Discard that
|
||||
// uncommitted mutation so a later retry reuses the same slot instead of
|
||||
// eventually publishing both the failed attempt and its retry.
|
||||
synchronized (cache) {
|
||||
try {
|
||||
try {
|
||||
cache.saveDurably();
|
||||
} catch (DurableFiles.PublishedException published) {
|
||||
// The new file is already active. Verify and keep its matching in-memory
|
||||
// state rather than rolling back and later overwriting the publication.
|
||||
}
|
||||
cache.reload();
|
||||
} catch (RuntimeException reloadFailure) {
|
||||
throw new ReloadFailedException(failure, reloadFailure);
|
||||
return verify.test(read.get());
|
||||
} catch (RuntimeException | java.io.IOException failure) {
|
||||
// addVote* mutates the JSON object before saveDurably runs. Discard that
|
||||
// uncommitted mutation so a later retry reuses the same slot instead of
|
||||
// eventually publishing both the failed attempt and its retry.
|
||||
try {
|
||||
cache.reload();
|
||||
} catch (RuntimeException reloadFailure) {
|
||||
throw new ReloadFailedException(failure, reloadFailure);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
return false;
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -106,9 +452,9 @@ public final class VoteCacheDurability {
|
||||
if (!expected.getUuid().equals(data.get("UUID").asString())
|
||||
|| !expected.getService().equals(data.get("Service").asString())
|
||||
|| expected.getTime() != data.get("Time").asLong()) return false;
|
||||
if (expected.getVoteId() == null) return true;
|
||||
String voteId = data.has("VoteId") ? data.get("VoteId").asString()
|
||||
: data.has("VoteID") ? data.get("VoteID").asString() : "";
|
||||
return expected.getVoteId().toString().equals(voteId);
|
||||
return expected.getVoteId() == null ? voteId == null || voteId.isEmpty()
|
||||
: expected.getVoteId().toString().equals(voteId);
|
||||
}
|
||||
}
|
||||
+542
-155
@@ -1,6 +1,7 @@
|
||||
package com.bencodez.votingplugin.proxy.cache;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.sql.SQLException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
@@ -10,6 +11,7 @@ import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.Objects;
|
||||
@@ -64,6 +66,45 @@ public abstract class VoteCacheHandler {
|
||||
}
|
||||
|
||||
private boolean jsonStorageQuarantined;
|
||||
// Only a complete handler recovery may clear uncertain SQL/journal ownership.
|
||||
private boolean unresolvedSqlBatchIdentity;
|
||||
|
||||
/** Read-only health state; quarantined JSON mutations still require successful recovery. */
|
||||
public synchronized boolean isJsonStorageQuarantined() {
|
||||
return jsonStorageQuarantined;
|
||||
}
|
||||
|
||||
/** Returns the immutable plugin-message party snapshot using handler-before-store locking. */
|
||||
public synchronized PendingPluginMessageVotePartyRewards getPluginMessageVotePartyRewards() {
|
||||
IVoteCache storage = requireVotePartyJsonStorage();
|
||||
synchronized (storage) {
|
||||
PendingPluginMessageVotePartyRewards rewards = storage.getPluginMessageVotePartyRewards();
|
||||
if (rewards == null) throw new IllegalStateException("Missing plugin-message vote-party snapshot");
|
||||
return rewards;
|
||||
}
|
||||
}
|
||||
|
||||
public synchronized void setPluginMessageVotePartyRewards(PendingPluginMessageVotePartyRewards rewards) {
|
||||
if (rewards == null) throw new IllegalArgumentException("Missing plugin-message vote-party backlog");
|
||||
IVoteCache storage = requireVotePartyJsonStorage();
|
||||
synchronized (storage) { storage.setPluginMessageVotePartyRewards(rewards); }
|
||||
}
|
||||
|
||||
/**
|
||||
* Holds the handler and JSON-store monitors through party staging, durable save,
|
||||
* and any rollback. The callback must remain limited to this cache transaction.
|
||||
*/
|
||||
public synchronized void runVotePartyCacheTransaction(Runnable operation) {
|
||||
Objects.requireNonNull(operation, "Vote-party transaction is required");
|
||||
IVoteCache storage = requireVotePartyJsonStorage();
|
||||
synchronized (storage) { operation.run(); }
|
||||
}
|
||||
|
||||
private IVoteCache requireVotePartyJsonStorage() {
|
||||
if (jsonStorage == null || jsonStorageQuarantined)
|
||||
throw new IllegalStateException("Vote-party JSON storage is unavailable or quarantined");
|
||||
return jsonStorage;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a server has cached votes.
|
||||
@@ -163,6 +204,107 @@ public abstract class VoteCacheHandler {
|
||||
return stored;
|
||||
}
|
||||
|
||||
/** Journals replay positions before any transport can consume this cache snapshot. */
|
||||
public synchronized boolean prepareCachedVoteBatch(String owner, boolean online,
|
||||
Collection<OfflineBungeeVote> eligible, int size) {
|
||||
if (owner == null || eligible == null || size < 0)
|
||||
return false;
|
||||
Map<OfflineBungeeVote, OfflineBungeeVote> staged = new LinkedHashMap<>();
|
||||
Collection<OfflineBungeeVote> owned = online ? getOnlineVotes(owner) : getVotes(owner);
|
||||
int unassigned = 0;
|
||||
boolean hasAssigned = false;
|
||||
for (OfflineBungeeVote vote : eligible) {
|
||||
if (vote == null || !owned.contains(vote) || !vote.isCachedVoteBatchValid()) return false;
|
||||
if (vote.hasCachedVoteBatch()) hasAssigned = true;
|
||||
else unassigned++;
|
||||
}
|
||||
// A surviving batch keeps its original positions; newly cached votes form a complete new batch.
|
||||
int assignedSize = hasAssigned ? unassigned : size;
|
||||
int next = 0;
|
||||
for (OfflineBungeeVote vote : eligible) {
|
||||
if (vote.hasCachedVoteBatch() && vote.isCachedBatchDurable() && vote.getVoteId() != null) continue;
|
||||
OfflineBungeeVote copy = copyForBatch(vote);
|
||||
if (!copy.hasCachedVoteBatch()) copy.setCachedVoteBatch(++next, assignedSize);
|
||||
if (!copy.isCachedVoteBatchValid() || !copy.hasCachedVoteBatch()) return false;
|
||||
int row = online ? vote.getOnlineVoteCacheRowId() : vote.getServerVoteCacheRowId();
|
||||
if (row > 0) copy.setCachedBatchSourceRowId(row);
|
||||
staged.put(vote, copy);
|
||||
}
|
||||
if (staged.isEmpty()) return true;
|
||||
if (jsonStorage == null || jsonStorageQuarantined || unresolvedSqlBatchIdentity) return false;
|
||||
synchronized (jsonStorage) {
|
||||
if (!ensureEmergencyJournalMarker()) return false;
|
||||
try {
|
||||
for (Entry<OfflineBungeeVote, OfflineBungeeVote> entry : staged.entrySet()) {
|
||||
OfflineBungeeVote copy = entry.getValue();
|
||||
Collection<String> keys = online ? jsonStorage.getOnlineVotes(owner) : jsonStorage.getServerVotes(owner);
|
||||
String key = online ? entry.getKey().getOnlineVoteCacheJsonKey()
|
||||
: entry.getKey().getServerVoteCacheJsonKey();
|
||||
if (key != null) {
|
||||
DataNode stored = online ? jsonStorage.getOnlineVotes(owner, key) : jsonStorage.getServerVotes(owner, key);
|
||||
if (stored == null || !stored.isObject() || !matchesStoredVote(stored, entry.getKey())
|
||||
&& !(entry.getKey().getVoteId() == null && sameStoredLegacyPayload(stored, entry.getKey())))
|
||||
throw new IllegalStateException("Cached replay no longer owns its JSON entry");
|
||||
} else if (keys != null) {
|
||||
for (String candidateKey : keys) {
|
||||
DataNode data = online ? jsonStorage.getOnlineVotes(owner, candidateKey)
|
||||
: jsonStorage.getServerVotes(owner, candidateKey);
|
||||
OfflineBungeeVote stored = decodeJsonVote(data);
|
||||
if (stored != null && matchesSqlBatchTwin(stored, entry.getKey(), copy.getCachedBatchSourceRowId())) {
|
||||
key = candidateKey;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (copy.getVoteId() == null) {
|
||||
OfflineBungeeVote prior = key == null ? null : decodeJsonVote(online
|
||||
? jsonStorage.getOnlineVotes(owner, key) : jsonStorage.getServerVotes(owner, key));
|
||||
copy.assignCachedVoteId(prior != null && prior.getVoteId() != null ? prior.getVoteId() : UUID.randomUUID());
|
||||
}
|
||||
int index = key == null ? nextCacheIndex(keys) : Integer.parseInt(key);
|
||||
if (online) {
|
||||
copy.setOnlineVoteCacheJsonKey(String.valueOf(index));
|
||||
jsonStorage.addVoteOnline(owner, index, copy);
|
||||
} else {
|
||||
copy.setServerVoteCacheJsonKey(String.valueOf(index));
|
||||
jsonStorage.addVote(owner, index, copy);
|
||||
}
|
||||
}
|
||||
if (!VoteCacheDurability.saveAndVerifyCachedBatch(jsonStorage, owner, online, staged.values())) return false;
|
||||
} catch (VoteCacheDurability.ReloadFailedException failure) {
|
||||
jsonStorageQuarantined = true;
|
||||
debug1(failure);
|
||||
return false;
|
||||
} catch (RuntimeException failure) {
|
||||
debug1(failure);
|
||||
try { jsonStorage.reload(); }
|
||||
catch (RuntimeException reloadFailure) { jsonStorageQuarantined = true; debug1(reloadFailure); }
|
||||
return false;
|
||||
}
|
||||
for (Entry<OfflineBungeeVote, OfflineBungeeVote> entry : staged.entrySet()) {
|
||||
OfflineBungeeVote copy = entry.getValue();
|
||||
copy.setCachedBatchDurable(true);
|
||||
entry.getKey().assignCachedVoteId(copy.getVoteId());
|
||||
entry.getKey().copyCachedVoteBatch(copy);
|
||||
if (online) entry.getKey().setOnlineVoteCacheJsonKey(copy.getOnlineVoteCacheJsonKey());
|
||||
else entry.getKey().setServerVoteCacheJsonKey(copy.getServerVoteCacheJsonKey());
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private OfflineBungeeVote copyForBatch(OfflineBungeeVote vote) {
|
||||
OfflineBungeeVote copy = new OfflineBungeeVote(vote.getVoteId(), vote.getPlayerName(), vote.getUuid(),
|
||||
vote.getService(), vote.getTime(), vote.isRealVote(), vote.getText(), vote.isBroadcastForwarded(),
|
||||
vote.isProxyBroadcastHandled(), vote.getBroadcastTargets(), vote.getBroadcastForwardedServers(),
|
||||
vote.isRewardDelivered(), vote.getHttpDeliveryIds(), vote.getHttpBroadcastDeliveryIds());
|
||||
if (vote.isWasOnlineKnown()) copy.setWasOnline(vote.isWasOnline());
|
||||
if (vote.isDelayValidationKnown()) copy.setDelayValidated(vote.isDelayValidated());
|
||||
else if (!vote.isQueueClassificationKnown()) copy.clearDelayValidation();
|
||||
copy.copyCachedVoteBatch(vote);
|
||||
return copy;
|
||||
}
|
||||
|
||||
/** Retains a failed server-cache insert for a later durability retry. */
|
||||
public synchronized boolean retainServerVoteForPersistenceRetry(String server, OfflineBungeeVote vote) {
|
||||
if (server == null || vote == null) return false;
|
||||
@@ -184,6 +326,8 @@ public abstract class VoteCacheHandler {
|
||||
*/
|
||||
public synchronized boolean updateServerVote(String server, OfflineBungeeVote vote) {
|
||||
if (useMySQL) {
|
||||
if (vote.getServerVoteCacheRowId() <= 0 && vote.getCachedBatchSourceRowId() > 0)
|
||||
return updateServerVoteJson(server, vote);
|
||||
if (voteCacheTable.updateProxyBroadcastState(vote, server)) {
|
||||
// SQL rows can have an emergency JSON twin after a mixed-version or
|
||||
// recovery path. Keep that exact twin current before publishing again.
|
||||
@@ -194,31 +338,7 @@ public abstract class VoteCacheHandler {
|
||||
if (vote.getServerVoteCacheRowId() > 0) return false;
|
||||
return updateServerVoteJson(server, vote);
|
||||
}
|
||||
if (jsonStorage == null || jsonStorageQuarantined) return false;
|
||||
|
||||
Collection<String> keys = jsonStorage.getServerVotes(server);
|
||||
if (keys == null) {
|
||||
return false;
|
||||
}
|
||||
for (String key : keys) {
|
||||
DataNode data = jsonStorage.getServerVotes(server, key);
|
||||
if (data == null || !data.isObject() || !data.has("UUID") || !data.has("Service")
|
||||
|| !data.has("Time")) {
|
||||
continue;
|
||||
}
|
||||
if (matchesStoredServerVote(key, data, vote)) {
|
||||
try {
|
||||
int index = Integer.parseInt(key);
|
||||
vote.setServerVoteCacheJsonKey(key);
|
||||
jsonStorage.addVote(server, index, vote);
|
||||
return verifyJsonServerVote(server, index, vote);
|
||||
} catch (RuntimeException e) {
|
||||
debug1(e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
return updateServerVoteJson(server, vote);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -386,6 +506,8 @@ public abstract class VoteCacheHandler {
|
||||
*/
|
||||
public synchronized boolean updateOnlineVote(String uuid, OfflineBungeeVote vote) {
|
||||
if (useMySQL) {
|
||||
if (vote.getOnlineVoteCacheRowId() <= 0 && vote.getCachedBatchSourceRowId() > 0)
|
||||
return updateOnlineVoteJson(uuid, vote);
|
||||
if (onlineVoteCacheTable.updateProxyBroadcastState(vote)) {
|
||||
return !hasJsonOnlineVote(vote, uuid) || updateOnlineVoteJson(uuid, vote);
|
||||
}
|
||||
@@ -394,31 +516,7 @@ public abstract class VoteCacheHandler {
|
||||
if (vote.getOnlineVoteCacheRowId() > 0) return false;
|
||||
return updateOnlineVoteJson(uuid, vote);
|
||||
}
|
||||
if (jsonStorage == null || jsonStorageQuarantined) return false;
|
||||
|
||||
Collection<String> keys = jsonStorage.getOnlineVotes(uuid);
|
||||
if (keys == null) {
|
||||
return false;
|
||||
}
|
||||
for (String key : keys) {
|
||||
DataNode data = jsonStorage.getOnlineVotes(uuid, key);
|
||||
if (data == null || !data.isObject() || !data.has("UUID") || !data.has("Service")
|
||||
|| !data.has("Time")) {
|
||||
continue;
|
||||
}
|
||||
if (matchesStoredOnlineVote(key, data, vote)) {
|
||||
try {
|
||||
int index = Integer.parseInt(key);
|
||||
vote.setOnlineVoteCacheJsonKey(key);
|
||||
jsonStorage.addVoteOnline(uuid, index, vote);
|
||||
return verifyJsonOnlineVote(uuid, index, vote);
|
||||
} catch (RuntimeException e) {
|
||||
debug1(e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
return updateOnlineVoteJson(uuid, vote);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -473,7 +571,15 @@ public abstract class VoteCacheHandler {
|
||||
if (votes == null || votes.isEmpty()) {
|
||||
return true;
|
||||
}
|
||||
boolean mysqlRemoved = !useMySQL || onlineVoteCacheTable.tryRemoveVote(removedVote);
|
||||
boolean mysqlRemoved = !useMySQL
|
||||
|| removedVote.getOnlineVoteCacheRowId() <= 0 && removedVote.getCachedBatchSourceRowId() > 0
|
||||
|| onlineVoteCacheTable.tryRemoveVote(removedVote);
|
||||
if (!mysqlRemoved) return false;
|
||||
// SQL deletion is committed even if paired JSON cleanup later fails.
|
||||
// Preserve the recovery bytes, but do not offer that removed owner again.
|
||||
if (useMySQL && removedVote.getOnlineVoteCacheRowId() > 0) {
|
||||
retireOnlineReplayOwner(uuid, removedVote);
|
||||
}
|
||||
boolean jsonRemoved = jsonStorage == null;
|
||||
if (jsonStorage != null && !jsonStorageQuarantined
|
||||
&& (!useMySQL || removedVote.getOnlineVoteCacheRowId() <= 0
|
||||
@@ -486,12 +592,23 @@ public abstract class VoteCacheHandler {
|
||||
}
|
||||
boolean removedDurably = mysqlRemoved && jsonRemoved;
|
||||
if (!removedDurably) return false;
|
||||
votes.removeIf(vote -> sameVoteIdentity(vote, removedVote));
|
||||
if (votes.isEmpty()) cachedOnlineVotes.remove(uuid);
|
||||
retireOnlineReplayOwner(uuid, removedVote);
|
||||
return true;
|
||||
}
|
||||
|
||||
private void retireOnlineReplayOwner(String uuid, OfflineBungeeVote removedVote) {
|
||||
ArrayList<OfflineBungeeVote> votes = cachedOnlineVotes.get(uuid);
|
||||
if (votes == null) return;
|
||||
votes.removeIf(vote -> sameVoteIdentity(vote, removedVote));
|
||||
if (votes.isEmpty()) cachedOnlineVotes.remove(uuid);
|
||||
}
|
||||
|
||||
protected boolean removeJsonOnlineVoteDurably(String uuid, OfflineBungeeVote removedVote) {
|
||||
if (jsonStorage == null || jsonStorageQuarantined) return false;
|
||||
synchronized (jsonStorage) { return removeJsonOnlineVoteDurablyLocked(uuid, removedVote); }
|
||||
}
|
||||
|
||||
private boolean removeJsonOnlineVoteDurablyLocked(String uuid, OfflineBungeeVote removedVote) {
|
||||
jsonStorage.removeOnlineVote(removedVote);
|
||||
try {
|
||||
return VoteCacheDurability.saveAndVerifyRemoval(jsonStorage,
|
||||
@@ -605,23 +722,41 @@ public abstract class VoteCacheHandler {
|
||||
}
|
||||
|
||||
private OfflineBungeeVote findServerVoteSqlTwin(String server, OfflineBungeeVote emergency) {
|
||||
if (emergency.getVoteId() == null) return null;
|
||||
for (OfflineBungeeVote candidate : getVotes(server)) {
|
||||
if (candidate.getServerVoteCacheRowId() > 0 && candidate.getServerVoteCacheJsonKey() == null
|
||||
&& emergency.getVoteId().equals(candidate.getVoteId())) return candidate;
|
||||
&& matchesSqlBatchTwin(emergency, candidate, candidate.getServerVoteCacheRowId())) return candidate;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private OfflineBungeeVote findOnlineVoteSqlTwin(String uuid, OfflineBungeeVote emergency) {
|
||||
if (emergency.getVoteId() == null) return null;
|
||||
for (OfflineBungeeVote candidate : getOnlineVotes(uuid)) {
|
||||
if (candidate.getOnlineVoteCacheRowId() > 0 && candidate.getOnlineVoteCacheJsonKey() == null
|
||||
&& emergency.getVoteId().equals(candidate.getVoteId())) return candidate;
|
||||
&& matchesSqlBatchTwin(emergency, candidate, candidate.getOnlineVoteCacheRowId())) return candidate;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private boolean matchesSqlBatchTwin(OfflineBungeeVote emergency, OfflineBungeeVote sql, int rowId) {
|
||||
if (emergency.getVoteId() != null && sql.getVoteId() != null)
|
||||
return emergency.getVoteId().equals(sql.getVoteId());
|
||||
return rowId > 0 && emergency.getCachedBatchSourceRowId() == rowId
|
||||
&& Objects.equals(emergency.getPlayerName(), sql.getPlayerName())
|
||||
&& Objects.equals(emergency.getUuid(), sql.getUuid())
|
||||
&& Objects.equals(emergency.getService(), sql.getService()) && emergency.getTime() == sql.getTime()
|
||||
&& emergency.isRealVote() == sql.isRealVote() && Objects.equals(emergency.getText(), sql.getText());
|
||||
}
|
||||
|
||||
private boolean sameStoredLegacyPayload(DataNode data, OfflineBungeeVote vote) {
|
||||
return data.has("UUID") && data.has("Service") && data.has("Time")
|
||||
&& Objects.equals(vote.getUuid(), data.get("UUID").asString())
|
||||
&& Objects.equals(vote.getService(), data.get("Service").asString())
|
||||
&& vote.getTime() == data.get("Time").asLong()
|
||||
&& Objects.equals(vote.getPlayerName(), data.has("Name") ? data.get("Name").asString() : "")
|
||||
&& Objects.equals(vote.getText(), data.has("Text") ? data.get("Text").asString() : "")
|
||||
&& vote.isRealVote() == (data.has("Real") && data.get("Real").asBoolean());
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads a vote identifier using the current key and the legacy key.
|
||||
*
|
||||
@@ -662,10 +797,12 @@ public abstract class VoteCacheHandler {
|
||||
|
||||
private boolean matchesStoredVote(DataNode data, OfflineBungeeVote vote) {
|
||||
String storedVoteId = readVoteId(data);
|
||||
if (vote.getVoteId() != null && storedVoteId != null && !storedVoteId.isEmpty()) {
|
||||
return vote.getVoteId().toString().equals(storedVoteId);
|
||||
}
|
||||
return vote.getUuid().equals(data.get("UUID").asString())
|
||||
if (vote.getVoteId() != null) return vote.getVoteId().toString().equals(storedVoteId);
|
||||
return (storedVoteId == null || storedVoteId.isEmpty())
|
||||
&& Objects.equals(vote.getPlayerName(), data.has("Name") ? data.get("Name").asString() : "")
|
||||
&& Objects.equals(vote.getText(), data.has("Text") ? data.get("Text").asString() : "")
|
||||
&& vote.isRealVote() == (data.has("Real") && data.get("Real").asBoolean())
|
||||
&& vote.getUuid().equals(data.get("UUID").asString())
|
||||
&& vote.getService().equals(data.get("Service").asString())
|
||||
&& vote.getTime() == data.get("Time").asLong();
|
||||
}
|
||||
@@ -694,6 +831,11 @@ public abstract class VoteCacheHandler {
|
||||
|
||||
/** Persists a server vote in the JSON emergency journal. */
|
||||
private boolean persistServerVoteToJson(String server, OfflineBungeeVote vote) {
|
||||
if (jsonStorage == null || jsonStorageQuarantined) return false;
|
||||
synchronized (jsonStorage) { return persistServerVoteToJsonLocked(server, vote); }
|
||||
}
|
||||
|
||||
private boolean persistServerVoteToJsonLocked(String server, OfflineBungeeVote vote) {
|
||||
if (jsonStorage == null || jsonStorageQuarantined) {
|
||||
return false;
|
||||
}
|
||||
@@ -701,7 +843,7 @@ public abstract class VoteCacheHandler {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
Collection<String> keys = jsonStorage.getServerVotes(server);
|
||||
Collection<String> keys = reservedJournalKeys(server, false);
|
||||
int index = nextCacheIndex(keys);
|
||||
vote.setServerVoteCacheJsonKey(String.valueOf(index));
|
||||
jsonStorage.addVote(server, index, vote);
|
||||
@@ -714,6 +856,11 @@ public abstract class VoteCacheHandler {
|
||||
|
||||
/** Persists an online vote in the JSON emergency journal. */
|
||||
private boolean persistOnlineVoteToJson(String uuid, OfflineBungeeVote vote) {
|
||||
if (jsonStorage == null || jsonStorageQuarantined) return false;
|
||||
synchronized (jsonStorage) { return persistOnlineVoteToJsonLocked(uuid, vote); }
|
||||
}
|
||||
|
||||
private boolean persistOnlineVoteToJsonLocked(String uuid, OfflineBungeeVote vote) {
|
||||
if (jsonStorage == null || jsonStorageQuarantined) {
|
||||
return false;
|
||||
}
|
||||
@@ -721,7 +868,7 @@ public abstract class VoteCacheHandler {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
Collection<String> keys = jsonStorage.getOnlineVotes(uuid);
|
||||
Collection<String> keys = reservedJournalKeys(uuid, true);
|
||||
int index = nextCacheIndex(keys);
|
||||
vote.setOnlineVoteCacheJsonKey(String.valueOf(index));
|
||||
jsonStorage.addVoteOnline(uuid, index, vote);
|
||||
@@ -732,6 +879,28 @@ public abstract class VoteCacheHandler {
|
||||
}
|
||||
}
|
||||
|
||||
private Collection<String> reservedJournalKeys(String owner, boolean online) {
|
||||
Collection<String> loaded = online ? jsonStorage.getOnlineVotes(owner) : jsonStorage.getServerVotes(owner);
|
||||
Set<String> keys = new LinkedHashSet<>();
|
||||
if (loaded != null) keys.addAll(loaded);
|
||||
Path path = jsonStorage.getStoragePath();
|
||||
if (path == null) return keys;
|
||||
try {
|
||||
var document = VoteCacheDurability.readJournal(path);
|
||||
String lane = online ? "OnlineCache" : "VoteCache";
|
||||
if (!document.has(lane)) return keys;
|
||||
var owners = document.get(lane);
|
||||
if (!owners.isJsonObject()) throw new IllegalStateException("Unresolved cache lane structure");
|
||||
if (!owners.getAsJsonObject().has(owner)) return keys;
|
||||
var rows = owners.getAsJsonObject().get(owner);
|
||||
if (!rows.isJsonObject()) throw new IllegalStateException("Unresolved cache owner structure");
|
||||
for (var entry : rows.getAsJsonObject().entrySet()) keys.add(entry.getKey());
|
||||
return keys;
|
||||
} catch (IOException failure) {
|
||||
throw new IllegalStateException("Unable to reserve persisted vote journal keys", failure);
|
||||
}
|
||||
}
|
||||
|
||||
protected boolean verifyJsonServerVote(String server, int index, OfflineBungeeVote vote) {
|
||||
try {
|
||||
return VoteCacheDurability.saveAndVerifyServerVote(jsonStorage, server, index, vote);
|
||||
@@ -771,6 +940,11 @@ public abstract class VoteCacheHandler {
|
||||
}
|
||||
|
||||
private boolean updateServerVoteJson(String server, OfflineBungeeVote vote) {
|
||||
if (jsonStorage == null || jsonStorageQuarantined) return false;
|
||||
synchronized (jsonStorage) { return updateServerVoteJsonLocked(server, vote); }
|
||||
}
|
||||
|
||||
private boolean updateServerVoteJsonLocked(String server, OfflineBungeeVote vote) {
|
||||
if (jsonStorage == null || jsonStorageQuarantined) {
|
||||
return false;
|
||||
}
|
||||
@@ -796,6 +970,11 @@ public abstract class VoteCacheHandler {
|
||||
}
|
||||
|
||||
private boolean updateOnlineVoteJson(String uuid, OfflineBungeeVote vote) {
|
||||
if (jsonStorage == null || jsonStorageQuarantined) return false;
|
||||
synchronized (jsonStorage) { return updateOnlineVoteJsonLocked(uuid, vote); }
|
||||
}
|
||||
|
||||
private boolean updateOnlineVoteJsonLocked(String uuid, OfflineBungeeVote vote) {
|
||||
if (jsonStorage == null || jsonStorageQuarantined) {
|
||||
return false;
|
||||
}
|
||||
@@ -940,6 +1119,11 @@ public abstract class VoteCacheHandler {
|
||||
|
||||
/** Persists a timed vote in the JSON emergency journal. */
|
||||
private boolean persistTimeVoteToJson(VoteTimeQueue vote) {
|
||||
if (jsonStorage == null || jsonStorageQuarantined) return false;
|
||||
synchronized (jsonStorage) { return persistTimeVoteToJsonLocked(vote); }
|
||||
}
|
||||
|
||||
private boolean persistTimeVoteToJsonLocked(VoteTimeQueue vote) {
|
||||
if (jsonStorage == null || jsonStorageQuarantined) return false;
|
||||
if (!ensureEmergencyJournalMarker()) {
|
||||
return false;
|
||||
@@ -1266,81 +1450,116 @@ public abstract class VoteCacheHandler {
|
||||
/**
|
||||
* Loads vote cache from storage.
|
||||
*/
|
||||
public void load() {
|
||||
public synchronized void load() {
|
||||
if (useMySQL) unresolvedSqlBatchIdentity = true;
|
||||
if (jsonStorage != null) {
|
||||
try { jsonStorage.reload(); jsonStorageQuarantined = false; }
|
||||
catch (RuntimeException failure) { jsonStorageQuarantined = true; throw failure; }
|
||||
}
|
||||
if (useMySQL) {
|
||||
// Load votes from MySQL
|
||||
voteCacheTable.getAllVotes().forEach(voteRow -> {
|
||||
OfflineBungeeVote vote = new OfflineBungeeVote(voteRow.getVoteId(), voteRow.getPlayerName(),
|
||||
voteRow.getUuid(), voteRow.getService(), voteRow.getTime(), voteRow.isRealVote(),
|
||||
voteRow.getText(), voteRow.isBroadcastForwarded(), voteRow.isProxyBroadcastHandled(),
|
||||
VoteTimeQueue.decodeBroadcastForwardedServers(voteRow.getBroadcastTargets()),
|
||||
VoteTimeQueue.decodeBroadcastForwardedServers(voteRow.getBroadcastForwardedServers()),
|
||||
voteRow.isRewardDelivered(), OfflineBungeeVote.decodeHttpDeliveryIds(voteRow.getHttpDeliveryIds()),
|
||||
OfflineBungeeVote.decodeHttpBroadcastDeliveryIds(voteRow.getHttpBroadcastDeliveryIds()));
|
||||
if (voteRow.isWasOnlineKnown()) vote.setWasOnline(voteRow.isWasOnline());
|
||||
if (voteRow.getDelayValidation() >= 0) vote.setDelayValidated(voteRow.getDelayValidation() == 1);
|
||||
else vote.clearDelayValidation();
|
||||
vote.setServerVoteCacheRowId(voteRow.getId());
|
||||
String server = voteRow.getServer();
|
||||
cachedVotes.putIfAbsent(server, new ArrayList<>());
|
||||
cachedVotes.get(server).add(vote);
|
||||
});
|
||||
final List<ProxyVoteCacheTable.VoteRow> serverRows;
|
||||
final List<ProxyOnlineVoteCacheTable.VoteRow> onlineRows;
|
||||
final List<ProxyTimedVoteCacheTable.TimedVoteRow> timedRows;
|
||||
try {
|
||||
serverRows = voteCacheTable.getAllVotesChecked();
|
||||
onlineRows = onlineVoteCacheTable.getAllVotesChecked();
|
||||
timedRows = timedVoteCacheTable.getAllVotesChecked();
|
||||
} catch (SQLException failure) {
|
||||
throw new IllegalStateException("Unable to read proxy vote cache snapshot", failure);
|
||||
}
|
||||
ConcurrentHashMap<String, ArrayList<OfflineBungeeVote>> previousVotes = cachedVotes;
|
||||
ConcurrentHashMap<String, ArrayList<OfflineBungeeVote>> previousOnlineVotes = cachedOnlineVotes;
|
||||
Queue<VoteTimeQueue> previousTimedVotes = timeChangeQueue;
|
||||
cachedVotes = new ConcurrentHashMap<>();
|
||||
cachedOnlineVotes = new ConcurrentHashMap<>();
|
||||
timeChangeQueue = new ConcurrentLinkedQueue<>();
|
||||
try {
|
||||
Set<Integer> serverSourceRows = new LinkedHashSet<>();
|
||||
Set<Integer> onlineSourceRows = new LinkedHashSet<>();
|
||||
for (ProxyVoteCacheTable.VoteRow row : serverRows) serverSourceRows.add(row.getId());
|
||||
for (ProxyOnlineVoteCacheTable.VoteRow row : onlineRows) onlineSourceRows.add(row.getId());
|
||||
// Load votes from MySQL
|
||||
serverRows.forEach(voteRow -> {
|
||||
OfflineBungeeVote vote = new OfflineBungeeVote(voteRow.getVoteId(), voteRow.getPlayerName(),
|
||||
voteRow.getUuid(), voteRow.getService(), voteRow.getTime(), voteRow.isRealVote(),
|
||||
voteRow.getText(), voteRow.isBroadcastForwarded(), voteRow.isProxyBroadcastHandled(),
|
||||
VoteTimeQueue.decodeBroadcastForwardedServers(voteRow.getBroadcastTargets()),
|
||||
VoteTimeQueue.decodeBroadcastForwardedServers(voteRow.getBroadcastForwardedServers()),
|
||||
voteRow.isRewardDelivered(), OfflineBungeeVote.decodeHttpDeliveryIds(voteRow.getHttpDeliveryIds()),
|
||||
OfflineBungeeVote.decodeHttpBroadcastDeliveryIds(voteRow.getHttpBroadcastDeliveryIds()));
|
||||
if (voteRow.isWasOnlineKnown()) vote.setWasOnline(voteRow.isWasOnline());
|
||||
if (voteRow.getDelayValidation() >= 0) vote.setDelayValidated(voteRow.getDelayValidation() == 1);
|
||||
else vote.clearDelayValidation();
|
||||
vote.setServerVoteCacheRowId(voteRow.getId());
|
||||
String server = voteRow.getServer();
|
||||
cachedVotes.putIfAbsent(server, new ArrayList<>());
|
||||
cachedVotes.get(server).add(vote);
|
||||
});
|
||||
|
||||
// Load online votes from MySQL
|
||||
onlineVoteCacheTable.getAllVotes().forEach(voteRow -> {
|
||||
OfflineBungeeVote vote = new OfflineBungeeVote(voteRow.getVoteId(), voteRow.getPlayerName(),
|
||||
voteRow.getUuid(), voteRow.getService(), voteRow.getTime(), voteRow.isRealVote(),
|
||||
voteRow.getText(), voteRow.isBroadcastForwarded(), voteRow.isProxyBroadcastHandled(),
|
||||
VoteTimeQueue.decodeBroadcastForwardedServers(voteRow.getBroadcastTargets()),
|
||||
VoteTimeQueue.decodeBroadcastForwardedServers(voteRow.getBroadcastForwardedServers()),
|
||||
voteRow.isRewardDelivered(), OfflineBungeeVote.decodeHttpDeliveryIds(voteRow.getHttpDeliveryIds()),
|
||||
OfflineBungeeVote.decodeHttpBroadcastDeliveryIds(voteRow.getHttpBroadcastDeliveryIds()));
|
||||
if (voteRow.isWasOnlineKnown()) vote.setWasOnline(voteRow.isWasOnline());
|
||||
if (voteRow.getDelayValidation() >= 0) vote.setDelayValidated(voteRow.getDelayValidation() == 1);
|
||||
else vote.clearDelayValidation();
|
||||
vote.setOnlineVoteCacheRowId(voteRow.getId());
|
||||
String player = vote.getUuid();
|
||||
cachedOnlineVotes.putIfAbsent(player, new ArrayList<>());
|
||||
cachedOnlineVotes.get(player).add(vote);
|
||||
});
|
||||
// Load online votes from MySQL
|
||||
onlineRows.forEach(voteRow -> {
|
||||
OfflineBungeeVote vote = new OfflineBungeeVote(voteRow.getVoteId(), voteRow.getPlayerName(),
|
||||
voteRow.getUuid(), voteRow.getService(), voteRow.getTime(), voteRow.isRealVote(),
|
||||
voteRow.getText(), voteRow.isBroadcastForwarded(), voteRow.isProxyBroadcastHandled(),
|
||||
VoteTimeQueue.decodeBroadcastForwardedServers(voteRow.getBroadcastTargets()),
|
||||
VoteTimeQueue.decodeBroadcastForwardedServers(voteRow.getBroadcastForwardedServers()),
|
||||
voteRow.isRewardDelivered(), OfflineBungeeVote.decodeHttpDeliveryIds(voteRow.getHttpDeliveryIds()),
|
||||
OfflineBungeeVote.decodeHttpBroadcastDeliveryIds(voteRow.getHttpBroadcastDeliveryIds()));
|
||||
if (voteRow.isWasOnlineKnown()) vote.setWasOnline(voteRow.isWasOnline());
|
||||
if (voteRow.getDelayValidation() >= 0) vote.setDelayValidated(voteRow.getDelayValidation() == 1);
|
||||
else vote.clearDelayValidation();
|
||||
vote.setOnlineVoteCacheRowId(voteRow.getId());
|
||||
String player = vote.getUuid();
|
||||
cachedOnlineVotes.putIfAbsent(player, new ArrayList<>());
|
||||
cachedOnlineVotes.get(player).add(vote);
|
||||
});
|
||||
|
||||
// Load timed votes from MySQL
|
||||
ArrayList<VoteTimeQueue> timedVotes = new ArrayList<>();
|
||||
timedVoteCacheTable.getAllVotes().forEach(timedVoteRow -> {
|
||||
VoteTimeQueue voteTimeQueue = new VoteTimeQueue(timedVoteRow.getVoteId(), timedVoteRow.getPlayerName(),
|
||||
timedVoteRow.getService(), timedVoteRow.getTime(), timedVoteRow.isProxyBroadcastHandled(),
|
||||
VoteTimeQueue.decodeBroadcastForwardedServers(timedVoteRow.getBroadcastTargets()),
|
||||
VoteTimeQueue.decodeBroadcastForwardedServers(timedVoteRow.getBroadcastForwardedServers()),
|
||||
timedVoteRow.getTotals(), timedVoteRow.isProcessed(),
|
||||
timedVoteRow.isMultiProxyForwardingHandled(), timedVoteRow.getUuid(),
|
||||
VoteTimeQueue.decodeHttpBroadcastDeliveryIds(timedVoteRow.getHttpBroadcastDeliveryIds()));
|
||||
voteTimeQueue.setMultiProxyForwardingRequired(timedVoteRow.isMultiProxyForwardingRequired());
|
||||
voteTimeQueue.setMultiProxyCapabilityDiscoveryPending(
|
||||
timedVoteRow.isMultiProxyCapabilityDiscoveryPending());
|
||||
voteTimeQueue.setVotePartyApplied(timedVoteRow.isVotePartyApplied());
|
||||
voteTimeQueue.setTotalsApplied(timedVoteRow.isTotalsApplied());
|
||||
voteTimeQueue.setRealVote(timedVoteRow.isRealVote());
|
||||
if (timedVoteRow.isWasOnlineKnown()) voteTimeQueue.setWasOnline(timedVoteRow.isWasOnline());
|
||||
if (timedVoteRow.getDelayValidation() >= 0) {
|
||||
voteTimeQueue.setDelayValidated(timedVoteRow.getDelayValidation() == 1);
|
||||
} else voteTimeQueue.clearDelayValidation();
|
||||
voteTimeQueue.setMultiProxyOrigin(timedVoteRow.getMultiProxyOrigin() == null ? ""
|
||||
: timedVoteRow.getMultiProxyOrigin());
|
||||
voteTimeQueue.setMultiProxyCompletionPending(timedVoteRow.isMultiProxyCompletionPending());
|
||||
voteTimeQueue.setMultiProxyRecipients(
|
||||
VoteTimeQueue.decodeBroadcastForwardedServers(timedVoteRow.getMultiProxyRecipients()));
|
||||
voteTimeQueue.setMultiProxyAcknowledgedServers(
|
||||
VoteTimeQueue.decodeBroadcastForwardedServers(timedVoteRow.getMultiProxyAcknowledgedServers()));
|
||||
voteTimeQueue.setMultiProxyLegacyPendingRecipients(
|
||||
VoteTimeQueue.decodeBroadcastForwardedServers(
|
||||
timedVoteRow.getMultiProxyLegacyPendingRecipients()));
|
||||
voteTimeQueue.setTimedVoteCacheRowId(timedVoteRow.getId());
|
||||
timedVotes.add(voteTimeQueue);
|
||||
});
|
||||
timeChangeQueue.addAll(timedVotes);
|
||||
loadJsonEmergencyVotes();
|
||||
// Load timed votes from MySQL
|
||||
ArrayList<VoteTimeQueue> timedVotes = new ArrayList<>();
|
||||
timedRows.forEach(timedVoteRow -> {
|
||||
VoteTimeQueue voteTimeQueue = new VoteTimeQueue(timedVoteRow.getVoteId(), timedVoteRow.getPlayerName(),
|
||||
timedVoteRow.getService(), timedVoteRow.getTime(), timedVoteRow.isProxyBroadcastHandled(),
|
||||
VoteTimeQueue.decodeBroadcastForwardedServers(timedVoteRow.getBroadcastTargets()),
|
||||
VoteTimeQueue.decodeBroadcastForwardedServers(timedVoteRow.getBroadcastForwardedServers()),
|
||||
timedVoteRow.getTotals(), timedVoteRow.isProcessed(),
|
||||
timedVoteRow.isMultiProxyForwardingHandled(), timedVoteRow.getUuid(),
|
||||
VoteTimeQueue.decodeHttpBroadcastDeliveryIds(timedVoteRow.getHttpBroadcastDeliveryIds()));
|
||||
voteTimeQueue.setMultiProxyForwardingRequired(timedVoteRow.isMultiProxyForwardingRequired());
|
||||
voteTimeQueue.setMultiProxyCapabilityDiscoveryPending(
|
||||
timedVoteRow.isMultiProxyCapabilityDiscoveryPending());
|
||||
voteTimeQueue.setVotePartyApplied(timedVoteRow.isVotePartyApplied());
|
||||
voteTimeQueue.setTotalsApplied(timedVoteRow.isTotalsApplied());
|
||||
voteTimeQueue.setRealVote(timedVoteRow.isRealVote());
|
||||
if (timedVoteRow.isWasOnlineKnown()) voteTimeQueue.setWasOnline(timedVoteRow.isWasOnline());
|
||||
if (timedVoteRow.getDelayValidation() >= 0) {
|
||||
voteTimeQueue.setDelayValidated(timedVoteRow.getDelayValidation() == 1);
|
||||
} else voteTimeQueue.clearDelayValidation();
|
||||
voteTimeQueue.setMultiProxyOrigin(timedVoteRow.getMultiProxyOrigin() == null ? ""
|
||||
: timedVoteRow.getMultiProxyOrigin());
|
||||
voteTimeQueue.setMultiProxyCompletionPending(timedVoteRow.isMultiProxyCompletionPending());
|
||||
voteTimeQueue.setMultiProxyRecipients(
|
||||
VoteTimeQueue.decodeBroadcastForwardedServers(timedVoteRow.getMultiProxyRecipients()));
|
||||
voteTimeQueue.setMultiProxyAcknowledgedServers(
|
||||
VoteTimeQueue.decodeBroadcastForwardedServers(timedVoteRow.getMultiProxyAcknowledgedServers()));
|
||||
voteTimeQueue.setMultiProxyLegacyPendingRecipients(
|
||||
VoteTimeQueue.decodeBroadcastForwardedServers(
|
||||
timedVoteRow.getMultiProxyLegacyPendingRecipients()));
|
||||
voteTimeQueue.setTimedVoteCacheRowId(timedVoteRow.getId());
|
||||
timedVotes.add(voteTimeQueue);
|
||||
});
|
||||
timeChangeQueue.addAll(timedVotes);
|
||||
unresolvedSqlBatchIdentity = !loadJsonEmergencyVotes(serverSourceRows, onlineSourceRows);
|
||||
} catch (RuntimeException failure) {
|
||||
cachedVotes = previousVotes;
|
||||
cachedOnlineVotes = previousOnlineVotes;
|
||||
timeChangeQueue = previousTimedVotes;
|
||||
throw failure;
|
||||
}
|
||||
|
||||
} else {
|
||||
cachedVotes.clear();
|
||||
cachedOnlineVotes.clear();
|
||||
timeChangeQueue.clear();
|
||||
try {
|
||||
for (String key : jsonStorage.getTimedVoteCache()) {
|
||||
DataNode data = jsonStorage.getTimedVoteCache(key);
|
||||
@@ -1397,6 +1616,7 @@ public abstract class VoteCacheHandler {
|
||||
if (data.has("DelayValidationKnown") && data.get("DelayValidationKnown").asBoolean())
|
||||
vote.setDelayValidated(data.has("DelayValidated") && data.get("DelayValidated").asBoolean());
|
||||
else vote.clearDelayValidation();
|
||||
restoreCachedVoteBatch(vote, data);
|
||||
vote.setServerVoteCacheJsonKey(num);
|
||||
votes.add(vote);
|
||||
}
|
||||
@@ -1451,6 +1671,7 @@ public abstract class VoteCacheHandler {
|
||||
if (data.has("DelayValidationKnown") && data.get("DelayValidationKnown").asBoolean())
|
||||
vote.setDelayValidated(data.has("DelayValidated") && data.get("DelayValidated").asBoolean());
|
||||
else vote.clearDelayValidation();
|
||||
restoreCachedVoteBatch(vote, data);
|
||||
vote.setOnlineVoteCacheJsonKey(num);
|
||||
votes.add(vote);
|
||||
}
|
||||
@@ -1479,14 +1700,26 @@ public abstract class VoteCacheHandler {
|
||||
|
||||
/**
|
||||
* Loads entries written to the JSON emergency journal while MySQL was
|
||||
* unavailable. Entries already present in SQL are de-duplicated only by vote
|
||||
* ID. Legacy entries without an ID remain distinct because equal fields cannot
|
||||
* prove that two durable rows represent the same vote.
|
||||
* unavailable. Stable vote IDs bind duplicates; legacy twins require the exact
|
||||
* persisted SQL source row and complete original vote identity.
|
||||
*/
|
||||
private void loadJsonEmergencyVotes() {
|
||||
if (jsonStorage == null || !jsonStorage.hasEmergencyJournalMarker()) {
|
||||
return;
|
||||
private boolean loadJsonEmergencyVotes(Set<Integer> serverSourceRows, Set<Integer> onlineSourceRows) {
|
||||
if (jsonStorage == null) return false;
|
||||
if (!jsonStorage.hasEmergencyJournalMarker()) return true;
|
||||
boolean resolved = true;
|
||||
com.google.gson.JsonObject persistedJournal = null;
|
||||
try {
|
||||
if (jsonStorage.getStoragePath() != null) {
|
||||
persistedJournal = VoteCacheDurability.readJournal(jsonStorage.getStoragePath());
|
||||
resolved = sqlJournalStructureIsValid(persistedJournal);
|
||||
}
|
||||
}
|
||||
catch (IOException | RuntimeException invalid) {
|
||||
resolved = false;
|
||||
debug1(new IllegalStateException("Unable to classify SQL vote journal structure"));
|
||||
}
|
||||
List<Entry<String, OfflineBungeeVote>> orphanedServerTwins = new ArrayList<>();
|
||||
List<Entry<String, OfflineBungeeVote>> orphanedOnlineTwins = new ArrayList<>();
|
||||
try {
|
||||
// Timed votes use the JSON store as an emergency outbox when the SQL
|
||||
// insert failed. Merge them before the ordinary cache lanes so an ACK
|
||||
@@ -1517,12 +1750,33 @@ public abstract class VoteCacheHandler {
|
||||
continue;
|
||||
}
|
||||
for (String key : keys) {
|
||||
OfflineBungeeVote vote = decodeJsonVote(jsonStorage.getServerVotes(server, key));
|
||||
if (vote == null) continue;
|
||||
OfflineBungeeVote vote;
|
||||
try {
|
||||
DataNode data = persistedJournal == null ? jsonStorage.getServerVotes(server, key)
|
||||
: persistedSqlJournalVote(persistedJournal, "VoteCache", server, key);
|
||||
validateSqlJournalIdentity(data);
|
||||
vote = decodeJsonVote(data);
|
||||
} catch (RuntimeException invalid) {
|
||||
resolved = false;
|
||||
debug1(new IllegalStateException("Invalid SQL vote journal identity"));
|
||||
continue;
|
||||
}
|
||||
if (vote == null) { resolved = false; continue; }
|
||||
vote.setServerVoteCacheJsonKey(key);
|
||||
OfflineBungeeVote sqlTwin = findServerVoteSqlTwin(server, vote);
|
||||
if (sqlTwin != null) sqlTwin.setServerVoteCacheJsonKey(key);
|
||||
else cachedVotes.computeIfAbsent(server, ignored -> new ArrayList<>()).add(vote);
|
||||
if (!vote.isCachedVoteBatchValid()) resolved = false;
|
||||
if (sqlTwin != null) {
|
||||
sqlTwin.setServerVoteCacheJsonKey(key);
|
||||
sqlTwin.copyCachedVoteBatch(vote);
|
||||
if (vote.getVoteId() != null) sqlTwin.assignCachedVoteId(vote.getVoteId());
|
||||
}
|
||||
else if (vote.getCachedBatchSourceRowId() > 0) {
|
||||
// Only a complete SQL snapshot can prove this source was removed.
|
||||
// A present or malformed unmatched source stays on disk, outside replay.
|
||||
if (vote.isCachedVoteBatchValid() && !serverSourceRows.contains(vote.getCachedBatchSourceRowId()))
|
||||
orphanedServerTwins.add(Map.entry(server, vote));
|
||||
else resolved = false;
|
||||
} else cachedVotes.computeIfAbsent(server, ignored -> new ArrayList<>()).add(vote);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1534,18 +1788,102 @@ public abstract class VoteCacheHandler {
|
||||
continue;
|
||||
}
|
||||
for (String key : keys) {
|
||||
OfflineBungeeVote vote = decodeJsonVote(jsonStorage.getOnlineVotes(player, key));
|
||||
if (vote == null) continue;
|
||||
OfflineBungeeVote vote;
|
||||
try {
|
||||
DataNode data = persistedJournal == null ? jsonStorage.getOnlineVotes(player, key)
|
||||
: persistedSqlJournalVote(persistedJournal, "OnlineCache", player, key);
|
||||
validateSqlJournalIdentity(data);
|
||||
vote = decodeJsonVote(data);
|
||||
} catch (RuntimeException invalid) {
|
||||
resolved = false;
|
||||
debug1(new IllegalStateException("Invalid SQL vote journal identity"));
|
||||
continue;
|
||||
}
|
||||
if (vote == null) { resolved = false; continue; }
|
||||
vote.setOnlineVoteCacheJsonKey(key);
|
||||
OfflineBungeeVote sqlTwin = findOnlineVoteSqlTwin(player, vote);
|
||||
if (sqlTwin != null) sqlTwin.setOnlineVoteCacheJsonKey(key);
|
||||
else cachedOnlineVotes.computeIfAbsent(player, ignored -> new ArrayList<>()).add(vote);
|
||||
if (!vote.isCachedVoteBatchValid()) resolved = false;
|
||||
if (sqlTwin != null) {
|
||||
sqlTwin.setOnlineVoteCacheJsonKey(key);
|
||||
sqlTwin.copyCachedVoteBatch(vote);
|
||||
if (vote.getVoteId() != null) sqlTwin.assignCachedVoteId(vote.getVoteId());
|
||||
}
|
||||
else if (vote.getCachedBatchSourceRowId() > 0) {
|
||||
if (vote.isCachedVoteBatchValid() && !onlineSourceRows.contains(vote.getCachedBatchSourceRowId()))
|
||||
orphanedOnlineTwins.add(Map.entry(player, vote));
|
||||
else resolved = false;
|
||||
} else cachedOnlineVotes.computeIfAbsent(player, ignored -> new ArrayList<>()).add(vote);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (RuntimeException e) {
|
||||
debug1(e);
|
||||
resolved = false;
|
||||
debug1(new IllegalStateException("Unable to classify SQL vote journal"));
|
||||
}
|
||||
// Retain the entire journal while any row cannot be safely reconstructed.
|
||||
if (!resolved) return false;
|
||||
// Cleanup failure must not turn a confirmed removed SQL owner into a live vote.
|
||||
for (Entry<String, OfflineBungeeVote> orphan : orphanedServerTwins) {
|
||||
try { if (!removeJsonServerVoteDurably(orphan.getKey(), orphan.getValue())) resolved = false; }
|
||||
catch (RuntimeException failure) { resolved = false; debug1(failure); }
|
||||
}
|
||||
for (Entry<String, OfflineBungeeVote> orphan : orphanedOnlineTwins) {
|
||||
try { if (!removeJsonOnlineVoteDurably(orphan.getKey(), orphan.getValue())) resolved = false; }
|
||||
catch (RuntimeException failure) { resolved = false; debug1(failure); }
|
||||
}
|
||||
return resolved;
|
||||
}
|
||||
|
||||
private boolean sqlJournalStructureIsValid(com.google.gson.JsonObject document) {
|
||||
// Configurate discards explicit JSON null children. Inspect persisted structure
|
||||
// so those unresolved records cannot vanish from Velocity's recovery scan.
|
||||
for (String lane : new String[] {"VoteCache", "OnlineCache"}) {
|
||||
if (!document.has(lane)) continue;
|
||||
var owners = document.get(lane);
|
||||
if (!owners.isJsonObject()) return false;
|
||||
for (var owner : owners.getAsJsonObject().entrySet()) {
|
||||
if (!owner.getValue().isJsonObject()) return false;
|
||||
Collection<String> loadedKeys = lane.equals("VoteCache") ? jsonStorage.getServerVotes(owner.getKey())
|
||||
: jsonStorage.getOnlineVotes(owner.getKey());
|
||||
for (var row : owner.getValue().getAsJsonObject().entrySet()) {
|
||||
if (!row.getValue().isJsonObject()) return false;
|
||||
// A normalized-away binding is unresolved even when its raw object
|
||||
// survives structural parsing. Inspect every raw row before clearing.
|
||||
if (loadedKeys == null || !loadedKeys.contains(row.getKey())) return false;
|
||||
try {
|
||||
DataNode data = new GsonDataNode(row.getValue());
|
||||
validateSqlJournalIdentity(data);
|
||||
OfflineBungeeVote vote = decodeJsonVote(data);
|
||||
if (vote == null || !vote.isCachedVoteBatchValid()) return false;
|
||||
} catch (RuntimeException invalid) { return false; }
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private DataNode persistedSqlJournalVote(com.google.gson.JsonObject document, String lane,
|
||||
String owner, String key) {
|
||||
// Classify raw values before an adapter can turn explicit null fields into absence.
|
||||
var data = document.getAsJsonObject(lane).getAsJsonObject(owner).get(key);
|
||||
return data == null ? null : new GsonDataNode(data);
|
||||
}
|
||||
|
||||
private void validateSqlJournalIdentity(DataNode data) {
|
||||
if (data == null || !data.isObject()) throw new IllegalArgumentException("Invalid SQL vote journal row");
|
||||
if (VoteCacheDurability.isOpaqueRecoveryRow(data))
|
||||
throw new IllegalArgumentException("Opaque SQL vote journal row");
|
||||
// Old emergency rows without replay metadata retain their established optional fields.
|
||||
if (!data.has("CachedBatchNumber") && !data.has("CachedBatchSize")
|
||||
&& !data.has("CachedBatchSourceRowId")) return;
|
||||
for (String field : new String[] {"Name", "UUID", "Service", "Text"})
|
||||
if (!data.has(field) || !data.get(field).isPrimitive()
|
||||
|| !(data.get(field).asPrimitive() instanceof String))
|
||||
throw new IllegalArgumentException("Invalid SQL vote journal identity");
|
||||
if (!data.has("Real") || !(data.get("Real").asPrimitive() instanceof Boolean)
|
||||
|| !data.has("Time") || !(data.get("Time").asPrimitive() instanceof Number))
|
||||
throw new IllegalArgumentException("Invalid SQL vote journal identity");
|
||||
new java.math.BigDecimal(data.get("Time").asString()).longValueExact();
|
||||
}
|
||||
|
||||
private boolean ensureEmergencyJournalMarker() {
|
||||
@@ -1655,9 +1993,46 @@ public abstract class VoteCacheHandler {
|
||||
if (data.has("DelayValidationKnown") && data.get("DelayValidationKnown").asBoolean())
|
||||
vote.setDelayValidated(data.has("DelayValidated") && data.get("DelayValidated").asBoolean());
|
||||
else vote.clearDelayValidation();
|
||||
restoreCachedVoteBatch(vote, data);
|
||||
return vote;
|
||||
}
|
||||
|
||||
private void restoreCachedVoteBatch(OfflineBungeeVote vote, DataNode data) {
|
||||
if (!data.has("CachedBatchNumber") && !data.has("CachedBatchSize")
|
||||
&& !data.has("CachedBatchSourceRowId")) return;
|
||||
try {
|
||||
int source = batchInteger(data, "CachedBatchSourceRowId");
|
||||
if (source > 0) {
|
||||
for (String field : new String[] {"Name", "UUID", "Service", "Text"})
|
||||
if (!data.has(field) || !data.get(field).isPrimitive()
|
||||
|| !(data.get(field).asPrimitive() instanceof String))
|
||||
throw new IllegalArgumentException("Missing cached replay identity");
|
||||
if (!data.has("Real") || !(data.get("Real").asPrimitive() instanceof Boolean)
|
||||
|| !data.has("Time") || !(data.get("Time").asPrimitive() instanceof Number))
|
||||
throw new IllegalArgumentException("Invalid cached replay identity");
|
||||
new java.math.BigDecimal(data.get("Time").asString()).longValueExact();
|
||||
}
|
||||
if (source < 0) throw new IllegalArgumentException("Invalid cached replay source");
|
||||
vote.setCachedBatchSourceRowId(source);
|
||||
int number = batchInteger(data, "CachedBatchNumber");
|
||||
int size = batchInteger(data, "CachedBatchSize");
|
||||
vote.setCachedVoteBatch(number, size);
|
||||
if (!vote.isCachedVoteBatchValid()) throw new IllegalArgumentException("Invalid cached replay metadata");
|
||||
vote.setCachedBatchDurable(vote.hasCachedVoteBatch());
|
||||
} catch (RuntimeException invalid) {
|
||||
// Preserve the row for recovery, but make it ineligible for replay.
|
||||
vote.setCachedVoteBatch(-1, -1);
|
||||
debug1(new IllegalStateException("Invalid cached replay metadata"));
|
||||
}
|
||||
}
|
||||
|
||||
private int batchInteger(DataNode data, String field) {
|
||||
if (!data.has(field) || !data.get(field).isPrimitive()
|
||||
|| !(data.get(field).asPrimitive() instanceof Number))
|
||||
throw new IllegalArgumentException("Missing or invalid cached replay field");
|
||||
return new java.math.BigDecimal(data.get(field).asString()).intValueExact();
|
||||
}
|
||||
|
||||
private final boolean useMySQL;
|
||||
private ProxyVoteCacheTable voteCacheTable;
|
||||
private ProxyTimedVoteCacheTable timedVoteCacheTable;
|
||||
@@ -1870,8 +2245,12 @@ public abstract class VoteCacheHandler {
|
||||
* @param removed list of votes to remove
|
||||
*/
|
||||
public synchronized void removeServerVotes(String server, ArrayList<OfflineBungeeVote> removed) {
|
||||
for (OfflineBungeeVote vote : removed) {
|
||||
boolean mysqlRemoved = !useMySQL || voteCacheTable.tryRemoveVote(vote, server);
|
||||
for (OfflineBungeeVote vote : new ArrayList<>(removed)) {
|
||||
boolean mysqlRemoved = !useMySQL
|
||||
|| vote.getServerVoteCacheRowId() <= 0 && vote.getCachedBatchSourceRowId() > 0
|
||||
|| voteCacheTable.tryRemoveVote(vote, server);
|
||||
if (!mysqlRemoved) continue;
|
||||
if (useMySQL && vote.getServerVoteCacheRowId() > 0) retireServerReplayOwner(server, vote);
|
||||
boolean jsonRemoved = jsonStorage == null;
|
||||
if (jsonStorage != null && !jsonStorageQuarantined
|
||||
&& (!useMySQL || vote.getServerVoteCacheRowId() <= 0
|
||||
@@ -1884,15 +2263,23 @@ public abstract class VoteCacheHandler {
|
||||
}
|
||||
boolean removedDurably = mysqlRemoved && jsonRemoved;
|
||||
if (!removedDurably) continue;
|
||||
ArrayList<OfflineBungeeVote> serverVotes = cachedVotes.get(server);
|
||||
if (serverVotes != null) {
|
||||
serverVotes.removeIf(candidate -> sameVoteIdentity(candidate, vote));
|
||||
if (serverVotes.isEmpty()) cachedVotes.remove(server);
|
||||
}
|
||||
retireServerReplayOwner(server, vote);
|
||||
}
|
||||
}
|
||||
|
||||
private void retireServerReplayOwner(String server, OfflineBungeeVote removedVote) {
|
||||
ArrayList<OfflineBungeeVote> votes = cachedVotes.get(server);
|
||||
if (votes == null) return;
|
||||
votes.removeIf(vote -> sameVoteIdentity(vote, removedVote));
|
||||
if (votes.isEmpty()) cachedVotes.remove(server);
|
||||
}
|
||||
|
||||
protected boolean removeJsonServerVoteDurably(String server, OfflineBungeeVote vote) {
|
||||
if (jsonStorage == null || jsonStorageQuarantined) return false;
|
||||
synchronized (jsonStorage) { return removeJsonServerVoteDurablyLocked(server, vote); }
|
||||
}
|
||||
|
||||
private boolean removeJsonServerVoteDurablyLocked(String server, OfflineBungeeVote vote) {
|
||||
jsonStorage.removeVote(server, vote);
|
||||
try {
|
||||
return VoteCacheDurability.saveAndVerifyRemoval(jsonStorage,
|
||||
|
||||
Vendored
+4
-4
@@ -2,7 +2,6 @@ package com.bencodez.votingplugin.proxy.cache;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Base64;
|
||||
import java.util.HashMap;
|
||||
@@ -12,7 +11,6 @@ import java.util.Set;
|
||||
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParser;
|
||||
import com.bencodez.votingplugin.util.DurableFiles;
|
||||
|
||||
/** Verifies that the cache library actually persisted the vote-party transaction. */
|
||||
@@ -25,6 +23,7 @@ public final class VotePartyCacheDurability {
|
||||
int expectedIncrease = cache.getVotePartyInreaseVotesRequired();
|
||||
PendingVotePartyProxyEffects expectedProxyEffects = cache.getPendingVotePartyProxyEffects();
|
||||
PendingVotePartyProxyEffects expectedQuarantinedEffects = cache.getQuarantinedVotePartyProxyEffects();
|
||||
PendingPluginMessageVotePartyRewards expectedPluginRewards = cache.getPluginMessageVotePartyRewards();
|
||||
try {
|
||||
cache.saveDurably();
|
||||
} catch (DurableFiles.PublishedException published) {
|
||||
@@ -32,13 +31,14 @@ public final class VotePartyCacheDurability {
|
||||
// restore stale in-memory state over the published file.
|
||||
}
|
||||
try {
|
||||
JsonObject root = JsonParser.parseString(Files.readString(file, StandardCharsets.UTF_8)).getAsJsonObject();
|
||||
JsonObject root = VoteCacheDurability.readJournal(file);
|
||||
JsonObject voteParty = object(root.get("VoteParty"));
|
||||
if (integer(voteParty, "CurrentVotes") != expectedVotes
|
||||
|| integer(voteParty, "IncreaseVotes") != expectedIncrease
|
||||
|| !pending(voteParty).equals(expectedPending)
|
||||
|| !proxyEffects(voteParty, "PendingProxyEffects").equals(expectedProxyEffects)
|
||||
|| !proxyEffects(voteParty, "QuarantinedProxyEffects").equals(expectedQuarantinedEffects))
|
||||
|| !proxyEffects(voteParty, "QuarantinedProxyEffects").equals(expectedQuarantinedEffects)
|
||||
|| !PendingPluginMessageVotePartyRewards.fromCacheJson(root).equals(expectedPluginRewards))
|
||||
throw new IOException("Vote-party cache state was not persisted");
|
||||
} catch (IOException failure) {
|
||||
throw failure;
|
||||
|
||||
+15
-1
@@ -444,6 +444,14 @@ public abstract class MultiProxyHandler {
|
||||
triggerVote(player, service, realVote, timeQueue, queueTime, text, uuid, voteId, origin);
|
||||
}
|
||||
|
||||
/** Additive occurrence metadata; queueTime remains the normal receiver clock convention. */
|
||||
public void triggerVote(String player, String service, boolean realVote, boolean timeQueue, long queueTime,
|
||||
VoteTotalsSnapshot text, String uuid, UUID voteId, String origin, boolean delayValidated,
|
||||
boolean delayValidationKnown, long canonicalOccurrenceTime) {
|
||||
triggerVote(player, service, realVote, timeQueue, queueTime, text, uuid, voteId, origin,
|
||||
delayValidated, delayValidationKnown);
|
||||
}
|
||||
|
||||
/** Called when a receiver acknowledges this proxy's stable vote ID. */
|
||||
public void onMultiProxyVoteAcknowledged(UUID voteId, String recipient) {
|
||||
// Optional for legacy implementations.
|
||||
@@ -1276,8 +1284,14 @@ public abstract class MultiProxyHandler {
|
||||
if (origin.isBlank()) {
|
||||
triggerVote(player, service, realVote, true, 0L, VoteTotalsSnapshot.parseStorage(totals), uuid);
|
||||
} else {
|
||||
// Older reliable origin envelopes still carry the sender's original
|
||||
// time. Keep it separate from receiver-local cooldown processing.
|
||||
long occurrenceTime = !f.containsKey(VotingPluginWire.K_CANONICAL_OCCURRENCE_TIME)
|
||||
&& com.bencodez.votingplugin.proxy.VoteOccurrenceMetadata.read(totals) == null
|
||||
? wireVote.time : wireVote.canonicalOccurrenceTime;
|
||||
triggerVote(player, service, realVote, true, 0L, VoteTotalsSnapshot.parseStorage(totals), uuid,
|
||||
wireVote.voteId, origin, wireVote.delayValidated, wireVote.delayValidationKnown);
|
||||
wireVote.voteId, origin, wireVote.delayValidated, wireVote.delayValidationKnown,
|
||||
occurrenceTime);
|
||||
}
|
||||
}
|
||||
return;
|
||||
|
||||
+153
-30
@@ -1,6 +1,7 @@
|
||||
package com.bencodez.votingplugin.proxy.velocity;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
@@ -15,16 +16,22 @@ import com.bencodez.votingplugin.proxy.OfflineBungeeVote;
|
||||
import com.bencodez.votingplugin.proxy.cache.ConfigDataNode;
|
||||
import com.bencodez.votingplugin.proxy.cache.DataNode;
|
||||
import com.bencodez.votingplugin.proxy.cache.IVoteCache;
|
||||
import com.bencodez.votingplugin.proxy.cache.VoteCacheDurability;
|
||||
import com.bencodez.votingplugin.proxy.cache.PendingVotePartyProxyEffects;
|
||||
import com.bencodez.votingplugin.proxy.cache.PendingPluginMessageVotePartyRewards;
|
||||
import com.bencodez.votingplugin.timequeue.VoteTimeQueue;
|
||||
import com.bencodez.votingplugin.util.DurableFiles;
|
||||
|
||||
import org.spongepowered.configurate.gson.GsonConfigurationLoader;
|
||||
|
||||
import com.google.gson.JsonObject;
|
||||
|
||||
/**
|
||||
* JSON-based vote cache implementation for Velocity proxy.
|
||||
*/
|
||||
public class VelocityJsonVoteCache extends VelocityJSONFile implements IVoteCache {
|
||||
private boolean writesPaused;
|
||||
private boolean journalLoaded;
|
||||
|
||||
/**
|
||||
* Constructs a new Velocity JSON vote cache.
|
||||
@@ -32,22 +39,119 @@ public class VelocityJsonVoteCache extends VelocityJSONFile implements IVoteCach
|
||||
*/
|
||||
public VelocityJsonVoteCache(File file) {
|
||||
super(file);
|
||||
reload();
|
||||
}
|
||||
|
||||
@Override
|
||||
public java.nio.file.Path getStoragePath() {
|
||||
public synchronized java.nio.file.Path getStoragePath() {
|
||||
return getPath();
|
||||
}
|
||||
|
||||
/** Routine saves use the same atomic publication and reload failure fence as journal writes. */
|
||||
@Override
|
||||
public synchronized void save() {
|
||||
if (writesPaused) return;
|
||||
try {
|
||||
saveDurably();
|
||||
} catch (IOException failure) {
|
||||
java.util.logging.Logger.getLogger(getClass().getName())
|
||||
.log(java.util.logging.Level.WARNING, "Unable to save the vote cache", failure);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized void reload() {
|
||||
try {
|
||||
var document = VoteCacheDurability.readJournal(getStoragePath());
|
||||
PendingPluginMessageVotePartyRewards.fromCacheJson(document);
|
||||
var loaded = GsonConfigurationLoader.builder()
|
||||
.source(() -> new java.io.BufferedReader(new java.io.StringReader(document.toString())))
|
||||
.build().load();
|
||||
validateTimedRows(document, loaded);
|
||||
// readJournal already verifies the raw object. Configurate can normalize
|
||||
// an object containing only null cache entries to an empty root.
|
||||
super.setConf(loaded);
|
||||
writesPaused = false;
|
||||
journalLoaded = true;
|
||||
} catch (IOException failure) {
|
||||
writesPaused = true;
|
||||
throw new UncheckedIOException("Unable to reload the vote cache", failure);
|
||||
} catch (RuntimeException failure) {
|
||||
writesPaused = true;
|
||||
throw failure;
|
||||
}
|
||||
}
|
||||
|
||||
/** Checks raw recovery fields using the same normalized flag coercion as the timed decoder. */
|
||||
private static void validateTimedRows(JsonObject document, org.spongepowered.configurate.ConfigurationNode loaded)
|
||||
throws IOException {
|
||||
if (!document.has("TimedVoteCache")) return;
|
||||
for (var entry : document.getAsJsonObject("TimedVoteCache").entrySet()) {
|
||||
var node = loaded.node("TimedVoteCache", entry.getKey());
|
||||
if (!node.isMap() || node.childrenMap().isEmpty())
|
||||
throw new IOException("Timed vote cache entry requires recovery");
|
||||
JsonObject raw = entry.getValue().getAsJsonObject();
|
||||
if (node.node("WasOnlineKnown").getBoolean()
|
||||
&& (!raw.has("WasOnline") || !raw.get("WasOnline").isJsonPrimitive()))
|
||||
throw new IOException("Timed vote cache entry requires recovery");
|
||||
if (node.node("DelayValidationKnown").getBoolean()
|
||||
&& raw.has("DelayValidated") && !raw.get("DelayValidated").isJsonPrimitive())
|
||||
throw new IOException("Timed vote cache entry requires recovery");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized org.spongepowered.configurate.ConfigurationNode getData() { return super.getData(); }
|
||||
@Override
|
||||
public synchronized org.spongepowered.configurate.ConfigurationNode getConf() { return super.getConf(); }
|
||||
@Override
|
||||
public synchronized org.spongepowered.configurate.ConfigurationNode getNode(Object... path) { return super.getNode(path); }
|
||||
@Override
|
||||
public synchronized void setConf(org.spongepowered.configurate.ConfigurationNode conf) { super.setConf(conf); }
|
||||
@Override
|
||||
public synchronized void set(Object[] path, Object value) { super.set(path, value); }
|
||||
@Override
|
||||
public synchronized void remove(Object... path) { super.remove(path); }
|
||||
|
||||
@Override
|
||||
public synchronized void saveDurably() throws IOException {
|
||||
if (writesPaused) throw new IOException("Vote cache writes require a successful reload");
|
||||
Path target = getStoragePath().toAbsolutePath().normalize();
|
||||
JsonObject previous = null;
|
||||
if (journalLoaded) {
|
||||
try {
|
||||
previous = VoteCacheDurability.readJournal(target);
|
||||
String rawPrevious = previous.toString();
|
||||
var previousNodes = GsonConfigurationLoader.builder()
|
||||
.source(() -> new java.io.BufferedReader(new java.io.StringReader(rawPrevious)))
|
||||
.build().load();
|
||||
validateTimedRows(previous, previousNodes);
|
||||
PendingPluginMessageVotePartyRewards.fromCacheJson(previous);
|
||||
}
|
||||
catch (IOException | RuntimeException failure) {
|
||||
writesPaused = true;
|
||||
throw new IOException("Vote cache is unreadable; reload is required before saving", failure);
|
||||
}
|
||||
}
|
||||
Path parent = target.getParent();
|
||||
if (parent == null) throw new IOException("Vote cache has no parent directory");
|
||||
Files.createDirectories(parent);
|
||||
Path staged = Files.createTempFile(parent, target.getFileName().toString(), ".tmp");
|
||||
try {
|
||||
GsonConfigurationLoader.builder().path(staged).build().save(getConf());
|
||||
Object root = getConf().raw();
|
||||
if (root == null || root instanceof java.util.Map<?, ?> map && map.isEmpty()) {
|
||||
// Configurate's empty-root writer can emit null or consecutive objects.
|
||||
// An empty cache always remains one complete JSON object on disk.
|
||||
Files.writeString(staged, "{}", StandardCharsets.UTF_8);
|
||||
} else {
|
||||
GsonConfigurationLoader.builder().path(staged).build().save(getConf());
|
||||
}
|
||||
JsonObject candidate = VoteCacheDurability.readJournal(staged);
|
||||
if (previous != null && hasEmergencyJournalMarker()
|
||||
&& VoteCacheDurability.preserveUnresolvedCacheRows(previous, candidate)) {
|
||||
Files.writeString(staged, candidate.toString(), StandardCharsets.UTF_8);
|
||||
}
|
||||
PendingPluginMessageVotePartyRewards.fromCacheJson(VoteCacheDurability.readJournal(staged));
|
||||
DurableFiles.publishStagedFile(staged, target);
|
||||
} finally {
|
||||
Files.deleteIfExists(staged);
|
||||
@@ -55,7 +159,7 @@ public class VelocityJsonVoteCache extends VelocityJSONFile implements IVoteCach
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addTimedVote(int num, VoteTimeQueue voteTimedQueue) {
|
||||
public synchronized void addTimedVote(int num, VoteTimeQueue voteTimedQueue) {
|
||||
setPath(voteTimedQueue.getName(), "TimedVoteCache", String.valueOf(num), "Name");
|
||||
setPath(voteTimedQueue.getService(), "TimedVoteCache", String.valueOf(num), "Service");
|
||||
setPath(voteTimedQueue.getTime(), "TimedVoteCache", String.valueOf(num), "Time");
|
||||
@@ -97,7 +201,7 @@ public class VelocityJsonVoteCache extends VelocityJSONFile implements IVoteCach
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addVote(String server, int num, OfflineBungeeVote voteData) {
|
||||
public synchronized void addVote(String server, int num, OfflineBungeeVote voteData) {
|
||||
setPath(voteData.getPlayerName(), "VoteCache", server, String.valueOf(num), "Name");
|
||||
setPath(voteData.getService(), "VoteCache", server, String.valueOf(num), "Service");
|
||||
setPath(voteData.getUuid(), "VoteCache", server, String.valueOf(num), "UUID");
|
||||
@@ -117,11 +221,14 @@ public class VelocityJsonVoteCache extends VelocityJSONFile implements IVoteCach
|
||||
"BroadcastForwardedServers");
|
||||
setPath(voteData.isRewardDelivered(), "VoteCache", server, String.valueOf(num), "RewardDelivered");
|
||||
setPath(voteData.encodeHttpDeliveryIds(), "VoteCache", server, String.valueOf(num), "HttpDeliveryIds");
|
||||
setPath(voteData.getCachedBatchNumber(), "VoteCache", server, String.valueOf(num), "CachedBatchNumber");
|
||||
setPath(voteData.getCachedBatchSize(), "VoteCache", server, String.valueOf(num), "CachedBatchSize");
|
||||
setPath(voteData.getCachedBatchSourceRowId(), "VoteCache", server, String.valueOf(num), "CachedBatchSourceRowId");
|
||||
setPath(voteData.encodeHttpBroadcastDeliveryIds(), "VoteCache", server, String.valueOf(num), "HttpBroadcastDeliveryIds");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addVoteOnline(String player, int num, OfflineBungeeVote voteData) {
|
||||
public synchronized void addVoteOnline(String player, int num, OfflineBungeeVote voteData) {
|
||||
setPath(voteData.getPlayerName(), "OnlineCache", player, String.valueOf(num), "Name");
|
||||
setPath(voteData.getService(), "OnlineCache", player, String.valueOf(num), "Service");
|
||||
setPath(voteData.getUuid(), "OnlineCache", player, String.valueOf(num), "UUID");
|
||||
@@ -141,11 +248,14 @@ public class VelocityJsonVoteCache extends VelocityJSONFile implements IVoteCach
|
||||
"BroadcastForwardedServers");
|
||||
setPath(voteData.isRewardDelivered(), "OnlineCache", player, String.valueOf(num), "RewardDelivered");
|
||||
setPath(voteData.encodeHttpDeliveryIds(), "OnlineCache", player, String.valueOf(num), "HttpDeliveryIds");
|
||||
setPath(voteData.getCachedBatchNumber(), "OnlineCache", player, String.valueOf(num), "CachedBatchNumber");
|
||||
setPath(voteData.getCachedBatchSize(), "OnlineCache", player, String.valueOf(num), "CachedBatchSize");
|
||||
setPath(voteData.getCachedBatchSourceRowId(), "OnlineCache", player, String.valueOf(num), "CachedBatchSourceRowId");
|
||||
setPath(voteData.encodeHttpBroadcastDeliveryIds(), "OnlineCache", player, String.valueOf(num), "HttpBroadcastDeliveryIds");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clearData() {
|
||||
public synchronized void clearData() {
|
||||
remove("VoteCache");
|
||||
remove("OnlineCache");
|
||||
remove("TimedVoteCache");
|
||||
@@ -153,7 +263,7 @@ public class VelocityJsonVoteCache extends VelocityJSONFile implements IVoteCach
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<String> getOnlineVotes(String name) {
|
||||
public synchronized Collection<String> getOnlineVotes(String name) {
|
||||
return getKeys(getNode("OnlineCache", name));
|
||||
}
|
||||
|
||||
@@ -163,17 +273,17 @@ public class VelocityJsonVoteCache extends VelocityJSONFile implements IVoteCach
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<String> getPlayers() {
|
||||
public synchronized Collection<String> getPlayers() {
|
||||
return getKeys(getNode("OnlineCache"));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<String> getServers() {
|
||||
public synchronized Collection<String> getServers() {
|
||||
return getKeys(getNode("VoteCache"));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<String> getServerVotes(String server) {
|
||||
public synchronized Collection<String> getServerVotes(String server) {
|
||||
return getKeys(getNode("VoteCache", server));
|
||||
}
|
||||
|
||||
@@ -183,7 +293,7 @@ public class VelocityJsonVoteCache extends VelocityJSONFile implements IVoteCach
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<String> getTimedVoteCache() {
|
||||
public synchronized Collection<String> getTimedVoteCache() {
|
||||
return getKeys(getNode("TimedVoteCache"));
|
||||
}
|
||||
|
||||
@@ -193,17 +303,30 @@ public class VelocityJsonVoteCache extends VelocityJSONFile implements IVoteCach
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeTimedVotes() {
|
||||
public synchronized void removeTimedVotes() {
|
||||
remove("TimedVoteCache");
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getVotePartyCache(String server) {
|
||||
public synchronized int getVotePartyCache(String server) {
|
||||
return getNode("VoteParty", "Cache", server).getInt(0);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<String> getPendingVotePartyRewardServers() {
|
||||
public synchronized PendingPluginMessageVotePartyRewards getPluginMessageVotePartyRewards() {
|
||||
return PendingPluginMessageVotePartyRewards.fromStorageValue(
|
||||
getNode("VoteParty", "PluginMessageRewards").raw());
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized void setPluginMessageVotePartyRewards(PendingPluginMessageVotePartyRewards rewards) {
|
||||
if (rewards == null) throw new IllegalArgumentException("Missing plugin-message vote-party backlog");
|
||||
if (rewards.deliveries().isEmpty()) remove("VoteParty", "PluginMessageRewards");
|
||||
else set(new Object[] { "VoteParty", "PluginMessageRewards" }, rewards.toStorageValue());
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized Collection<String> getPendingVotePartyRewardServers() {
|
||||
Collection<String> encoded = getKeys(getNode("VoteParty", "PendingRewards"));
|
||||
Collection<String> servers = new ArrayList<>();
|
||||
if (encoded != null) for (String key : encoded) try {
|
||||
@@ -215,41 +338,41 @@ public class VelocityJsonVoteCache extends VelocityJSONFile implements IVoteCach
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<String> getPendingVotePartyRewardIds(String server) {
|
||||
public synchronized Collection<String> getPendingVotePartyRewardIds(String server) {
|
||||
return getKeys(getNode("VoteParty", "PendingRewards", encodeServerKey(server)));
|
||||
}
|
||||
|
||||
@Override
|
||||
public PendingVotePartyProxyEffects getPendingVotePartyProxyEffects() {
|
||||
public synchronized PendingVotePartyProxyEffects getPendingVotePartyProxyEffects() {
|
||||
return new PendingVotePartyProxyEffects(
|
||||
getString(getNode("VoteParty", "PendingProxyEffects", "Broadcast"), ""),
|
||||
getStringList(getNode("VoteParty", "PendingProxyEffects", "Commands"), java.util.List.of()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public PendingVotePartyProxyEffects getQuarantinedVotePartyProxyEffects() {
|
||||
public synchronized PendingVotePartyProxyEffects getQuarantinedVotePartyProxyEffects() {
|
||||
return new PendingVotePartyProxyEffects(
|
||||
getString(getNode("VoteParty", "QuarantinedProxyEffects", "Broadcast"), ""),
|
||||
getStringList(getNode("VoteParty", "QuarantinedProxyEffects", "Commands"), java.util.List.of()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getVotePartyCurrentVotes() {
|
||||
public synchronized int getVotePartyCurrentVotes() {
|
||||
return getInt(getNode("VoteParty", "CurrentVotes"), 0);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getVotePartyInreaseVotesRequired() {
|
||||
public synchronized int getVotePartyInreaseVotesRequired() {
|
||||
return getInt(getNode("VoteParty", "IncreaseVotes"), 0);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setVotePartyCache(String server, int amount) {
|
||||
public synchronized void setVotePartyCache(String server, int amount) {
|
||||
setPath(amount, "VoteParty", "Cache", server);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setPendingVotePartyReward(String server, String deliveryId, boolean pending) {
|
||||
public synchronized void setPendingVotePartyReward(String server, String deliveryId, boolean pending) {
|
||||
String serverKey = encodeServerKey(server);
|
||||
if (pending) setPath(true, "VoteParty", "PendingRewards", serverKey, deliveryId);
|
||||
else {
|
||||
@@ -260,7 +383,7 @@ public class VelocityJsonVoteCache extends VelocityJSONFile implements IVoteCach
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setPendingVotePartyProxyEffects(PendingVotePartyProxyEffects effects) {
|
||||
public synchronized void setPendingVotePartyProxyEffects(PendingVotePartyProxyEffects effects) {
|
||||
if (effects.isEmpty()) {
|
||||
remove("VoteParty", "PendingProxyEffects");
|
||||
return;
|
||||
@@ -270,7 +393,7 @@ public class VelocityJsonVoteCache extends VelocityJSONFile implements IVoteCach
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setQuarantinedVotePartyProxyEffects(PendingVotePartyProxyEffects effects) {
|
||||
public synchronized void setQuarantinedVotePartyProxyEffects(PendingVotePartyProxyEffects effects) {
|
||||
if (effects.isEmpty()) {
|
||||
remove("VoteParty", "QuarantinedProxyEffects");
|
||||
return;
|
||||
@@ -289,27 +412,27 @@ public class VelocityJsonVoteCache extends VelocityJSONFile implements IVoteCach
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setVotePartyCurrentVotes(int amount) {
|
||||
public synchronized void setVotePartyCurrentVotes(int amount) {
|
||||
setPath(amount, "VoteParty", "CurrentVotes");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setVotePartyInreaseVotesRequired(int amount) {
|
||||
public synchronized void setVotePartyInreaseVotesRequired(int amount) {
|
||||
setPath(amount, "VoteParty", "IncreaseVotes");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeOnlineVotes(String player) {
|
||||
public synchronized void removeOnlineVotes(String player) {
|
||||
remove("OnlineCache", player);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeServerVotes(String server) {
|
||||
public synchronized void removeServerVotes(String server) {
|
||||
remove("VoteCache", server);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeServerVote(String server, String uuid) {
|
||||
public synchronized void removeServerVote(String server, String uuid) {
|
||||
Collection<String> votes = getServerVotes(server);
|
||||
if (votes == null) {
|
||||
return;
|
||||
@@ -333,7 +456,7 @@ public class VelocityJsonVoteCache extends VelocityJSONFile implements IVoteCach
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeVote(String server, OfflineBungeeVote vote) {
|
||||
public synchronized void removeVote(String server, OfflineBungeeVote vote) {
|
||||
if (vote.getServerVoteCacheJsonKey() != null) {
|
||||
remove("VoteCache", server, vote.getServerVoteCacheJsonKey());
|
||||
return;
|
||||
@@ -373,7 +496,7 @@ public class VelocityJsonVoteCache extends VelocityJSONFile implements IVoteCach
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeOnlineVote(OfflineBungeeVote vote) {
|
||||
public synchronized void removeOnlineVote(OfflineBungeeVote vote) {
|
||||
if (vote.getOnlineVoteCacheJsonKey() != null && vote.getUuid() != null) {
|
||||
remove("OnlineCache", vote.getUuid(), vote.getOnlineVoteCacheJsonKey());
|
||||
return;
|
||||
|
||||
+15
-2
@@ -49,6 +49,7 @@ import com.bencodez.votingplugin.proxy.ProxyRuntimeReplacementLifecycle;
|
||||
import com.bencodez.votingplugin.proxy.VotingPluginProxyConfig;
|
||||
import com.bencodez.votingplugin.proxy.VotingPluginProxy.VoteRetryException;
|
||||
import com.bencodez.votingplugin.util.MinecraftUsernameValidator;
|
||||
import com.bencodez.votingplugin.util.ServiceSiteValidator;
|
||||
import com.bencodez.votingplugin.timequeue.VoteTimeQueue;
|
||||
import com.google.inject.Inject;
|
||||
import com.velocitypowered.api.command.CommandMeta;
|
||||
@@ -508,6 +509,18 @@ public class VotingPluginVelocity {
|
||||
}
|
||||
}
|
||||
|
||||
/** Captured ingress survives scheduler/reload/identity-resolution delays. */
|
||||
public IncomingVoteRuntimeResult processIncomingVote(String player, String service, UUID voteId, long occurredAt) {
|
||||
if (reloading) return IncomingVoteRuntimeResult.RETRY_AFTER_RELOAD;
|
||||
synchronized (reloadLock) {
|
||||
if (reloading) return IncomingVoteRuntimeResult.RETRY_AFTER_RELOAD;
|
||||
VotingPluginProxy runtime = votingPluginProxy;
|
||||
if (!runtimeOperational || runtime == null) return IncomingVoteRuntimeResult.RUNTIME_UNAVAILABLE;
|
||||
runtime.vote(player, service, true, false, 0, null, null, voteId, occurredAt);
|
||||
return IncomingVoteRuntimeResult.PROCESSED;
|
||||
}
|
||||
}
|
||||
|
||||
/** Owns a Votifier event before any fallible executor handoff. */
|
||||
public void acceptIncomingVote(String player, String service) {
|
||||
PendingIncomingVote pending = pendingIncomingVotes.admit(player, service);
|
||||
@@ -557,12 +570,12 @@ public class VotingPluginVelocity {
|
||||
try {
|
||||
IncomingVoteRuntimeResult result;
|
||||
synchronized (reloadLock) {
|
||||
result = processIncomingVote(pending.getPlayer(), pending.getService(), pending.getVoteId());
|
||||
result = processIncomingVote(pending.getPlayer(), pending.getService(), pending.getVoteId(), pending.getAcceptedAt());
|
||||
if (result == IncomingVoteRuntimeResult.PROCESSED) pendingIncomingVotes.complete(pending);
|
||||
}
|
||||
if (result == IncomingVoteRuntimeResult.PROCESSED) {
|
||||
logger.info("Vote received " + MinecraftUsernameValidator.sanitizeForLog(pending.getPlayer())
|
||||
+ " from service site " + MinecraftUsernameValidator.sanitizeForLog(pending.getService()));
|
||||
+ " from service site " + ServiceSiteValidator.sanitizeForLog(pending.getService()));
|
||||
return;
|
||||
}
|
||||
if (result == IncomingVoteRuntimeResult.RETRY_AFTER_RELOAD) {
|
||||
|
||||
+1
-2
@@ -123,8 +123,7 @@ public class ServiceSiteHandler {
|
||||
|
||||
public void saveToServerData() {
|
||||
List<String> out = toListFormat(sitesRef.get());
|
||||
plugin.getServerData().getData().set(SERVERDATA_PATH, out);
|
||||
plugin.getServerData().saveData();
|
||||
plugin.getServerData().setStringList(SERVERDATA_PATH, out);
|
||||
}
|
||||
|
||||
public void refreshFromWebOnce(boolean logMore) {
|
||||
|
||||
@@ -12,7 +12,6 @@ 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;
|
||||
@@ -25,14 +24,14 @@ public class SignHandler {
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
private String data;
|
||||
private volatile String data;
|
||||
|
||||
/** The lines. */
|
||||
private ArrayList<String> lines;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
private Location location;
|
||||
private volatile Location location;
|
||||
|
||||
private String playerName;
|
||||
|
||||
@@ -48,7 +47,7 @@ public class SignHandler {
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
private Location skullLocation;
|
||||
private volatile Location skullLocation;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@@ -56,6 +55,88 @@ 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.
|
||||
*
|
||||
@@ -81,19 +162,28 @@ public class SignHandler {
|
||||
}
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
private boolean checkSkull(Block block) {
|
||||
if (block.getState() instanceof Skull) {
|
||||
if (!playerName.equals("No Player")) {
|
||||
Skull skull = (Skull) block.getState();
|
||||
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")) {
|
||||
try {
|
||||
SkullMeta meta = (SkullMeta) plugin.getSkullCacheHandler().getSkull(uuid, playerName).getItemMeta();
|
||||
skull.setOwnerProfile(meta.getOwnerProfile());
|
||||
skull.update(true, false);
|
||||
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);
|
||||
} catch (Exception e) {
|
||||
plugin.debug("Failed to set skull for " + playerName);
|
||||
plugin.debug("Failed to set skull for " + name);
|
||||
plugin.debug(e);
|
||||
skull.setOwner(playerName);
|
||||
skull.update(true, false);
|
||||
if (!current(frame)) return true;
|
||||
if (skull.setOwner(name) && current(frame) && skull.update(true, false)) rememberSkull(frame, target);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -106,18 +196,24 @@ public class SignHandler {
|
||||
* Check skulls.
|
||||
*/
|
||||
public void checkSkulls() {
|
||||
if (noNameAvailable()) {
|
||||
return;
|
||||
}
|
||||
if (skullLocation != null) {
|
||||
checkSkull(skullLocation.getBlock());
|
||||
return;
|
||||
}
|
||||
Render rendered = currentRender();
|
||||
checkSkulls(rendered.name(), rendered.identity());
|
||||
}
|
||||
|
||||
Location loc = location;
|
||||
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 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);
|
||||
updateSkulls(loc1, loc2, frame);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -190,6 +286,12 @@ 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);
|
||||
}
|
||||
@@ -198,95 +300,131 @@ public class SignHandler {
|
||||
* Update lines.
|
||||
*/
|
||||
public void updateLines() {
|
||||
lines = new ArrayList<>();
|
||||
checkValidSign();
|
||||
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);
|
||||
|
||||
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());
|
||||
}
|
||||
|
||||
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);
|
||||
|
||||
}
|
||||
|
||||
Render rendered = renderLines();
|
||||
synchronized (this) { applyRender(rendered); }
|
||||
}
|
||||
|
||||
/**
|
||||
* Update sign.
|
||||
*
|
||||
* @param delay the delay
|
||||
*/
|
||||
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>();
|
||||
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);
|
||||
}
|
||||
|
||||
/** 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) {
|
||||
plugin.getBukkitScheduler().runTaskLater(plugin, new Runnable() {
|
||||
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());
|
||||
}
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
@Override
|
||||
public void run() {
|
||||
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 {
|
||||
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();
|
||||
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);
|
||||
}
|
||||
|
||||
} catch (Exception ex) {
|
||||
plugin.debug("Failed to update sign at " + getLocation().toString());
|
||||
VotingPluginMain.plugin.debug(ex);
|
||||
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());
|
||||
}
|
||||
}, delay, getLocation());
|
||||
} catch (Exception failure) {
|
||||
plugin.debug("Failed to update sign display");
|
||||
plugin.debug(failure);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -296,19 +434,38 @@ public class SignHandler {
|
||||
* @param loc2 the second location
|
||||
*/
|
||||
public void updateSkulls(Location loc1, Location loc2) {
|
||||
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;
|
||||
}
|
||||
Render rendered = currentRender();
|
||||
updateSkulls(loc1, loc2, rendered.name(), rendered.identity());
|
||||
}
|
||||
|
||||
}
|
||||
private void updateSkulls(Location loc1, Location loc2, String name, UUID identity) {
|
||||
updateSkulls(loc1, loc2, skullFrame(name, identity));
|
||||
}
|
||||
|
||||
for (Block block : MiscUtils.getInstance().getRegionBlocks(location.getWorld(), loc1, loc2)) {
|
||||
checkSkull(block);
|
||||
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();
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -64,6 +64,69 @@ 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.
|
||||
*/
|
||||
|
||||
+294
@@ -0,0 +1,294 @@
|
||||
package com.bencodez.votingplugin.specialrewards.datemilestones;
|
||||
|
||||
import com.bencodez.votingplugin.core.datemilestones.DateVoteEvent;
|
||||
import com.bencodez.votingplugin.util.DurableFiles;
|
||||
import java.io.IOException;
|
||||
import java.io.StringReader;
|
||||
import java.io.StringWriter;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.LinkOption;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.channels.FileChannel;
|
||||
import java.nio.channels.FileLock;
|
||||
import java.nio.channels.OverlappingFileLockException;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Properties;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
|
||||
/** Single local accounting owner. All entry points must run on a persistence worker. */
|
||||
public final class DateVoteLedger {
|
||||
public record Progress(int votes, Set<Integer> reservedAwards, Set<Integer> submittedAwards, Set<Integer> deferredAwards) { }
|
||||
private static final int MAX_RECORDS = 100_000;
|
||||
private final Path directory;
|
||||
private final int recordCapacity;
|
||||
public DateVoteLedger(Path directory) { this(directory, MAX_RECORDS); }
|
||||
// Smaller limits keep boundary regression fixtures bounded; production uses MAX_RECORDS.
|
||||
DateVoteLedger(Path directory, int recordCapacity) {
|
||||
if (recordCapacity < 1 || recordCapacity > MAX_RECORDS) throw new IllegalArgumentException("Invalid milestone record capacity");
|
||||
this.directory = directory.toAbsolutePath().normalize();
|
||||
this.recordCapacity = recordCapacity;
|
||||
}
|
||||
|
||||
public synchronized List<Integer> record(DateVoteEvent event, UUID player, UUID occurrence) throws IOException {
|
||||
return record(event, player, occurrence, true);
|
||||
}
|
||||
public synchronized List<Integer> record(DateVoteEvent event, UUID player, UUID occurrence, boolean processRewards) throws IOException {
|
||||
return withLedgerLock(() -> recordLocked(event, player, occurrence, processRewards));
|
||||
}
|
||||
private List<Integer> recordLocked(DateVoteEvent event, UUID player, UUID occurrence, boolean processRewards) throws IOException {
|
||||
seal(event);
|
||||
Path file = playerFile(event, player);
|
||||
Properties state = read(file);
|
||||
String fingerprint = state.getProperty("fingerprint");
|
||||
if (fingerprint != null && !fingerprint.equals(event.fingerprint())) throw new IOException("Event accounting changed; use a new event ID");
|
||||
validateFingerprint(event, state);
|
||||
Set<UUID> seen = occurrences(state);
|
||||
boolean changed = !seen.contains(occurrence);
|
||||
if (changed && (seen.size() >= 4096 || votes(state) >= 4096))
|
||||
throw new IOException("Event occurrence capacity reached (4096); progress retained");
|
||||
seen.add(occurrence);
|
||||
state.setProperty("fingerprint", event.fingerprint());
|
||||
state.setProperty("seen", String.join(",", seen.stream().map(UUID::toString).sorted().toList()));
|
||||
int votes = votes(state);
|
||||
List<Integer> awards = new ArrayList<>();
|
||||
for (int threshold : event.thresholds()) {
|
||||
String key = "award." + threshold;
|
||||
if (votes >= threshold && !state.containsKey(key)) {
|
||||
state.setProperty(key, "DEFERRED");
|
||||
changed = true;
|
||||
}
|
||||
if (processRewards && votes >= threshold && "DEFERRED".equals(state.getProperty(key))) awards.add(threshold);
|
||||
}
|
||||
// Persist counts and known unattempted awards; each submission claims only its own threshold.
|
||||
if (changed) write(file, state);
|
||||
return List.copyOf(awards);
|
||||
}
|
||||
/** Explicit administrative adjustment; retains receipt IDs and all prior reward fences. */
|
||||
public synchronized Progress setVotes(DateVoteEvent event, UUID player, int value) throws IOException {
|
||||
if (value < 0 || value > 4096) throw new IllegalArgumentException("Votes must be between 0 and 4096");
|
||||
return withLedgerLock(() -> {
|
||||
seal(event);
|
||||
Path file = playerFile(event, player);
|
||||
Properties state = read(file);
|
||||
validateFingerprint(event, state);
|
||||
state.setProperty("fingerprint", event.fingerprint());
|
||||
state.putIfAbsent("seen", "");
|
||||
state.setProperty("adjustment", Integer.toString(value - occurrences(state).size()));
|
||||
for (int threshold : event.thresholds()) if (value >= threshold)
|
||||
state.putIfAbsent("award." + threshold, "DEFERRED");
|
||||
write(file, state);
|
||||
return progressLocked(event, player);
|
||||
});
|
||||
}
|
||||
/** Force skips the count requirement; even an explicit repeat cannot erase an uncertain reservation. */
|
||||
public synchronized boolean reserveForced(DateVoteEvent event, UUID player, int threshold,
|
||||
boolean ignoreLimits) throws IOException {
|
||||
if (!event.thresholds().contains(threshold)) throw new IllegalArgumentException("Unknown milestone threshold");
|
||||
return withLedgerLock(() -> {
|
||||
seal(event);
|
||||
Path file = playerFile(event, player);
|
||||
Properties state = read(file);
|
||||
validateFingerprint(event, state);
|
||||
String previous = state.getProperty("award." + threshold);
|
||||
if ("RESERVED".equals(previous) || !ignoreLimits && "SUBMITTED".equals(previous)) return false;
|
||||
state.setProperty("fingerprint", event.fingerprint());
|
||||
state.putIfAbsent("seen", "");
|
||||
state.putIfAbsent("adjustment", "0");
|
||||
state.setProperty("award." + threshold, "RESERVED");
|
||||
write(file, state);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
/** Atomically admit one known unattempted threshold immediately before its external submission. */
|
||||
public synchronized boolean reserve(DateVoteEvent event, UUID player, int threshold) throws IOException {
|
||||
return withLedgerLock(() -> reserveLocked(event, player, threshold));
|
||||
}
|
||||
private boolean reserveLocked(DateVoteEvent event, UUID player, int threshold) throws IOException {
|
||||
Path file = playerFile(event, player);
|
||||
Properties state = read(file);
|
||||
validateFingerprint(event, state);
|
||||
if (!event.thresholds().contains(threshold) || votes(state) < threshold
|
||||
|| !"DEFERRED".equals(state.getProperty("award." + threshold))) return false;
|
||||
state.setProperty("award." + threshold, "RESERVED");
|
||||
write(file, state);
|
||||
return true;
|
||||
}
|
||||
public synchronized void submitted(DateVoteEvent event, UUID player, int threshold) throws IOException {
|
||||
withLedgerLock(() -> { submittedLocked(event, player, threshold); return null; });
|
||||
}
|
||||
private void submittedLocked(DateVoteEvent event, UUID player, int threshold) throws IOException {
|
||||
Path file = playerFile(event, player);
|
||||
Properties state = read(file);
|
||||
validateFingerprint(event, state);
|
||||
if (!"RESERVED".equals(state.getProperty("award." + threshold))) return;
|
||||
state.setProperty("award." + threshold, "SUBMITTED");
|
||||
write(file, state);
|
||||
}
|
||||
public synchronized Progress progress(DateVoteEvent event, UUID player) throws IOException {
|
||||
// An absent ledger is a valid empty snapshot. A read must not initialize
|
||||
// accounting storage, including for legacy votes with no event progress.
|
||||
// Unknown/unreadable paths still enter the checked ownership path.
|
||||
if (Files.notExists(directory, LinkOption.NOFOLLOW_LINKS))
|
||||
return new Progress(0, Set.of(), Set.of(), Set.of());
|
||||
return withLedgerLock(() -> progressLocked(event, player));
|
||||
}
|
||||
private Progress progressLocked(DateVoteEvent event, UUID player) throws IOException {
|
||||
Properties definitions = readSealedDefinitions(event);
|
||||
String sealed = definitions.getProperty(event.id());
|
||||
if (sealed != null && !sealed.equals(event.fingerprint())) throw new IOException("Event accounting changed; use a new ID");
|
||||
Properties state = read(playerFile(event, player));
|
||||
validateFingerprint(event, state);
|
||||
Set<Integer> reserved = new HashSet<>(), submitted = new HashSet<>(), deferred = new HashSet<>();
|
||||
for (String key : state.stringPropertyNames()) {
|
||||
if (key.startsWith("award.")) {
|
||||
int threshold;
|
||||
try { threshold = Integer.parseInt(key.substring(6)); }
|
||||
catch (NumberFormatException invalid) { throw new IOException("Invalid award state", invalid); }
|
||||
if ("RESERVED".equals(state.getProperty(key))) reserved.add(threshold);
|
||||
else if ("SUBMITTED".equals(state.getProperty(key))) submitted.add(threshold);
|
||||
else if ("DEFERRED".equals(state.getProperty(key))) deferred.add(threshold);
|
||||
else throw new IOException("Unknown award state");
|
||||
}
|
||||
}
|
||||
return new Progress(votes(state), Set.copyOf(reserved), Set.copyOf(submitted), Set.copyOf(deferred));
|
||||
}
|
||||
@FunctionalInterface
|
||||
private interface LedgerAction<T> { T run() throws IOException; }
|
||||
private <T> T withLedgerLock(LedgerAction<T> action) throws IOException {
|
||||
if (Files.isSymbolicLink(directory)) throw new IOException("Unsafe milestone directory");
|
||||
Files.createDirectories(directory);
|
||||
if (Files.isSymbolicLink(directory)) throw new IOException("Unsafe milestone directory");
|
||||
// Interning shares this monitor across plugin classloaders without retaining a static registry.
|
||||
// On Unix, closing any descriptor for a file can release another channel's process-owned lock.
|
||||
String monitor = ("com.bencodez.votingplugin.DateVoteLedger:" + directory.toRealPath()).intern();
|
||||
if (Thread.holdsLock(monitor)) throw new IOException("Date milestone ledger is busy");
|
||||
synchronized (monitor) {
|
||||
Path lockPath = directory.resolve(".ledger.lock");
|
||||
if (Files.isSymbolicLink(lockPath) || (Files.exists(lockPath, LinkOption.NOFOLLOW_LINKS)
|
||||
&& !Files.isRegularFile(lockPath, LinkOption.NOFOLLOW_LINKS)))
|
||||
throw new IOException("Unsafe milestone lock path");
|
||||
try (FileChannel channel = FileChannel.open(lockPath, StandardOpenOption.CREATE, StandardOpenOption.WRITE,
|
||||
LinkOption.NOFOLLOW_LINKS)) {
|
||||
FileLock lock;
|
||||
try { lock = channel.tryLock(); }
|
||||
catch (OverlappingFileLockException busy) { throw new IOException("Date milestone ledger is busy", busy); }
|
||||
if (lock == null) throw new IOException("Date milestone ledger is busy");
|
||||
try (lock) { return action.run(); }
|
||||
}
|
||||
}
|
||||
}
|
||||
private void validateFingerprint(DateVoteEvent event, Properties state) throws IOException {
|
||||
if (state.isEmpty()) return;
|
||||
if (!event.fingerprint().equals(state.getProperty("fingerprint")))
|
||||
throw new IOException("Event accounting changed or state invalid; use a new ID");
|
||||
int votes = votes(state);
|
||||
for (int threshold : event.thresholds()) if (votes >= threshold && !state.containsKey("award." + threshold))
|
||||
throw new IOException("Missing reached milestone award state; progress retained for review");
|
||||
for (String key : state.stringPropertyNames()) if (key.startsWith("award.")
|
||||
&& !event.thresholds().contains(Integer.parseInt(key.substring(6))))
|
||||
throw new IOException("Award is outside configured milestone contract");
|
||||
}
|
||||
private void seal(DateVoteEvent event) throws IOException {
|
||||
Properties definitions = readSealedDefinitions(event);
|
||||
String old = definitions.getProperty(event.id());
|
||||
if (old != null && !old.equals(event.fingerprint())) throw new IOException("DateVoteMilestones event " + event.id() + " changed accounting; use a new ID");
|
||||
if (old == null) {
|
||||
if (definitions.size() >= 1024) throw new IOException("Event definition capacity reached");
|
||||
definitions.setProperty(event.id(), event.fingerprint());
|
||||
write(directory.resolve("definitions.properties"), definitions);
|
||||
}
|
||||
}
|
||||
/** Missing metadata cannot turn surviving player history into a fresh event. */
|
||||
private Properties readSealedDefinitions(DateVoteEvent event) throws IOException {
|
||||
if (Files.isSymbolicLink(directory)) throw new IOException("Unsafe milestone directory");
|
||||
Properties definitions = read(directory.resolve("definitions.properties"));
|
||||
if (!definitions.containsKey(event.id()) && Files.exists(directory, LinkOption.NOFOLLOW_LINKS)) {
|
||||
// Bounded accounting directory; this lookup is exclusively on the I/O owner.
|
||||
try (var history = Files.newDirectoryStream(directory, event.fileId() + "-*.properties")) {
|
||||
if (history.iterator().hasNext())
|
||||
throw new IOException("Missing historical event seal; preserve state and repair metadata before accounting");
|
||||
}
|
||||
}
|
||||
return definitions;
|
||||
}
|
||||
private Path playerFile(DateVoteEvent event, UUID player) {
|
||||
return directory.resolve(event.fileId() + "-" + player + ".properties");
|
||||
}
|
||||
private Set<UUID> occurrences(Properties state) throws IOException {
|
||||
Set<UUID> ids = new HashSet<>();
|
||||
String raw = state.getProperty("seen", "");
|
||||
if (!raw.isEmpty()) for (String id : raw.split(",", -1)) {
|
||||
try { if (!ids.add(UUID.fromString(id))) throw new IOException("Duplicate stored occurrence"); }
|
||||
catch (IllegalArgumentException invalid) { throw new IOException("Invalid stored occurrence", invalid); }
|
||||
if (ids.size() > 4096) throw new IOException("Oversized event state");
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
private int votes(Properties state) throws IOException {
|
||||
String adjustment = state.getProperty("adjustment", "0");
|
||||
if (!adjustment.matches("-?(0|[1-9][0-9]{0,3})")) throw new IOException("Invalid progress adjustment");
|
||||
int offset = Integer.parseInt(adjustment);
|
||||
int result = occurrences(state).size() + offset;
|
||||
if (offset < -4096 || offset > 4096 || result < 0 || result > 4096)
|
||||
throw new IOException("Invalid adjusted progress");
|
||||
return result;
|
||||
}
|
||||
private Properties read(Path file) throws IOException {
|
||||
Properties state = new Properties() {
|
||||
@Override public synchronized Object put(Object key, Object value) {
|
||||
if (containsKey(key)) throw new IllegalArgumentException("Duplicate stored field");
|
||||
return super.put(key, value);
|
||||
}
|
||||
};
|
||||
if (Files.notExists(file, LinkOption.NOFOLLOW_LINKS)) return new Properties();
|
||||
if (Files.isSymbolicLink(directory)) throw new IOException("Unsafe milestone directory");
|
||||
if (Files.isSymbolicLink(file) || !Files.isRegularFile(file, LinkOption.NOFOLLOW_LINKS) || Files.size(file) > 256 * 1024)
|
||||
throw new IOException("Unsafe/oversized date milestone state");
|
||||
try { state.load(new StringReader(Files.readString(file))); }
|
||||
catch (IllegalArgumentException invalid) { throw new IOException("Malformed milestone state", invalid); }
|
||||
if (file.getFileName().toString().equals("definitions.properties")) {
|
||||
if (state.isEmpty() || state.size() > 1024) throw new IOException("Empty/oversized definitions; existing seals must not be reset");
|
||||
for (String key : state.stringPropertyNames()) if (!key.matches("[A-Za-z0-9_-]{1,64}")
|
||||
|| !state.getProperty(key).matches("[a-f0-9]{64}")) throw new IOException("Invalid definition state");
|
||||
} else {
|
||||
if (!state.containsKey("fingerprint") || !state.getProperty("fingerprint").matches("[a-f0-9]{64}")
|
||||
|| !state.containsKey("seen") || state.size() > 67) throw new IOException("Incomplete milestone state");
|
||||
Set<UUID> seen = occurrences(state);
|
||||
votes(state);
|
||||
for (String key : state.stringPropertyNames()) if (!key.equals("fingerprint") && !key.equals("seen")
|
||||
&& !key.equals("adjustment")) {
|
||||
if (!key.matches("award\\.[1-9][0-9]{0,3}")) throw new IOException("Unknown milestone state field");
|
||||
int threshold = Integer.parseInt(key.substring(6));
|
||||
if (threshold > 4096 || threshold > seen.size() && !state.containsKey("adjustment")
|
||||
|| !(state.getProperty(key).equals("RESERVED") || state.getProperty(key).equals("SUBMITTED") || state.getProperty(key).equals("DEFERRED")))
|
||||
throw new IOException("Invalid award state");
|
||||
}
|
||||
}
|
||||
Properties mutable = new Properties(); mutable.putAll(state);
|
||||
return mutable;
|
||||
}
|
||||
protected void write(Path file, Properties state) throws IOException {
|
||||
if (Files.isSymbolicLink(directory)) throw new IOException("Unsafe milestone directory");
|
||||
Files.createDirectories(directory);
|
||||
if (Files.isSymbolicLink(directory) || Files.isSymbolicLink(file)) throw new IOException("Unsafe milestone state path");
|
||||
boolean newRecord = !file.getFileName().toString().equals("definitions.properties") && Files.notExists(file, LinkOption.NOFOLLOW_LINKS);
|
||||
if (newRecord) {
|
||||
int recordCount = 0;
|
||||
try (var files = Files.newDirectoryStream(directory, "*.properties")) {
|
||||
for (Path existing : files) if (!existing.getFileName().toString().equals("definitions.properties")) {
|
||||
if (++recordCount >= recordCapacity) throw new IOException("Milestone record capacity reached; existing progress retained");
|
||||
}
|
||||
}
|
||||
}
|
||||
StringWriter writer = new StringWriter(); state.store(writer, "DateVoteMilestones v1");
|
||||
String text = writer.toString();
|
||||
if (text.length() > 256 * 1024) throw new IOException("Oversized milestone state");
|
||||
Path staged = Files.createTempFile(directory, "milestone-", ".tmp");
|
||||
try { Files.writeString(staged, text); DurableFiles.publishStagedFile(staged, file); }
|
||||
finally { Files.deleteIfExists(staged); }
|
||||
}
|
||||
}
|
||||
+94
@@ -0,0 +1,94 @@
|
||||
package com.bencodez.votingplugin.specialrewards.datemilestones;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.TreeSet;
|
||||
import java.util.regex.Pattern;
|
||||
import org.bukkit.configuration.ConfigurationSection;
|
||||
|
||||
/** Bounded owner configuration; persistent award identities remain the numeric thresholds. */
|
||||
final class DateVoteMilestoneConfig {
|
||||
record Reward(String key, boolean enabled) { }
|
||||
private static final Pattern RANGE = Pattern.compile("(\\d+)\\s*\\.\\.\\s*(\\d+)(?:\\s+step\\s+(\\d+))?");
|
||||
private DateVoteMilestoneConfig() { }
|
||||
|
||||
static Map<Integer, Reward> read(ConfigurationSection event) {
|
||||
var section = event.getConfigurationSection("Milestones");
|
||||
if (section == null || section.getKeys(false).isEmpty() || section.getKeys(false).size() > 64)
|
||||
throw new IllegalArgumentException("Milestones requires 1–64 entries");
|
||||
Map<Integer, Reward> result = new LinkedHashMap<>();
|
||||
for (String key : section.getKeys(false)) {
|
||||
var milestone = section.getConfigurationSection(key);
|
||||
for (var entry : entry(key, milestone).entrySet()) {
|
||||
if (result.putIfAbsent(entry.getKey(), entry.getValue()) != null)
|
||||
throw new IllegalArgumentException("Milestone thresholds must not overlap between entries");
|
||||
if (result.size() > 64) throw new IllegalArgumentException("At most 64 thresholds per event");
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
static Map<Integer, Reward> entry(String key, ConfigurationSection section) {
|
||||
if (!key.matches("[A-Za-z0-9_-]{1,64}") || section == null
|
||||
|| section.getConfigurationSection("Rewards") == null)
|
||||
throw new IllegalArgumentException("Each milestone requires an ID and Rewards section");
|
||||
if (section.contains("Enabled") && !(section.get("Enabled") instanceof Boolean))
|
||||
throw new IllegalArgumentException("Milestone Enabled must be a boolean");
|
||||
for (String unsupported : List.of("Total", "Group", "Limit")) {
|
||||
if (section.contains(unsupported))
|
||||
throw new IllegalArgumentException(unsupported + " is not supported for date milestones");
|
||||
}
|
||||
TreeSet<Integer> thresholds = new TreeSet<>();
|
||||
if (!section.contains("At") && !section.contains("Every")) {
|
||||
int value = integer(key, false);
|
||||
if (!key.equals(Integer.toString(value))) throw new IllegalArgumentException("Legacy threshold must be canonical");
|
||||
thresholds.add(value);
|
||||
} else {
|
||||
if (section.contains("At")) {
|
||||
Object raw = section.get("At");
|
||||
List<?> values = raw instanceof List<?> list ? list : java.util.Collections.singletonList(raw);
|
||||
if (values.isEmpty() || values.size() > 64) throw new IllegalArgumentException("At requires 1–64 values");
|
||||
for (Object value : values) addAt(thresholds, value);
|
||||
}
|
||||
if (section.contains("Every")) {
|
||||
int every = integer(section.get("Every"), false);
|
||||
for (int value = every; value <= 4096; value += every) add(thresholds, value);
|
||||
}
|
||||
}
|
||||
Map<Integer, Reward> result = new LinkedHashMap<>();
|
||||
for (int value : thresholds) result.put(value, new Reward(key, section.getBoolean("Enabled", true)));
|
||||
return result;
|
||||
}
|
||||
|
||||
private static void addAt(TreeSet<Integer> values, Object raw) {
|
||||
if (raw instanceof String text) {
|
||||
var range = RANGE.matcher(text.trim());
|
||||
if (range.matches()) {
|
||||
int start = integer(range.group(1), true), end = integer(range.group(2), true);
|
||||
int step = range.group(3) == null ? 1 : integer(range.group(3), false);
|
||||
int first = Math.min(start, end), last = Math.max(start, end);
|
||||
for (int value = first; value <= last; value += step) add(values, value == 0 ? 1 : value);
|
||||
return;
|
||||
}
|
||||
}
|
||||
int value = integer(raw, true);
|
||||
add(values, value == 0 ? 1 : value);
|
||||
}
|
||||
|
||||
private static void add(TreeSet<Integer> values, int value) {
|
||||
values.add(value);
|
||||
if (values.size() > 64) throw new IllegalArgumentException("At most 64 thresholds per event");
|
||||
}
|
||||
|
||||
private static int integer(Object raw, boolean zero) {
|
||||
// Avoid Number.intValue truncation and YAML's boolean/string-list coercions.
|
||||
if (!(raw instanceof Byte || raw instanceof Short || raw instanceof Integer || raw instanceof Long || raw instanceof String))
|
||||
throw new IllegalArgumentException("Threshold must be an integer");
|
||||
String text = raw.toString().trim();
|
||||
if (!text.matches("\\d{1,4}")) throw new IllegalArgumentException("Threshold must be an integer from 1 to 4096");
|
||||
int value = Integer.parseInt(text);
|
||||
if (value < (zero ? 0 : 1) || value > 4096) throw new IllegalArgumentException("Threshold out of range");
|
||||
return value;
|
||||
}
|
||||
}
|
||||
+548
@@ -0,0 +1,548 @@
|
||||
package com.bencodez.votingplugin.specialrewards.datemilestones;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.RejectedExecutionException;
|
||||
import org.bukkit.configuration.ConfigurationSection;
|
||||
import org.bukkit.configuration.file.YamlConfiguration;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import com.bencodez.advancedcore.api.rewards.RewardOptions;
|
||||
import com.bencodez.votingplugin.VotingPluginMain;
|
||||
import com.bencodez.votingplugin.core.datemilestones.DateVoteEvent;
|
||||
import com.bencodez.votingplugin.core.datemilestones.DateVoteProgressSnapshot;
|
||||
import com.bencodez.advancedcore.api.rewards.DirectlyDefinedReward;
|
||||
import com.bencodez.votingplugin.user.VotingPluginUser;
|
||||
import com.bencodez.votingplugin.util.BukkitCompletionScheduler;
|
||||
|
||||
/** Owner-defined windows, independently accounted on one backend using original occurrence IDs. */
|
||||
public final class DateVoteMilestones {
|
||||
private record Definition(DateVoteEvent event, YamlConfiguration rewards, java.util.Set<Integer> enabledThresholds,
|
||||
java.util.Map<Integer, DateVoteMilestoneConfig.Reward> milestones, boolean countFakeVotes) { }
|
||||
private final VotingPluginMain plugin;
|
||||
private volatile List<Definition> definitions = List.of();
|
||||
private final java.util.Set<UUID> pendingProgress = new java.util.HashSet<>();
|
||||
private final java.util.concurrent.atomic.AtomicInteger deferredAccounting = new java.util.concurrent.atomic.AtomicInteger();
|
||||
private final java.util.concurrent.atomic.AtomicInteger pendingAdministration = new java.util.concurrent.atomic.AtomicInteger();
|
||||
private record PlaceholderIdentity(UUID player, boolean resolveName) { }
|
||||
private final java.util.Map<PlaceholderIdentity, CachedProgress> placeholderCache = new java.util.LinkedHashMap<>(256, 0.75f, true);
|
||||
private static final class ProgressRequest {
|
||||
boolean invalidated;
|
||||
UUID resolvedStorageId;
|
||||
}
|
||||
private final java.util.Map<PlaceholderIdentity, ProgressRequest> placeholderRequests = new java.util.HashMap<>();
|
||||
private record CachedProgress(Object generation, long expires, UUID storageId, java.util.Map<String, DateVoteLedger.Progress> events) { }
|
||||
private volatile Object generation = new Object();
|
||||
private DateVoteLedger ledger;
|
||||
public DateVoteMilestones(VotingPluginMain plugin) { this.plugin = plugin; }
|
||||
private synchronized DateVoteLedger ledger() {
|
||||
if (ledger == null) ledger = new DateVoteLedger(plugin.getDataFolder().toPath().resolve("date-vote-milestones"));
|
||||
return ledger;
|
||||
}
|
||||
/** Configuration is already loaded; this method performs no disk access. */
|
||||
public void reload() {
|
||||
generation = null;
|
||||
synchronized (placeholderCache) {
|
||||
placeholderCache.clear();
|
||||
// Queued/running refreshes still own their admission until their existing finally/rejection path releases it.
|
||||
placeholderRequests.values().forEach(request -> request.invalidated = true);
|
||||
}
|
||||
List<Definition> loaded = new ArrayList<>();
|
||||
YamlConfiguration rewards = new YamlConfiguration();
|
||||
var root = plugin.getSpecialRewardsConfig().getData().getConfigurationSection("DateVoteMilestones");
|
||||
if (root != null && !root.getKeys(false).isEmpty()) {
|
||||
try { rewards.loadFromString(plugin.getSpecialRewardsConfig().getData().saveToString()); }
|
||||
catch (org.bukkit.configuration.InvalidConfigurationException invalid) {
|
||||
definitions = List.of(); generation = new Object();
|
||||
plugin.getLogger().warning("DateVoteMilestones configuration snapshot invalid"); return;
|
||||
}
|
||||
}
|
||||
int considered = 0;
|
||||
if (root != null) for (String id : root.getKeys(false)) {
|
||||
if (++considered > 64) { plugin.getLogger().warning("DateVoteMilestones supports at most 64 configured events"); break; }
|
||||
try {
|
||||
ConfigurationSection section = root.getConfigurationSection(id);
|
||||
if (section == null) throw new IllegalArgumentException("Expected an event section");
|
||||
registerRewardHandles(id, section, rewards);
|
||||
DateVoteEvent event = parse(id, section);
|
||||
if (plugin.getBungeeSettings().isUseBungeecoord() && event.accountingServer().isBlank())
|
||||
throw new IllegalArgumentException("Proxy events require one explicit AccountingServer and all-server identified delivery");
|
||||
var configured = DateVoteMilestoneConfig.read(section);
|
||||
var enabledThresholds = configured.entrySet().stream().filter(entry -> entry.getValue().enabled())
|
||||
.map(java.util.Map.Entry::getKey).collect(java.util.stream.Collectors.toUnmodifiableSet());
|
||||
loaded.add(new Definition(event, rewards, enabledThresholds, java.util.Map.copyOf(configured),
|
||||
section.getBoolean("CountFakeVotes", true)));
|
||||
} catch (Exception invalid) {
|
||||
plugin.getLogger().warning("DateVoteMilestones " + id + " disabled: " + invalid.getMessage());
|
||||
}
|
||||
}
|
||||
definitions = List.copyOf(loaded);
|
||||
generation = new Object();
|
||||
}
|
||||
/** Queued rewards must resolve even when an accounting-only setting is invalid. */
|
||||
private void registerRewardHandles(String id, ConfigurationSection section, YamlConfiguration rewards) {
|
||||
String fileId = DateVoteEvent.fileId(id);
|
||||
var milestones = section.getConfigurationSection("Milestones");
|
||||
if (milestones == null) return;
|
||||
java.util.Map<Integer, DateVoteMilestoneConfig.Reward> configuredRewards = new java.util.LinkedHashMap<>();
|
||||
java.util.Set<Integer> ambiguous = new java.util.HashSet<>();
|
||||
int count = 0;
|
||||
for (String key : milestones.getKeys(false)) {
|
||||
if (++count > 64) break;
|
||||
try {
|
||||
for (var entry : DateVoteMilestoneConfig.entry(key, milestones.getConfigurationSection(key)).entrySet()) {
|
||||
if (configuredRewards.size() >= 64 && !configuredRewards.containsKey(entry.getKey())) continue;
|
||||
if (configuredRewards.putIfAbsent(entry.getKey(), entry.getValue()) != null) ambiguous.add(entry.getKey());
|
||||
}
|
||||
} catch (IllegalArgumentException invalid) { /* Keep independent valid queued reward handles. */ }
|
||||
}
|
||||
for (var entry : configuredRewards.entrySet()) {
|
||||
int threshold = entry.getKey();
|
||||
if (ambiguous.contains(threshold)) continue;
|
||||
String source = "DateVoteMilestones." + id + ".Milestones." + entry.getValue().key() + ".Rewards";
|
||||
var configured = rewards.getConfigurationSection(source);
|
||||
if (configured == null) continue;
|
||||
String alias = "DateVoteMilestonesRuntime." + fileId + ".Milestones." + threshold + ".Rewards";
|
||||
rewards.createSection(alias, configured.getValues(true));
|
||||
plugin.addDirectlyDefinedRewards(new DirectlyDefinedReward(alias) {
|
||||
private String sourcePath(String requested) {
|
||||
if (!requested.equals(alias) && !requested.startsWith(alias + "."))
|
||||
throw new IllegalArgumentException("Unexpected date milestone reward path");
|
||||
String current = currentRewardSource(plugin.getSpecialRewardsConfig().getData(), id, threshold);
|
||||
if (current == null) throw new IllegalStateException("Date milestone reward definition is unavailable");
|
||||
return current + requested.substring(alias.length());
|
||||
}
|
||||
@Override public ConfigurationSection getFileData() {
|
||||
YamlConfiguration data = new YamlConfiguration();
|
||||
var live = plugin.getSpecialRewardsConfig().getData();
|
||||
String currentSource = currentRewardSource(live, id, threshold);
|
||||
var current = currentSource == null ? null
|
||||
: live.getConfigurationSection(currentSource);
|
||||
if (current != null) data.createSection(alias, current.getValues(true));
|
||||
return data;
|
||||
}
|
||||
@Override public void createSection(String path) { plugin.getSpecialRewardsConfig().createSection(sourcePath(path)); }
|
||||
@Override public void setData(String path, Object value) { plugin.getSpecialRewardsConfig().setValue(sourcePath(path), value); }
|
||||
@Override public void save() { plugin.getSpecialRewardsConfig().saveData(); }
|
||||
});
|
||||
}
|
||||
}
|
||||
/** Old registry handles can outlive YAML replacement during reload; resolve by stable threshold. */
|
||||
private static String currentRewardSource(ConfigurationSection live, String id, int threshold) {
|
||||
var milestones = live.getConfigurationSection("DateVoteMilestones." + id + ".Milestones");
|
||||
if (milestones == null) return null;
|
||||
String found = null;
|
||||
int count = 0;
|
||||
for (String key : milestones.getKeys(false)) {
|
||||
if (++count > 64) break;
|
||||
try {
|
||||
if (!DateVoteMilestoneConfig.entry(key, milestones.getConfigurationSection(key)).containsKey(threshold)) continue;
|
||||
if (found != null) return null;
|
||||
found = "DateVoteMilestones." + id + ".Milestones." + key + ".Rewards";
|
||||
} catch (IllegalArgumentException invalid) { /* An unrelated invalid entry does not hide queued rewards. */ }
|
||||
}
|
||||
return found;
|
||||
}
|
||||
public static DateVoteEvent parse(String id, ConfigurationSection section) {
|
||||
if (section.contains("CountFakeVotes") && !section.isBoolean("CountFakeVotes"))
|
||||
throw new IllegalArgumentException("CountFakeVotes must be a boolean");
|
||||
String zone = section.getString("Timezone");
|
||||
String start = section.getString("Start"), end = section.getString("End");
|
||||
var milestones = section.getConfigurationSection("Milestones");
|
||||
if (zone == null || start == null || end == null || milestones == null)
|
||||
throw new IllegalArgumentException("Start, End, Timezone and Milestones are required");
|
||||
List<Integer> thresholds = new ArrayList<>(DateVoteMilestoneConfig.read(section).keySet());
|
||||
Object rawSites = section.get("VoteSites");
|
||||
if (rawSites != null && (!(rawSites instanceof List<?> sites)
|
||||
|| sites.stream().anyMatch(site -> !(site instanceof String))))
|
||||
throw new IllegalArgumentException("VoteSites must be a list of configured site keys");
|
||||
return new DateVoteEvent(id, section.getString("DisplayName", id), section.getBoolean("Enabled", false),
|
||||
DateVoteEvent.timestamp(start, zone), DateVoteEvent.timestamp(end, zone), zone, thresholds,
|
||||
new java.util.HashSet<>(section.getStringList("VoteSites")), section.getString("AccountingServer", ""));
|
||||
}
|
||||
static String path(DateVoteEvent event, int threshold) {
|
||||
return "DateVoteMilestonesRuntime." + event.fileId() + ".Milestones." + threshold + ".Rewards";
|
||||
}
|
||||
/** Owner-thread extension events use the existing ordered storage worker without waiting on gameplay. */
|
||||
public boolean deferAccepted(VotingPluginUser user, String site, UUID occurrence, long occurredAt,
|
||||
boolean real, boolean proxy, boolean canonicalProxy, boolean targeted, boolean forceProxyRouting) {
|
||||
if (plugin.getBungeeSettings().isUseBungeecoord() && !proxy) return true;
|
||||
if (occurrence == null || occurredAt <= 0 || proxy && (!canonicalProxy || targeted)) return true;
|
||||
List<Definition> snapshot = definitions;
|
||||
if (snapshot.stream().noneMatch(definition -> definition.event().matches(occurredAt, site,
|
||||
real || definition.countFakeVotes(), proxy,
|
||||
plugin.getBungeeSettings().getServer()))) return true;
|
||||
int pending;
|
||||
do {
|
||||
pending = deferredAccounting.get();
|
||||
if (pending >= 64) {
|
||||
plugin.getLogger().warning("DateVoteMilestones deferred accounting is busy; occurrence remains unconfirmed.");
|
||||
return false;
|
||||
}
|
||||
} while (!deferredAccounting.compareAndSet(pending, pending + 1));
|
||||
try {
|
||||
plugin.getUserManager().getDataManager().getTimer().execute(() -> {
|
||||
try {
|
||||
if (!plugin.isEnabled() || snapshot != definitions) return;
|
||||
accepted(user, site, occurrence, occurredAt, real, proxy, canonicalProxy, targeted, forceProxyRouting);
|
||||
} finally { deferredAccounting.decrementAndGet(); }
|
||||
});
|
||||
} catch (RejectedExecutionException rejected) {
|
||||
deferredAccounting.decrementAndGet();
|
||||
plugin.getLogger().warning("DateVoteMilestones deferred accounting was rejected; occurrence remains unconfirmed.");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
/** Called only from the asynchronous accepted-vote pipeline; never from navigation. */
|
||||
public boolean accepted(VotingPluginUser user, String site, UUID occurrence, long occurredAt,
|
||||
boolean real, boolean proxy, boolean canonicalProxy, boolean targeted, boolean forceProxyRouting) {
|
||||
if (plugin.getBungeeSettings().isUseBungeecoord() && !proxy) return true;
|
||||
if (occurrence == null || occurredAt <= 0 || proxy && (!canonicalProxy || targeted)) return true;
|
||||
boolean recorded = true;
|
||||
for (Definition definition : definitions) {
|
||||
DateVoteEvent event = definition.event();
|
||||
if (!event.matches(occurredAt, site, real || definition.countFakeVotes(), proxy,
|
||||
plugin.getBungeeSettings().getServer())) continue;
|
||||
List<Integer> reached;
|
||||
try {
|
||||
reached = ledger().record(event, user.getJavaUUID(), occurrence, plugin.getOptions().isProcessRewards());
|
||||
invalidateProgress(user.getJavaUUID());
|
||||
} catch (IOException | RuntimeException failure) {
|
||||
recorded = false;
|
||||
plugin.getLogger().warning("DateVoteMilestones " + event.id() + " occurrence was not confirmed; proxy delivery must remain quarantined for accounting reconciliation: " + failure.getMessage());
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
for (int threshold : reached) {
|
||||
if (!plugin.getOptions().isProcessRewards()) break;
|
||||
if (!definition.enabledThresholds().contains(threshold)) continue;
|
||||
var placeholders = new HashMap<String, String>();
|
||||
placeholders.put("DateVoteEvent", event.displayName());
|
||||
placeholders.put("DateVoteThreshold", Integer.toString(threshold));
|
||||
if (!ledger().reserve(event, user.getJavaUUID(), threshold)) continue;
|
||||
plugin.getRewardHandler().giveReward(user, definition.rewards(), path(event, threshold),
|
||||
new RewardOptions().setPrefix("DateVoteMilestones-" + event.id() + "-" + threshold)
|
||||
.setServer(forceProxyRouting).setPlaceholders(placeholders));
|
||||
// Submission is not a transactional guarantee of arbitrary command execution.
|
||||
ledger().submitted(event, user.getJavaUUID(), threshold);
|
||||
}
|
||||
} catch (IOException | RuntimeException failure) {
|
||||
plugin.getLogger().warning("DateVoteMilestones " + event.id() + " accounting/reward submission failed; progress retained for review: " + failure.getMessage());
|
||||
}
|
||||
}
|
||||
return recorded;
|
||||
}
|
||||
public enum AdminAction { Status, Preview, SetVotes, Force, ForceNoLimits }
|
||||
|
||||
/** Admission is not success: all identity/storage/reward work runs on the ordered worker. */
|
||||
public void administer(CommandSender sender, AdminAction action, String player, String eventId, String argument) {
|
||||
Object epoch = generation;
|
||||
dispatchAdmin(sender, action, () -> {
|
||||
if (!current(epoch) || !adminAllowed(sender, action)) return;
|
||||
if (!validPlayer(player) || eventId == null || !eventId.matches("[A-Za-z0-9_-]{1,64}")) {
|
||||
sender.sendMessage("Invalid exact player or event ID."); return;
|
||||
}
|
||||
int count;
|
||||
do { count = pendingAdministration.get();
|
||||
if (count >= 64) { sender.sendMessage("Date milestone administration is busy. Try again shortly."); return; }
|
||||
} while (!pendingAdministration.compareAndSet(count, count + 1));
|
||||
try {
|
||||
plugin.getUserManager().getDataManager().getTimer().execute(() -> {
|
||||
try {
|
||||
if (!current(epoch)) return;
|
||||
List<String> result = administerOnWorker(action, player, eventId, argument, epoch);
|
||||
dispatchAdmin(sender, action, () -> {
|
||||
if (current(epoch) && adminAllowed(sender, action)) result.forEach(sender::sendMessage);
|
||||
});
|
||||
} catch (IOException | RuntimeException failure) {
|
||||
dispatchAdmin(sender, action, () -> {
|
||||
if (current(epoch) && adminAllowed(sender, action))
|
||||
sender.sendMessage("Date milestone operation failed; inspect retained progress before retrying rewards.");
|
||||
});
|
||||
} finally { pendingAdministration.decrementAndGet(); }
|
||||
});
|
||||
} catch (RejectedExecutionException unavailable) {
|
||||
pendingAdministration.decrementAndGet();
|
||||
sender.sendMessage("Date milestone storage is unavailable; nothing was submitted.");
|
||||
}
|
||||
});
|
||||
}
|
||||
private boolean current(Object epoch) {
|
||||
return epoch != null && epoch == generation && plugin.isEnabled() && plugin.getDateVoteMilestones() == this;
|
||||
}
|
||||
private static boolean validPlayer(String player) {
|
||||
return player != null && (player.matches("[A-Za-z0-9_]{1,16}")
|
||||
|| player.matches("[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}"));
|
||||
}
|
||||
private boolean adminAllowed(CommandSender sender, AdminAction action) {
|
||||
return (!(sender instanceof Player p) || p.isOnline()) && (sender.hasPermission("VotingPlugin.Admin")
|
||||
|| sender.hasPermission("VotingPlugin.Commands.AdminVote.DateVoteMilestone." + action.name()));
|
||||
}
|
||||
private void dispatchAdmin(CommandSender sender, AdminAction action, Runnable effect) {
|
||||
Player player = sender instanceof Player p ? p : null;
|
||||
Runnable checked = () -> { if (plugin.isEnabled() && adminAllowed(sender, action)) effect.run(); };
|
||||
BukkitCompletionScheduler.run(plugin, player, checked, player == null ? checked : () -> { }, () -> { });
|
||||
}
|
||||
private List<String> administerOnWorker(AdminAction action, String player, String eventId, String argument,
|
||||
Object epoch) throws IOException {
|
||||
Definition definition = definitions.stream().filter(d -> d.event().id().equals(eventId)).findFirst().orElse(null);
|
||||
if (definition == null) return List.of("Unknown or invalid date event ID.");
|
||||
DateVoteEvent event = definition.event();
|
||||
boolean network = plugin.getBungeeSettings().isUseBungeecoord();
|
||||
if (network && !event.accountingServer().equals(plugin.getBungeeSettings().getServer()))
|
||||
return List.of("Progress is remote; run this command on the configured AccountingServer.");
|
||||
Integer value = null;
|
||||
List<Integer> selected = List.of();
|
||||
if (action == AdminAction.SetVotes) {
|
||||
if (argument == null || !argument.matches("0|[1-9][0-9]{0,3}") || Integer.parseInt(argument) > 4096)
|
||||
return List.of("Votes must be an integer from 0 to 4096.");
|
||||
value = Integer.parseInt(argument);
|
||||
} else if (action == AdminAction.Force || action == AdminAction.ForceNoLimits) {
|
||||
if (!event.enabled() || !plugin.getOptions().isProcessRewards())
|
||||
return List.of("Event or reward processing is disabled; no reward was submitted.");
|
||||
if (argument == null || !argument.matches("[A-Za-z0-9_-]{1,64}")) return List.of("Invalid milestone ID or threshold.");
|
||||
String selector = argument;
|
||||
// A named At/Every entry can expand into several independently fenced thresholds.
|
||||
selected = event.thresholds().stream().filter(n -> definition.milestones().get(n).key().equals(selector)).toList();
|
||||
if (selected.isEmpty()) selected = event.thresholds().stream().filter(n -> Integer.toString(n).equals(selector)).toList();
|
||||
if (selected.isEmpty()) return List.of("Unknown milestone ID or threshold.");
|
||||
}
|
||||
VotingPluginUser user = player.length() == 36
|
||||
? plugin.getVotingPluginUserManager().getVotingPluginUser(UUID.fromString(player), false)
|
||||
: plugin.getVotingPluginUserManager().getVotingPluginUser(player);
|
||||
UUID storageId = user.getJavaUUID();
|
||||
if (!current(epoch)) return List.of();
|
||||
if (action == AdminAction.SetVotes) {
|
||||
var result = ledger().setVotes(event, storageId, value);
|
||||
invalidateProgress(storageId);
|
||||
return List.of("Date event " + eventId + " votes set to " + result.votes()
|
||||
+ "; receipt IDs and reward fences retained. No rewards were submitted.");
|
||||
}
|
||||
if (action == AdminAction.Force || action == AdminAction.ForceNoLimits) {
|
||||
int submitted = 0;
|
||||
for (int threshold : selected) {
|
||||
if (!current(epoch) || !plugin.getOptions().isProcessRewards()) break;
|
||||
if (!definition.enabledThresholds().contains(threshold)) continue;
|
||||
if (!ledger().reserveForced(event, storageId, threshold, action == AdminAction.ForceNoLimits)) continue;
|
||||
invalidateProgress(storageId);
|
||||
var placeholders = new HashMap<String, String>();
|
||||
placeholders.put("DateVoteEvent", event.displayName());
|
||||
placeholders.put("DateVoteThreshold", Integer.toString(threshold));
|
||||
plugin.getRewardHandler().giveReward(user, definition.rewards(), path(event, threshold),
|
||||
new RewardOptions().setPrefix("DateVoteMilestones-" + event.id() + "-" + threshold)
|
||||
.setServer(network).setPlaceholders(placeholders));
|
||||
ledger().submitted(event, storageId, threshold);
|
||||
submitted++;
|
||||
}
|
||||
return List.of("Date event " + eventId + ": submitted " + submitted + " of " + selected.size()
|
||||
+ " selected thresholds; disabled or fenced thresholds skipped. Vote count unchanged.");
|
||||
}
|
||||
var progress = ledger().progress(event, storageId);
|
||||
List<String> lines = new ArrayList<>();
|
||||
lines.add("Date event " + eventId + ": votes=" + progress.votes() + ", CountFakeVotes=" + definition.countFakeVotes()
|
||||
+ ", status=" + (!event.enabled() ? "disabled" : System.currentTimeMillis() < event.start() ? "upcoming"
|
||||
: System.currentTimeMillis() >= event.end() ? "ended" : "active")
|
||||
+ ". Stored in date-vote-milestones/<event-file-id>-<player-uuid>.properties.");
|
||||
for (int threshold : event.thresholds()) lines.add("Milestone " + definition.milestones().get(threshold).key()
|
||||
+ " at " + threshold + ": " + (progress.reservedAwards().contains(threshold) ? "pending review"
|
||||
: progress.submittedAwards().contains(threshold) ? "submitted"
|
||||
: progress.deferredAwards().contains(threshold) ? "deferred" : "not reached")
|
||||
+ (definition.enabledThresholds().contains(threshold) ? "" : " (disabled)"));
|
||||
return List.copyOf(lines);
|
||||
}
|
||||
private void invalidateProgress(UUID player) {
|
||||
synchronized (placeholderCache) {
|
||||
placeholderCache.entrySet().removeIf(entry -> player.equals(entry.getValue().storageId()));
|
||||
// Unresolved names have not read the ledger yet; their later read
|
||||
// will observe this mutation. Once resolved, fence matching reads.
|
||||
placeholderRequests.values().forEach(request -> {
|
||||
if (player.equals(request.resolvedStorageId)) request.invalidated = true;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/** Nonblocking projection using a previously captured storage identity. */
|
||||
public String placeholder(UUID player, String request) {
|
||||
return placeholder(player, null, request);
|
||||
}
|
||||
|
||||
/** Named offline identity is resolved only on the persistence worker. */
|
||||
public String placeholder(UUID player, java.util.function.Supplier<String> offlineName, String request) {
|
||||
if (player == null || request == null || request.length() > 100 || !plugin.isEnabled()) return "unavailable";
|
||||
PlaceholderIdentity identity = new PlaceholderIdentity(player, offlineName != null);
|
||||
int split = request.indexOf('_');
|
||||
if (split < 1) return "invalid";
|
||||
String metric = request.substring(0, split).toLowerCase(java.util.Locale.ROOT);
|
||||
String id = request.substring(split + 1);
|
||||
int threshold = -1;
|
||||
if (metric.equals("award")) {
|
||||
split = id.indexOf('_');
|
||||
if (split < 1 || !id.substring(0, split).matches("[1-9][0-9]{0,3}")) return "invalid";
|
||||
threshold = Integer.parseInt(id.substring(0, split)); id = id.substring(split + 1);
|
||||
} else if (!List.of("votes", "next", "status").contains(metric)) return "invalid";
|
||||
String eventId = id;
|
||||
Definition definition = definitions.stream().filter(d -> d.event().id().equals(eventId)).findFirst().orElse(null);
|
||||
if (definition == null) return "invalid";
|
||||
DateVoteEvent event = definition.event();
|
||||
if (metric.equals("status")) return !event.enabled() ? "disabled" : System.currentTimeMillis() < event.start()
|
||||
? "upcoming" : System.currentTimeMillis() >= event.end() ? "ended" : "active";
|
||||
if (metric.equals("award") && !event.thresholds().contains(threshold)) return "invalid";
|
||||
if (plugin.getBungeeSettings().isUseBungeecoord() && !event.accountingServer().equals(plugin.getBungeeSettings().getServer()))
|
||||
return "remote";
|
||||
Object epoch = generation;
|
||||
if (epoch == null) return "unavailable";
|
||||
CachedProgress cached;
|
||||
ProgressRequest launch = null;
|
||||
synchronized (placeholderCache) {
|
||||
cached = placeholderCache.get(identity);
|
||||
if (cached == null || cached.generation() != epoch || System.nanoTime() >= cached.expires()) {
|
||||
cached = null;
|
||||
if (!placeholderRequests.containsKey(identity)) {
|
||||
if (placeholderRequests.size() >= 64) return "unavailable";
|
||||
launch = new ProgressRequest();
|
||||
if (!identity.resolveName()) launch.resolvedStorageId = player;
|
||||
placeholderRequests.put(identity, launch);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (launch != null && !refreshPlaceholder(identity, offlineName, epoch, definitions, launch)) return "unavailable";
|
||||
if (cached == null) return "loading";
|
||||
var progress = cached.events().get(eventId);
|
||||
if (progress == null) return "unavailable";
|
||||
if (metric.equals("votes")) return Integer.toString(progress.votes());
|
||||
if (metric.equals("next")) return event.thresholds().stream().filter(n -> n > progress.votes()
|
||||
&& definition.enabledThresholds().contains(n)).findFirst().map(Object::toString).orElse("0");
|
||||
return progress.reservedAwards().contains(threshold) ? "pending_review" : progress.submittedAwards().contains(threshold)
|
||||
? "submitted" : progress.deferredAwards().contains(threshold) ? "deferred" : "not_reached";
|
||||
}
|
||||
private boolean refreshPlaceholder(PlaceholderIdentity identity, java.util.function.Supplier<String> offlineName, Object epoch, List<Definition> snapshot, ProgressRequest request) {
|
||||
try {
|
||||
plugin.getUserManager().getDataManager().getTimer().execute(() -> {
|
||||
try {
|
||||
if (!current(epoch)) return;
|
||||
UUID storageId;
|
||||
try {
|
||||
String name = offlineName == null ? null : offlineName.get();
|
||||
storageId = name == null || name.isBlank() ? identity.player()
|
||||
: plugin.getVotingPluginUserManager().getVotingPluginUser(identity.player(), name).getJavaUUID();
|
||||
if (storageId == null) throw new IllegalStateException("Missing storage identity");
|
||||
synchronized (placeholderCache) {
|
||||
if (!current(epoch) || request.invalidated || placeholderRequests.get(identity) != request) return;
|
||||
request.resolvedStorageId = storageId;
|
||||
}
|
||||
} catch (RuntimeException unavailable) {
|
||||
synchronized (placeholderCache) {
|
||||
if (current(epoch) && !request.invalidated && placeholderRequests.get(identity) == request) {
|
||||
if (placeholderCache.size() >= 256) placeholderCache.remove(placeholderCache.keySet().iterator().next());
|
||||
placeholderCache.put(identity, new CachedProgress(epoch, System.nanoTime() + 1_000_000_000L, null, java.util.Map.of()));
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
java.util.Map<String, DateVoteLedger.Progress> results = new HashMap<>();
|
||||
for (Definition definition : snapshot) {
|
||||
var event = definition.event();
|
||||
if (plugin.getBungeeSettings().isUseBungeecoord()
|
||||
&& !event.accountingServer().equals(plugin.getBungeeSettings().getServer())) continue;
|
||||
try { results.put(event.id(), ledger().progress(event, storageId)); }
|
||||
catch (IOException | RuntimeException unavailable) { /* Missing entry means unavailable, never zero. */ }
|
||||
}
|
||||
synchronized (placeholderCache) {
|
||||
if (!current(epoch) || request.invalidated || placeholderRequests.get(identity) != request) return;
|
||||
if (placeholderCache.size() >= 256) placeholderCache.remove(placeholderCache.keySet().iterator().next());
|
||||
placeholderCache.put(identity, new CachedProgress(epoch, System.nanoTime() + 5_000_000_000L, storageId, java.util.Map.copyOf(results)));
|
||||
}
|
||||
} finally { synchronized (placeholderCache) { placeholderRequests.remove(identity, request); } }
|
||||
});
|
||||
return true;
|
||||
} catch (RuntimeException unavailable) {
|
||||
synchronized (placeholderCache) {
|
||||
if (current(epoch) && placeholderRequests.get(identity) == request) {
|
||||
if (placeholderCache.size() >= 256) placeholderCache.remove(placeholderCache.keySet().iterator().next());
|
||||
placeholderCache.put(identity, new CachedProgress(epoch, System.nanoTime() + 1_000_000_000L, null, java.util.Map.of()));
|
||||
}
|
||||
placeholderRequests.remove(identity, request);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
public void progress(Player player) {
|
||||
progress(player, (view, current) -> com.bencodez.votingplugin.commands.gui.player.DateVoteEventsMenu.open(plugin, player, view, current));
|
||||
}
|
||||
/** Display is an entity-owned effect; identity resolution and ledger reads stay on the storage worker. */
|
||||
void progress(Player player, java.util.function.BiConsumer<DateVoteProgressSnapshot, java.util.function.BooleanSupplier> display) {
|
||||
BukkitCompletionScheduler.run(plugin, player, () -> {
|
||||
UUID uuid = player.getUniqueId();
|
||||
String playerName = player.getName();
|
||||
if (!canView(player)) return;
|
||||
synchronized (pendingProgress) {
|
||||
if (pendingProgress.contains(uuid) || pendingProgress.size() >= 64) {
|
||||
player.sendMessage("Date voting progress is already being checked or busy. Try again shortly."); return;
|
||||
}
|
||||
pendingProgress.add(uuid);
|
||||
}
|
||||
List<Definition> snapshot = definitions;
|
||||
try {
|
||||
plugin.getUserManager().getDataManager().getTimer().execute(() -> {
|
||||
try {
|
||||
if (snapshot != definitions || !plugin.isEnabled()) return;
|
||||
boolean proxyBackend = plugin.getBungeeSettings().isUseBungeecoord();
|
||||
String server = plugin.getBungeeSettings().getServer();
|
||||
boolean localProgress = snapshot.stream().anyMatch(d -> !proxyBackend || d.event().accountingServer().equals(server));
|
||||
UUID storageId = !localProgress ? uuid
|
||||
: plugin.getVotingPluginUserManager().getVotingPluginUser(uuid, playerName).getJavaUUID();
|
||||
List<DateVoteProgressSnapshot.Event> events = new ArrayList<>();
|
||||
long now = System.currentTimeMillis();
|
||||
for (Definition definition : snapshot) {
|
||||
var event = definition.event();
|
||||
var milestones = event.thresholds().stream().map(threshold -> {
|
||||
var configured = definition.milestones().get(threshold);
|
||||
var rewards = definition.rewards().getConfigurationSection(path(event, threshold));
|
||||
var types = rewards == null ? List.<String>of() : rewards.getKeys(false).stream()
|
||||
.filter(key -> key.length() <= 64).limit(16).toList();
|
||||
return new DateVoteProgressSnapshot.Milestone(threshold, configured.key(), configured.enabled(), types);
|
||||
}).toList();
|
||||
if (proxyBackend && !event.accountingServer().equals(server)) {
|
||||
events.add(view(event, DateVoteProgressSnapshot.Availability.REMOTE, null, milestones)); continue;
|
||||
}
|
||||
try {
|
||||
var progress = ledger().progress(event, storageId);
|
||||
events.add(view(event, DateVoteProgressSnapshot.Availability.OWNED, progress, milestones));
|
||||
} catch (IOException failure) {
|
||||
events.add(view(event, DateVoteProgressSnapshot.Availability.UNAVAILABLE, null, milestones));
|
||||
}
|
||||
}
|
||||
var result = new DateVoteProgressSnapshot(now, events);
|
||||
java.util.function.BooleanSupplier current = () -> canView(player) && snapshot == definitions
|
||||
&& plugin.getDateVoteMilestones() == this;
|
||||
BukkitCompletionScheduler.run(plugin, player, () -> {
|
||||
if (current.getAsBoolean()) display.accept(result, current);
|
||||
}, () -> { }, () -> { });
|
||||
} catch (RuntimeException unavailable) {
|
||||
BukkitCompletionScheduler.run(plugin, player, () -> {
|
||||
if (canView(player) && snapshot == definitions)
|
||||
player.sendMessage("Date voting progress is temporarily unavailable.");
|
||||
}, () -> { }, () -> { });
|
||||
} finally { synchronized (pendingProgress) { pendingProgress.remove(uuid); } }
|
||||
});
|
||||
} catch (RejectedExecutionException unavailable) {
|
||||
synchronized (pendingProgress) { pendingProgress.remove(uuid); }
|
||||
player.sendMessage("Date voting progress is temporarily unavailable.");
|
||||
}
|
||||
}, () -> { }, () -> { });
|
||||
}
|
||||
private boolean canView(Player player) {
|
||||
return plugin.isEnabled() && player.isOnline()
|
||||
&& (player.hasPermission("VotingPlugin.Commands.Vote.DateEvents") || player.hasPermission("VotingPlugin.Player"));
|
||||
}
|
||||
private static DateVoteProgressSnapshot.Event view(DateVoteEvent event, DateVoteProgressSnapshot.Availability availability,
|
||||
DateVoteLedger.Progress progress, List<DateVoteProgressSnapshot.Milestone> milestones) {
|
||||
return new DateVoteProgressSnapshot.Event(event, availability, progress == null ? 0 : progress.votes(),
|
||||
progress == null ? java.util.Set.of() : progress.submittedAwards(),
|
||||
progress == null ? java.util.Set.of() : progress.deferredAwards(),
|
||||
progress == null ? java.util.Set.of() : progress.reservedAwards(), milestones);
|
||||
}
|
||||
}
|
||||
+13
-3
@@ -146,8 +146,9 @@ public class VoteParty implements Listener {
|
||||
public void commandVoteParty(CommandSender sender) {
|
||||
if (plugin.getSpecialRewardsConfig().isVotePartyEnabled()) {
|
||||
ArrayList<String> msg = plugin.getConfigFile().getFormatCommandsVoteParty();
|
||||
int votesRequired = getVotesRequired();
|
||||
int votes = getTotalVotes();
|
||||
var display = plugin.getServerData().getVotePartyDisplay();
|
||||
int votesRequired = display.required(plugin.getSpecialRewardsConfig().getVotePartyVotesRequired());
|
||||
int votes = display.total();
|
||||
int neededVotes = votesRequired - votes;
|
||||
HashMap<String, String> placeholders = new HashMap<>();
|
||||
placeholders.put("votesrequired", "" + votesRequired);
|
||||
@@ -243,7 +244,16 @@ public class VoteParty implements Listener {
|
||||
*/
|
||||
public void giveRewards(VotingPluginUser orgUser, boolean forceBungee) {
|
||||
rewardHandler.giveRewards(orgUser, forceBungee);
|
||||
reset(false);
|
||||
// Clear this party's recipient list immediately, as before. Delaying it
|
||||
// would risk wiping voters recorded for the next party.
|
||||
setVotedUsers(new ArrayList<>());
|
||||
// Shared-MySQL recipients capture eligibility on AdvancedCore's ordered
|
||||
// storage worker. Only the persisted per-user counter wipe must run
|
||||
// behind those reads; it must not overtake deferred eligibility checks.
|
||||
com.bencodez.advancedcore.api.user.usercache.UserDataManager manager =
|
||||
plugin.getUserManager().getDataManager();
|
||||
if (manager != null && manager.deferSharedStorageWork(this::resetVotePartyCount)) return;
|
||||
resetVotePartyCount();
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+104
-10
@@ -3,6 +3,8 @@ package com.bencodez.votingplugin.specialrewards.voteparty;
|
||||
import java.util.ArrayList;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.entity.Player;
|
||||
@@ -11,6 +13,7 @@ import com.bencodez.advancedcore.api.messages.PlaceholderUtils;
|
||||
import com.bencodez.advancedcore.api.misc.MiscUtils;
|
||||
import com.bencodez.advancedcore.api.rewards.RewardBuilder;
|
||||
import com.bencodez.advancedcore.api.user.UserDataFetchMode;
|
||||
import com.bencodez.advancedcore.api.user.usercache.UserDataManager;
|
||||
import com.bencodez.simpleapi.array.ArrayUtils;
|
||||
import com.bencodez.votingplugin.VotingPluginMain;
|
||||
import com.bencodez.votingplugin.user.VotingPluginUser;
|
||||
@@ -37,10 +40,15 @@ public final class VotePartyRewardHandler {
|
||||
}
|
||||
|
||||
public void giveReward(VotingPluginUser user, boolean online, boolean useBungee) {
|
||||
givePreparedReward(user, online, useBungee, !plugin.getServerData().isLastVotePartySameDay());
|
||||
}
|
||||
|
||||
private void givePreparedReward(VotingPluginUser user, boolean online, boolean useBungee,
|
||||
boolean firstVotePartyToday) {
|
||||
new RewardBuilder(plugin.getSpecialRewardsConfig().getData(),
|
||||
plugin.getSpecialRewardsConfig().getVotePartyRewardsPath()).setOnline(online)
|
||||
.withPlaceHolder("VotesRequired", "" + plugin.getSpecialRewardsConfig().getVotePartyVotesRequired())
|
||||
.withPlaceHolder("FirstVotePartyToday", "" + !plugin.getServerData().isLastVotePartySameDay())
|
||||
.withPlaceHolder("FirstVotePartyToday", "" + firstVotePartyToday)
|
||||
.setServer(useBungee).send(user);
|
||||
}
|
||||
|
||||
@@ -82,13 +90,14 @@ public final class VotePartyRewardHandler {
|
||||
}
|
||||
}
|
||||
|
||||
/** Dispatch to every eligible user, preserving each online player's scheduler owner. */
|
||||
private void giveAllPlayers(VotingPluginUser triggeringUser, boolean forceBungee) {
|
||||
plugin.debug("Trying to give all players vote party");
|
||||
ArrayList<String> alreadyGiven = new ArrayList<>();
|
||||
for (Player player : Bukkit.getOnlinePlayers()) {
|
||||
VotingPluginUser user = resolveUser(triggeringUser, player.getUniqueId(), player);
|
||||
if (!plugin.getSpecialRewardsConfig().isVotePartyGiveOnlinePlayersOnly() || user.isOnline()) {
|
||||
voteParty.giveReward(user, forceBungee);
|
||||
giveRewardWhenLoaded(user, forceBungee, player);
|
||||
}
|
||||
alreadyGiven.add(player.getUniqueId().toString());
|
||||
}
|
||||
@@ -99,30 +108,115 @@ public final class VotePartyRewardHandler {
|
||||
}
|
||||
VotingPluginUser user = resolveUser(triggeringUser, UUID.fromString(uuid), null);
|
||||
if (!plugin.getSpecialRewardsConfig().isVotePartyGiveOnlinePlayersOnly() || user.isOnline()) {
|
||||
voteParty.giveReward(user, forceBungee);
|
||||
giveRewardWhenLoaded(user, forceBungee, null);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Dispatch to users recorded for this party before its voter list is reset. */
|
||||
private void giveVotedPlayers(VotingPluginUser triggeringUser, boolean forceBungee) {
|
||||
plugin.debug("Trying to give all voted players vote party");
|
||||
plugin.debug(ArrayUtils.makeStringList(voteParty.getVotedUsers()));
|
||||
for (String uuid : voteParty.getVotedUsers()) {
|
||||
VotingPluginUser user = resolveUser(triggeringUser, UUID.fromString(uuid), null);
|
||||
if (!plugin.getSpecialRewardsConfig().isVotePartyGiveOnlinePlayersOnly() || user.isOnline()) {
|
||||
voteParty.giveReward(user, forceBungee);
|
||||
// Capture a live player only on a platform-owned thread. The vote path
|
||||
// can also originate from a storage worker, where Bukkit lookups are unsafe.
|
||||
UserDataManager manager = sharedDataManager();
|
||||
Player owner = manager != null && manager.isPlatformOwnedThread()
|
||||
? Bukkit.getPlayer(user.getJavaUUID()) : null;
|
||||
giveRewardWhenLoaded(user, forceBungee, owner);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Resolve a recipient without forcing an uncached SQL read for shared storage. */
|
||||
private VotingPluginUser resolveUser(VotingPluginUser triggeringUser, UUID uuid, Player onlinePlayer) {
|
||||
if (triggeringUser != null && triggeringUser.getJavaUUID().equals(uuid)) {
|
||||
return triggeringUser;
|
||||
VotingPluginUser user = triggeringUser != null && triggeringUser.getJavaUUID().equals(uuid)
|
||||
? triggeringUser
|
||||
: onlinePlayer == null
|
||||
? plugin.getVotingPluginUserManager().getVotingPluginUser(uuid, true)
|
||||
: plugin.getVotingPluginUserManager().getVotingPluginUser(onlinePlayer);
|
||||
if (sharedDataManager() != null) {
|
||||
// Reward placeholders need the published shared cache, including for the triggering user.
|
||||
user.userDataFetechMode(UserDataFetchMode.DEFAULT);
|
||||
} else if (user != triggeringUser) {
|
||||
// Preserve direct reads for file/SQLite storage.
|
||||
user.userDataFetechMode(UserDataFetchMode.NO_CACHE);
|
||||
}
|
||||
VotingPluginUser user = onlinePlayer == null
|
||||
? plugin.getVotingPluginUserManager().getVotingPluginUser(uuid)
|
||||
: plugin.getVotingPluginUserManager().getVotingPluginUser(onlinePlayer);
|
||||
user.userDataFetechMode(UserDataFetchMode.NO_CACHE);
|
||||
return user;
|
||||
}
|
||||
|
||||
/** Returns the active shared SQL manager or null for nonshared storage. */
|
||||
private UserDataManager sharedDataManager() {
|
||||
UserDataManager manager = plugin.getUserManager().getDataManager();
|
||||
return manager != null && manager.hasSharedSqlBackend() ? manager : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Capture shared SQL reward eligibility on AdvancedCore's storage worker.
|
||||
* This must finish before the VoteParty counter wipe is enqueued on that worker.
|
||||
* A caller running on a platform thread must not check even a published cache
|
||||
* directly because checking publication takes the cache's synchronized monitor.
|
||||
*/
|
||||
private void giveRewardWhenLoaded(VotingPluginUser user, boolean forceBungee, Player callbackOwner) {
|
||||
UserDataManager manager = sharedDataManager();
|
||||
if (manager == null) {
|
||||
voteParty.giveReward(user, forceBungee);
|
||||
return;
|
||||
}
|
||||
UUID uuid = user.getJavaUUID();
|
||||
|
||||
// VoteParty clears per-user counters and updates the last-party timestamp
|
||||
// after dispatch. Capture these decisions before that reset, not when the
|
||||
// deferred reward finally runs on the player scheduler.
|
||||
final boolean firstPartyToday = !plugin.getServerData().isLastVotePartySameDay();
|
||||
final int userVotesRequired = plugin.getSpecialRewardsConfig().getVotePartyUserVotesRequired();
|
||||
|
||||
// A mapped cache entry can still be an *unpublished* placeholder, so
|
||||
// cacheUserIfNeeded() alone would not make reward placeholders safe to read.
|
||||
Supplier<Integer> populate = () -> {
|
||||
if (manager.getPublishedCache(uuid) == null) manager.cacheUser(uuid, null);
|
||||
if (manager.getPublishedCache(uuid) == null) return null;
|
||||
// Read eligibility on the storage worker, before VoteParty resets counters.
|
||||
return userVotesRequired > 0 ? user.getVotePartyVotes() : 0;
|
||||
};
|
||||
Consumer<Integer> success = votes -> {
|
||||
if (votes == null) {
|
||||
plugin.getLogger().warning("VoteParty reward not sent: shared user data is unavailable for " + uuid);
|
||||
return;
|
||||
}
|
||||
if (votes < userVotesRequired) return;
|
||||
|
||||
// Eligibility was captured on the storage worker before reset. Do not
|
||||
// re-read the cache on a platform thread or re-check reset counters.
|
||||
Runnable deliver = () -> givePreparedReward(user, user.isOnline(), forceBungee, firstPartyToday);
|
||||
if (callbackOwner != null) {
|
||||
deliver.run();
|
||||
} else {
|
||||
// A worker-originated vote has no captured Player. Its completion is
|
||||
// on the global platform scheduler; discover a live owner there.
|
||||
Player online = Bukkit.getPlayer(uuid);
|
||||
if (online == null) deliver.run();
|
||||
else plugin.getBukkitScheduler().runTask(plugin, deliver, online);
|
||||
}
|
||||
};
|
||||
Consumer<Throwable> failure = error -> plugin.getLogger()
|
||||
.warning("Failed to load shared user data for VoteParty reward " + uuid + ": " + error);
|
||||
|
||||
try {
|
||||
if (manager.deferSharedStorageResult(populate, success, failure, callbackOwner)) return;
|
||||
|
||||
// Called from a non-platform worker: storage reads are safe here, but reward
|
||||
// effects still need the Bukkit/Folia scheduler.
|
||||
Integer ready = populate.get();
|
||||
if (callbackOwner != null) {
|
||||
plugin.getBukkitScheduler().runTask(plugin, () -> success.accept(ready), callbackOwner);
|
||||
} else {
|
||||
plugin.getBukkitScheduler().runTask(plugin, () -> success.accept(ready));
|
||||
}
|
||||
} catch (RuntimeException | Error error) {
|
||||
failure.accept(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
+2
-4
@@ -24,8 +24,7 @@ public final class VotePartyState {
|
||||
}
|
||||
|
||||
public void setTotalVotes(int value) {
|
||||
plugin.getServerData().getData().set(TOTAL_PATH, value);
|
||||
plugin.getServerData().saveData();
|
||||
plugin.getServerData().setInt(TOTAL_PATH, value);
|
||||
}
|
||||
|
||||
public List<String> getVotedUsers() {
|
||||
@@ -34,8 +33,7 @@ public final class VotePartyState {
|
||||
}
|
||||
|
||||
public void setVotedUsers(List<String> users) {
|
||||
plugin.getServerData().getData().set(VOTED_PATH, users);
|
||||
plugin.getServerData().saveData();
|
||||
plugin.getServerData().setStringList(VOTED_PATH, users);
|
||||
}
|
||||
|
||||
public int getVotesRequired() {
|
||||
|
||||
+21
@@ -40,6 +40,7 @@ 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;
|
||||
@@ -56,6 +57,26 @@ 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() {
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,277 @@
|
||||
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(); }
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
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"; };
|
||||
}
|
||||
}
|
||||
+289
-35
@@ -3,10 +3,15 @@ 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;
|
||||
@@ -24,11 +29,24 @@ 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();
|
||||
|
||||
@@ -48,10 +66,23 @@ public class TimeQueueHandler implements Listener {
|
||||
* @param voteUsername the voter username
|
||||
* @param voteSiteName the vote site name
|
||||
*/
|
||||
public void addVote(String voteUsername, String voteSiteName) {
|
||||
timeChangeQueue.add(new VoteTimeQueue(voteUsername, voteSiteName,
|
||||
LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()));
|
||||
}
|
||||
public void addVote(String voteUsername, String voteSiteName) { addVote(voteUsername, voteSiteName, 0L); }
|
||||
|
||||
public void addVote(String voteUsername, String voteSiteName, long occurredAt) {
|
||||
addVote(voteUsername, voteSiteName, occurredAt, UUID.randomUUID());
|
||||
}
|
||||
|
||||
public void addVote(String voteUsername, String voteSiteName, long occurredAt, UUID localOccurrenceId) {
|
||||
java.util.Objects.requireNonNull(localOccurrenceId, "localOccurrenceId");
|
||||
VoteTimeQueue queued = new VoteTimeQueue(voteUsername, voteSiteName,
|
||||
LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli());
|
||||
queued.setLocalOccurrenceId(localOccurrenceId);
|
||||
if (occurredAt > 0) queued.setCanonicalOccurrenceTime(occurredAt);
|
||||
synchronized (persistenceLock) {
|
||||
timeChangeQueue.add(queued);
|
||||
if (stopping) persistPendingVotes();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads cached votes from server data and schedules queue processing.
|
||||
@@ -59,8 +90,29 @@ public class TimeQueueHandler implements Listener {
|
||||
public void load() {
|
||||
for (String str : plugin.getServerData().getTimedVoteCacheKeys()) {
|
||||
ConfigurationSection data = plugin.getServerData().getTimedVoteCacheSection(str);
|
||||
timeChangeQueue
|
||||
.add(new VoteTimeQueue(data.getString("Name"), data.getString("Service"), data.getLong("Time")));
|
||||
VoteTimeQueue queued = new VoteTimeQueue(data.getString("Name"), data.getString("Service"), data.getLong("Time"));
|
||||
UUID localOccurrenceId;
|
||||
if (!data.contains("LocalOccurrenceId")) {
|
||||
// The existing ServerData saver can defer publication. Derive only
|
||||
// legacy migration IDs from their persisted row identity so a crash
|
||||
// before that save completes cannot reroll the same legacy row.
|
||||
String identity = "legacy-local-timed-vote\u0000" + str + "\u0000" + queued.getName()
|
||||
+ "\u0000" + queued.getService() + "\u0000" + queued.getTime();
|
||||
localOccurrenceId = UUID.nameUUIDFromBytes(identity.getBytes(java.nio.charset.StandardCharsets.UTF_8));
|
||||
plugin.getServerData().setTimedVoteLocalOccurrenceId(str, localOccurrenceId);
|
||||
} else {
|
||||
String rawId = data.getString("LocalOccurrenceId");
|
||||
try {
|
||||
localOccurrenceId = UUID.fromString(rawId);
|
||||
if (!localOccurrenceId.toString().equalsIgnoreCase(rawId)) throw new IllegalArgumentException();
|
||||
} catch (IllegalArgumentException | NullPointerException malformed) {
|
||||
plugin.getLogger().warning("Invalid local occurrence ID in timed vote cache; row withheld");
|
||||
continue;
|
||||
}
|
||||
}
|
||||
queued.setLocalOccurrenceId(localOccurrenceId);
|
||||
if (data.contains("CanonicalOccurrenceTime")) queued.setCanonicalOccurrenceTime(data.getLong("CanonicalOccurrenceTime", -1L));
|
||||
timeChangeQueue.add(queued);
|
||||
}
|
||||
scheduleQueueProcessing(120, TimeUnit.SECONDS);
|
||||
}
|
||||
@@ -76,17 +128,11 @@ public class TimeQueueHandler implements Listener {
|
||||
}
|
||||
|
||||
private void scheduleQueueProcessing(long delay, TimeUnit 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);
|
||||
synchronized (persistenceLock) { if (stopping) return; }
|
||||
boolean admitted = VoteTaskAdmission.trySchedule(plugin.getVoteTimer(), this::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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -94,15 +140,14 @@ 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);
|
||||
}, delayTicks);
|
||||
}, delaySeconds);
|
||||
} catch (RuntimeException rejected) {
|
||||
retryPending.set(false);
|
||||
plugin.getLogger().warning("Unable to queue a time-queue retry; pending votes remain persisted for recovery.");
|
||||
plugin.getLogger().warning("Unable to queue a time-queue retry; pending votes remain owned for recovery.");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -110,32 +155,241 @@ public class TimeQueueHandler implements Listener {
|
||||
* Processes all votes in the queue.
|
||||
*/
|
||||
public void processQueue() {
|
||||
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");
|
||||
return;
|
||||
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 (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());
|
||||
voteEvent.setLocalOccurrenceId(vote.getLocalOccurrenceId());
|
||||
if (vote.getCanonicalOccurrenceTime() != 0L) voteEvent.setCanonicalOccurrenceTime(vote.getCanonicalOccurrenceTime());
|
||||
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 (!timeChangeQueue.isEmpty()) {
|
||||
int num = 0;
|
||||
for (VoteTimeQueue vote : timeChangeQueue) {
|
||||
plugin.getServerData().addTimeVoted(num, vote);
|
||||
num++;
|
||||
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);
|
||||
}
|
||||
}
|
||||
timeChangeQueue.clear();
|
||||
}
|
||||
}
|
||||
@@ -30,6 +30,10 @@ public class VoteTimeQueue {
|
||||
@Getter
|
||||
@Setter
|
||||
private UUID voteId;
|
||||
/** Local Bukkit receipt identity; never used as a proxy transport vote ID. */
|
||||
@Getter
|
||||
@Setter
|
||||
private UUID localOccurrenceId;
|
||||
/** SQL primary key for a legacy timed-cache row, or {@code -1} when not SQL-backed. */
|
||||
@Getter
|
||||
@Setter
|
||||
@@ -47,6 +51,19 @@ public class VoteTimeQueue {
|
||||
@Getter
|
||||
@Setter
|
||||
private String totals;
|
||||
|
||||
public long getCanonicalOccurrenceTime() {
|
||||
Long original = com.bencodez.votingplugin.proxy.VoteOccurrenceMetadata.read(totals);
|
||||
return original == null ? 0L : original;
|
||||
}
|
||||
|
||||
public void setCanonicalOccurrenceTime(long time) {
|
||||
totals = com.bencodez.votingplugin.proxy.VoteOccurrenceMetadata.store(totals, time);
|
||||
}
|
||||
|
||||
public void setTotals(String updated) {
|
||||
totals = com.bencodez.votingplugin.proxy.VoteOccurrenceMetadata.preserve(totals, updated);
|
||||
}
|
||||
@Getter
|
||||
@Setter
|
||||
private boolean processed;
|
||||
@@ -400,7 +417,8 @@ public class VoteTimeQueue {
|
||||
|
||||
/** Returns whether any standalone HTTP broadcast still has to be delivered. */
|
||||
public boolean hasPendingHttpBroadcastDeliveryIds() {
|
||||
return !httpBroadcastDeliveryIds.isEmpty();
|
||||
return httpBroadcastDeliveryIds.keySet().stream().anyMatch(key -> !key.startsWith(
|
||||
com.bencodez.votingplugin.proxy.VotingPluginWire.REWARD_QUEUE_METADATA_PREFIX));
|
||||
}
|
||||
|
||||
public String encodeHttpBroadcastDeliveryIds() {
|
||||
|
||||
+269
@@ -0,0 +1,269 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
+28
-18
@@ -113,11 +113,12 @@ public class TopVoterHandler implements Listener {
|
||||
*/
|
||||
public String[] getTopVotersWeekly() {
|
||||
ArrayList<String> msg = new ArrayList<>();
|
||||
ArrayList<TopVoterPlayer> users = new ArrayList<>(plugin.getTopVoter(TopVoter.Weekly).keySet());
|
||||
var board = plugin.getTopVoterDisplay(TopVoter.Weekly);
|
||||
ArrayList<TopVoterPlayer> users = new ArrayList<>(board.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%", "" + plugin.getTopVoter(TopVoter.Weekly).get(users.get(i)));
|
||||
.replace("%votes%", "" + board.get(users.get(i)));
|
||||
msg.add(line);
|
||||
}
|
||||
msg = ArrayUtils.colorize(msg);
|
||||
@@ -638,11 +639,12 @@ public class TopVoterHandler implements Listener {
|
||||
* @return the string[]
|
||||
*/
|
||||
public String[] topVoterAllTime(int page) {
|
||||
int pagesize = plugin.getConfigFile().getFormatPageSize();
|
||||
page = Math.max(1, page);
|
||||
int pagesize = Math.max(1, plugin.getConfigFile().getFormatPageSize());
|
||||
ArrayList<String> msg = new ArrayList<>();
|
||||
ArrayList<String> topVoters = new ArrayList<>();
|
||||
int count = 1;
|
||||
for (Entry<TopVoterPlayer, Integer> entry : plugin.getTopVoter(TopVoter.AllTime).entrySet()) {
|
||||
for (Entry<TopVoterPlayer, Integer> entry : plugin.getTopVoterDisplay(TopVoter.AllTime).entrySet()) {
|
||||
String line = plugin.getConfigFile().getFormatCommandsVoteTopLine();
|
||||
line = line.replace("%num%", "" + count);
|
||||
line = line.replace("%player%", entry.getKey().getPlayerName());
|
||||
@@ -662,7 +664,8 @@ public class TopVoterHandler implements Listener {
|
||||
title = title.replace("%Top%", plugin.getConfigFile().getFormatTopVoterAllTime());
|
||||
msg.add(MessageAPI.colorize(title));
|
||||
|
||||
for (int i = (page - 1) * pagesize; (i < topVoters.size()) && (i < (((page - 1) * pagesize) + 10)); i++) {
|
||||
long start = (long) (page - 1) * pagesize;
|
||||
for (int i = (int) Math.min(start, topVoters.size()); i < topVoters.size() && i < start + pagesize; i++) {
|
||||
msg.add(topVoters.get(i));
|
||||
}
|
||||
|
||||
@@ -676,11 +679,12 @@ public class TopVoterHandler implements Listener {
|
||||
* @return array of formatted top voter lines
|
||||
*/
|
||||
public String[] topVoterDaily(int page) {
|
||||
int pagesize = plugin.getConfigFile().getFormatPageSize();
|
||||
page = Math.max(1, page);
|
||||
int pagesize = Math.max(1, plugin.getConfigFile().getFormatPageSize());
|
||||
ArrayList<String> msg = new ArrayList<>();
|
||||
ArrayList<String> topVoters = new ArrayList<>();
|
||||
int count = 1;
|
||||
for (Entry<TopVoterPlayer, Integer> entry : plugin.getTopVoter(TopVoter.Daily).entrySet()) {
|
||||
for (Entry<TopVoterPlayer, Integer> entry : plugin.getTopVoterDisplay(TopVoter.Daily).entrySet()) {
|
||||
String line = plugin.getConfigFile().getFormatCommandsVoteTopLine();
|
||||
line = line.replace("%num%", "" + count);
|
||||
line = line.replace("%player%", entry.getKey().getPlayerName());
|
||||
@@ -700,7 +704,8 @@ public class TopVoterHandler implements Listener {
|
||||
title = title.replace("%Top%", plugin.getConfigFile().getFormatTopVoterDaily());
|
||||
msg.add(MessageAPI.colorize(title));
|
||||
|
||||
for (int i = (page - 1) * pagesize; (i < topVoters.size()) && (i < (((page - 1) * pagesize) + 10)); i++) {
|
||||
long start = (long) (page - 1) * pagesize;
|
||||
for (int i = (int) Math.min(start, topVoters.size()); i < topVoters.size() && i < start + pagesize; i++) {
|
||||
msg.add(topVoters.get(i));
|
||||
}
|
||||
|
||||
@@ -714,11 +719,12 @@ public class TopVoterHandler implements Listener {
|
||||
* @return array of formatted top voter lines
|
||||
*/
|
||||
public String[] topVoterMonthly(int page) {
|
||||
int pagesize = plugin.getConfigFile().getFormatPageSize();
|
||||
page = Math.max(1, page);
|
||||
int pagesize = Math.max(1, plugin.getConfigFile().getFormatPageSize());
|
||||
ArrayList<String> msg = new ArrayList<>();
|
||||
ArrayList<String> topVoters = new ArrayList<>();
|
||||
int count = 1;
|
||||
for (Entry<TopVoterPlayer, Integer> entry : plugin.getTopVoter(TopVoter.Monthly).entrySet()) {
|
||||
for (Entry<TopVoterPlayer, Integer> entry : plugin.getTopVoterDisplay(TopVoter.Monthly).entrySet()) {
|
||||
String line = plugin.getConfigFile().getFormatCommandsVoteTopLine();
|
||||
line = line.replace("%num%", "" + count);
|
||||
line = line.replace("%player%", entry.getKey().getPlayerName());
|
||||
@@ -738,7 +744,8 @@ public class TopVoterHandler implements Listener {
|
||||
title = title.replace("%Top%", plugin.getConfigFile().getFormatTopVoterMonthly());
|
||||
msg.add(MessageAPI.colorize(title));
|
||||
|
||||
for (int i = (page - 1) * pagesize; (i < topVoters.size()) && (i < (((page - 1) * pagesize) + 10)); i++) {
|
||||
long start = (long) (page - 1) * pagesize;
|
||||
for (int i = (int) Math.min(start, topVoters.size()); i < topVoters.size() && i < start + pagesize; i++) {
|
||||
msg.add(topVoters.get(i));
|
||||
}
|
||||
|
||||
@@ -752,7 +759,7 @@ public class TopVoterHandler implements Listener {
|
||||
*/
|
||||
public String[] topVotersAllTime() {
|
||||
ArrayList<String> msg = new ArrayList<>();
|
||||
List<Entry<TopVoterPlayer, Integer>> list = new LinkedList<>(plugin.getTopVoter(TopVoter.AllTime).entrySet());
|
||||
List<Entry<TopVoterPlayer, Integer>> list = new LinkedList<>(plugin.getTopVoterDisplay(TopVoter.AllTime).entrySet());
|
||||
int i = 0;
|
||||
for (Entry<TopVoterPlayer, Integer> entry : list) {
|
||||
String line = "%num%: %player%, %votes%";
|
||||
@@ -778,7 +785,8 @@ public class TopVoterHandler implements Listener {
|
||||
*/
|
||||
public String[] topVotersDaily() {
|
||||
ArrayList<String> msg = new ArrayList<>();
|
||||
ArrayList<TopVoterPlayer> users = new ArrayList<>(plugin.getTopVoter(TopVoter.Daily).keySet());
|
||||
var board = plugin.getTopVoterDisplay(TopVoter.Daily);
|
||||
ArrayList<TopVoterPlayer> users = new ArrayList<>(board.keySet());
|
||||
for (int i = 0; i < users.size(); i++) {
|
||||
String line = "%num%: %player%, %votes%";
|
||||
line = line.replace("%num%", "" + (i + 1));
|
||||
@@ -787,7 +795,7 @@ public class TopVoterHandler implements Listener {
|
||||
} catch (Exception ex) {
|
||||
VotingPluginMain.plugin.debug(ex);
|
||||
}
|
||||
line = line.replace("%votes%", "" + plugin.getTopVoter(TopVoter.Monthly).get(users.get(i)));
|
||||
line = line.replace("%votes%", "" + board.get(users.get(i)));
|
||||
msg.add(line);
|
||||
}
|
||||
|
||||
@@ -801,7 +809,7 @@ public class TopVoterHandler implements Listener {
|
||||
*/
|
||||
public String[] topVotersMonthly() {
|
||||
ArrayList<String> msg = new ArrayList<>();
|
||||
List<Entry<TopVoterPlayer, Integer>> list = new LinkedList<>(plugin.getTopVoter(TopVoter.Monthly).entrySet());
|
||||
List<Entry<TopVoterPlayer, Integer>> list = new LinkedList<>(plugin.getTopVoterDisplay(TopVoter.Monthly).entrySet());
|
||||
int i = 0;
|
||||
for (Entry<TopVoterPlayer, Integer> entry : list) {
|
||||
String line = "%num%: %player%, %votes%";
|
||||
@@ -827,11 +835,12 @@ public class TopVoterHandler implements Listener {
|
||||
* @return array of formatted top voter lines
|
||||
*/
|
||||
public String[] topVoterWeekly(int page) {
|
||||
int pagesize = plugin.getConfigFile().getFormatPageSize();
|
||||
page = Math.max(1, page);
|
||||
int pagesize = Math.max(1, plugin.getConfigFile().getFormatPageSize());
|
||||
ArrayList<String> msg = new ArrayList<>();
|
||||
ArrayList<String> topVoters = new ArrayList<>();
|
||||
int count = 1;
|
||||
for (Entry<TopVoterPlayer, Integer> entry : plugin.getTopVoter(TopVoter.Weekly).entrySet()) {
|
||||
for (Entry<TopVoterPlayer, Integer> entry : plugin.getTopVoterDisplay(TopVoter.Weekly).entrySet()) {
|
||||
String line = plugin.getConfigFile().getFormatCommandsVoteTopLine();
|
||||
line = line.replace("%num%", "" + count);
|
||||
line = line.replace("%player%", entry.getKey().getPlayerName());
|
||||
@@ -851,7 +860,8 @@ public class TopVoterHandler implements Listener {
|
||||
title = title.replace("%Top%", plugin.getConfigFile().getFormatTopVoterWeekly());
|
||||
msg.add(MessageAPI.colorize(title));
|
||||
|
||||
for (int i = (page - 1) * pagesize; (i < topVoters.size()) && (i < (((page - 1) * pagesize) + 10)); i++) {
|
||||
long start = (long) (page - 1) * pagesize;
|
||||
for (int i = (int) Math.min(start, topVoters.size()); i < topVoters.size() && i < start + pagesize; i++) {
|
||||
msg.add(topVoters.get(i));
|
||||
}
|
||||
|
||||
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
+38
-4
@@ -93,10 +93,20 @@ 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.getVotingPluginUserManager().getVotingPluginUser(UUID.fromString(uuid), false).cacheAsync();
|
||||
plugin.getBukkitScheduler().runTaskAsynchronously(plugin,
|
||||
() -> tryInvalidateAndRefreshOnWorker(plugin, uuid, columns));
|
||||
} 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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -106,13 +116,37 @@ 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) {
|
||||
invalidate(plugin, uuid, columns);
|
||||
if (plugin == null || uuid == null) return;
|
||||
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;
|
||||
try {
|
||||
plugin.getUserManager().getDataManager().cacheUser(UUID.fromString(uuid), null);
|
||||
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;
|
||||
} 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);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+326
-159
@@ -21,6 +21,7 @@ import com.bencodez.simpleapi.sql.DataType;
|
||||
import com.bencodez.simpleapi.sql.data.DataValue;
|
||||
import com.bencodez.simpleapi.sql.data.DataValueInt;
|
||||
import com.bencodez.votingplugin.VotingPluginMain;
|
||||
import com.bencodez.votingplugin.placeholders.PlaceHolders;
|
||||
import com.bencodez.votingplugin.util.BukkitCompletionScheduler;
|
||||
|
||||
/** Performs point writes that must remain atomic across shared MySQL servers. */
|
||||
@@ -124,7 +125,7 @@ final class SharedMysqlPointMutator {
|
||||
int previousTotal = cachedPoints(user, pointsColumn);
|
||||
int predictedTotal = previousTotal + amount;
|
||||
cachePredictedPoints(user, predictedTotal, pointsColumn);
|
||||
if (!run(() -> update(user, amount, false, pointsColumn), true)) {
|
||||
if (!runPointMutation(user, () -> update(user, amount, false, pointsColumn), true)) {
|
||||
discardOptimisticPoints(user, pointsColumn);
|
||||
if (failOnRejectedAdmission) throw new IllegalStateException("Point mutation storage worker is unavailable");
|
||||
return previousTotal;
|
||||
@@ -185,16 +186,29 @@ final class SharedMysqlPointMutator {
|
||||
|
||||
AddResult addCommittedToColumn(VotingPluginUser user, int amount, String operationId, String pointsColumn) {
|
||||
if (operationId == null || operationId.isEmpty()) return addCommittedToColumn(user, amount, pointsColumn);
|
||||
drainCache(user, pointsColumn);
|
||||
var placeholders = plugin.getPlaceholders();
|
||||
UUID uuid = UUID.fromString(user.getUUID());
|
||||
if (placeholders != null) placeholders.beginSharedPointDebit(uuid);
|
||||
boolean confirmed = false;
|
||||
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 {
|
||||
discardPointsCache(user, pointsColumn);
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -209,18 +223,36 @@ final class SharedMysqlPointMutator {
|
||||
|
||||
AddResult removeCommittedFromColumn(VotingPluginUser user, int amount, String operationId, String pointsColumn) {
|
||||
if (operationId == null || operationId.isEmpty()) return new AddResult(false, 0);
|
||||
drainCache(user, pointsColumn);
|
||||
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;
|
||||
try {
|
||||
drainCache(user, pointsColumn);
|
||||
SharedPointAdditionJournal.AdditionResult result = SharedPointAdditionJournal.forTable(plugin.getMysql())
|
||||
.subtract(operationId, user.getUUID(), pointsColumn, amount, System.currentTimeMillis());
|
||||
return new AddResult(true, result.total());
|
||||
outcome = new AddResult(true, result.total());
|
||||
} catch (SQLException failure) {
|
||||
logFailure(failure);
|
||||
return new AddResult(failure instanceof SharedPointAdditionJournal.DebitRejectedException
|
||||
? MutationOutcome.REJECTED : MutationOutcome.INDETERMINATE, 0);
|
||||
if (failure instanceof SharedPointAdditionJournal.DebitRejectedException) {
|
||||
outcome = new AddResult(MutationOutcome.REJECTED, 0);
|
||||
} else {
|
||||
logFailure(failure);
|
||||
outcome = new AddResult(MutationOutcome.INDETERMINATE, 0);
|
||||
}
|
||||
} finally {
|
||||
discardPointsCache(user, pointsColumn);
|
||||
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);
|
||||
}
|
||||
}
|
||||
return new AddResult(outcome.outcome(), outcome.total(), refreshed);
|
||||
}
|
||||
|
||||
/** Looks up a completed retry before its Bukkit receive event is dispatched. */
|
||||
@@ -326,7 +358,20 @@ final class SharedMysqlPointMutator {
|
||||
|
||||
boolean set(VotingPluginUser user, int value, boolean async) {
|
||||
String pointsColumn = user.getPointsPath();
|
||||
return run(() -> setAbsolute(user, value, pointsColumn), async);
|
||||
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;
|
||||
}
|
||||
|
||||
boolean setCommitted(VotingPluginUser user, int value) {
|
||||
@@ -339,7 +384,7 @@ final class SharedMysqlPointMutator {
|
||||
|
||||
void cap(VotingPluginUser user, int maximum, boolean async) {
|
||||
String pointsColumn = user.getPointsPath();
|
||||
run(() -> capAt(user, maximum, pointsColumn), async);
|
||||
runPointMutation(user, () -> capAt(user, maximum, pointsColumn), async);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -357,7 +402,7 @@ final class SharedMysqlPointMutator {
|
||||
int predictedTotal = (int) Math.max(Integer.MIN_VALUE,
|
||||
Math.min((long) previousTotal + amount, maximum));
|
||||
cachePredictedPoints(user, predictedTotal, pointsColumn);
|
||||
if (!run(() -> addAndCapAt(user, amount, maximum, pointsColumn), true)) {
|
||||
if (!runPointMutation(user, () -> addAndCapAt(user, amount, maximum, pointsColumn), true)) {
|
||||
discardOptimisticPoints(user, pointsColumn);
|
||||
}
|
||||
}
|
||||
@@ -370,7 +415,7 @@ final class SharedMysqlPointMutator {
|
||||
if (!async) return remove(user, amount);
|
||||
String pointsColumn = user.getPointsPath();
|
||||
boolean predictedSuccess = cachedPoints(user, pointsColumn) >= amount;
|
||||
boolean submitted = run(() -> update(user, -amount, true, pointsColumn), true);
|
||||
boolean submitted = runPointMutation(user, () -> update(user, -amount, true, pointsColumn), true);
|
||||
// Preserve the historical asynchronous API contract: the caller receives
|
||||
// the cached prediction while the conditional database debit runs later.
|
||||
return submitted && predictedSuccess;
|
||||
@@ -498,41 +543,40 @@ 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(() -> {
|
||||
try {
|
||||
drainCache(source);
|
||||
drainCache(target);
|
||||
} catch (RuntimeException cacheFailure) {
|
||||
plugin.debug(cacheFailure);
|
||||
completeOnBukkit(sourcePlayer, completion, PointTransferResult.UNAVAILABLE);
|
||||
return;
|
||||
}
|
||||
MySQL table = plugin.getMysql();
|
||||
String transferId = UUID.randomUUID().toString();
|
||||
String owner = UUID.randomUUID().toString();
|
||||
SharedPointTransferJournal journal;
|
||||
SharedPointTransferJournal prepared = null;
|
||||
boolean known = true;
|
||||
boolean reserved = false;
|
||||
PointTransferResult failed = PointTransferResult.UNAVAILABLE;
|
||||
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);
|
||||
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) {
|
||||
// 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);
|
||||
known |= failure instanceof SharedPointTransferJournal.PreparationFailure;
|
||||
logFailure(failure);
|
||||
completeOnBukkit(sourcePlayer, completion, PointTransferResult.UNAVAILABLE);
|
||||
} 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);
|
||||
return;
|
||||
}
|
||||
SharedPointTransferJournal journal = prepared;
|
||||
|
||||
/*
|
||||
* Do not claim the reservation until the Bukkit approval task has actually
|
||||
@@ -562,6 +606,7 @@ 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);
|
||||
}
|
||||
}
|
||||
@@ -574,8 +619,7 @@ final class SharedMysqlPointMutator {
|
||||
System.currentTimeMillis());
|
||||
if (claim == SharedPointTransferJournal.ClaimOutcome.NOT_CLAIMED) {
|
||||
try {
|
||||
journal.refundReserved(transferId, source.getUUID(), sourcePoints, debitAmount);
|
||||
discardPointsCache(source, sourcePoints);
|
||||
refundReservedWithPublication(source, journal, transferId, sourcePoints, debitAmount);
|
||||
} catch (SQLException failure) {
|
||||
logFailure(failure);
|
||||
}
|
||||
@@ -713,10 +757,7 @@ final class SharedMysqlPointMutator {
|
||||
} catch (SQLException markerFailure) {
|
||||
boolean refunded = false;
|
||||
try {
|
||||
refunded = journal.refundHookStarted(transferId, source.getUUID(), sourcePoints, debitAmount);
|
||||
if (refunded) {
|
||||
discardPointsCache(source, sourcePoints);
|
||||
}
|
||||
refunded = refundClaimedWithPublication(source, journal, transferId, sourcePoints, debitAmount);
|
||||
} catch (SQLException refundFailure) {
|
||||
logFailure(refundFailure);
|
||||
}
|
||||
@@ -736,17 +777,24 @@ 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 {
|
||||
discardPointsCache(source, sourcePoints);
|
||||
discardPointsCache(target, targetPoints);
|
||||
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);
|
||||
}
|
||||
result = outcome == SharedPointTransferJournal.SettlementOutcome.COMPLETED ? PointTransferResult.SUCCESS
|
||||
: outcome == SharedPointTransferJournal.SettlementOutcome.REFUNDED ? PointTransferResult.CANCELLED
|
||||
@@ -760,14 +808,29 @@ 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 {
|
||||
if (journal.refundReserved(transferId, source.getUUID(), sourcePoints, debitAmount)) {
|
||||
discardPointsCache(source, sourcePoints);
|
||||
}
|
||||
refundReservedWithPublication(source, journal, transferId, sourcePoints, debitAmount);
|
||||
} catch (SQLException refundFailure) {
|
||||
logFailure(refundFailure);
|
||||
}
|
||||
@@ -783,24 +846,23 @@ 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 = journal.refundHookStarted(transferId, source.getUUID(), sourcePoints, debitAmount);
|
||||
refunded = refundClaimedWithPublication(source, journal, transferId, sourcePoints, debitAmount);
|
||||
} else {
|
||||
refunded = journal.refundReserved(transferId, source.getUUID(), sourcePoints, debitAmount);
|
||||
refunded = refundReservedWithPublication(source, journal, transferId, 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 = journal.refundHookStarted(transferId, source.getUUID(), sourcePoints, debitAmount);
|
||||
refunded = refundClaimedWithPublication(source, journal, transferId, sourcePoints, debitAmount);
|
||||
if (!refunded) {
|
||||
refunded = journal.refundReserved(transferId, source.getUUID(), sourcePoints, debitAmount);
|
||||
refunded = refundReservedWithPublication(source, journal, transferId, sourcePoints, debitAmount);
|
||||
}
|
||||
} catch (SQLException refundFailure) {
|
||||
logFailure(refundFailure);
|
||||
}
|
||||
logFailure(markerFailure);
|
||||
}
|
||||
if (refunded) discardPointsCache(source, sourcePoints);
|
||||
if (!refunded) {
|
||||
rememberPendingCompensationMarker(plugin, transferId);
|
||||
logIndeterminateClaim(transferId);
|
||||
@@ -815,19 +877,32 @@ 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 {
|
||||
journal.refundHookStarted(transferId, source.getUUID(), sourcePoints, debitAmount);
|
||||
refundClaimedWithPublication(source, journal, transferId, 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);
|
||||
@@ -890,6 +965,23 @@ final class SharedMysqlPointMutator {
|
||||
}
|
||||
}
|
||||
|
||||
private boolean runPointMutation(VotingPluginUser user, Runnable operation, boolean async) {
|
||||
PlaceHolders placeholders = plugin.getPlaceholders();
|
||||
Consumer<Boolean> admission = placeholders == null ? null
|
||||
: placeholders.sharedPointAdmissionCompletion(UUID.fromString(user.getUUID()));
|
||||
boolean accepted = run(() -> {
|
||||
boolean settled = false;
|
||||
try {
|
||||
operation.run();
|
||||
settled = true;
|
||||
} finally {
|
||||
if (admission != null) admission.accept(settled);
|
||||
}
|
||||
}, async);
|
||||
if (!accepted && admission != null) admission.accept(false);
|
||||
return accepted;
|
||||
}
|
||||
|
||||
private boolean run(Runnable operation, boolean async) {
|
||||
if (async) {
|
||||
try {
|
||||
@@ -910,25 +1002,34 @@ final class SharedMysqlPointMutator {
|
||||
}
|
||||
|
||||
private boolean update(VotingPluginUser user, int delta, boolean requireNonnegative, String points) {
|
||||
drainCache(user, points);
|
||||
MySQL table = plugin.getMysql();
|
||||
StringBuilder sql = new StringBuilder("UPDATE ").append(table.qi(table.getTableName())).append(" SET ")
|
||||
.append(table.qi(points)).append(" = COALESCE(").append(table.qi(points)).append(", 0) + ? WHERE ")
|
||||
.append(table.qi("uuid")).append(table.getDbType() == DbType.POSTGRESQL ? " = ?::uuid" : " = ?");
|
||||
if (requireNonnegative) {
|
||||
sql.append(" AND COALESCE(").append(table.qi(points)).append(", 0) >= ?");
|
||||
}
|
||||
try (Connection connection = requireConnection(table);
|
||||
PreparedStatement statement = connection.prepareStatement(sql.toString())) {
|
||||
statement.setInt(1, delta);
|
||||
statement.setString(2, user.getUUID());
|
||||
if (requireNonnegative) statement.setInt(3, -delta);
|
||||
return statement.executeUpdate() == 1;
|
||||
} catch (SQLException failure) {
|
||||
logFailure(failure);
|
||||
return false;
|
||||
PlaceHolders publication = beginPointPublication(user);
|
||||
// Classify this arithmetic statement; an earlier uncertain operation stays fenced.
|
||||
boolean known = true;
|
||||
try {
|
||||
drainCache(user, points);
|
||||
MySQL table = plugin.getMysql();
|
||||
StringBuilder sql = new StringBuilder("UPDATE ").append(table.qi(table.getTableName())).append(" SET ")
|
||||
.append(table.qi(points)).append(" = COALESCE(").append(table.qi(points)).append(", 0) + ? WHERE ")
|
||||
.append(table.qi("uuid")).append(table.getDbType() == DbType.POSTGRESQL ? " = ?::uuid" : " = ?");
|
||||
if (requireNonnegative) {
|
||||
sql.append(" AND COALESCE(").append(table.qi(points)).append(", 0) >= ?");
|
||||
}
|
||||
try (Connection connection = requireConnection(table);
|
||||
PreparedStatement statement = connection.prepareStatement(sql.toString())) {
|
||||
statement.setInt(1, delta);
|
||||
statement.setString(2, user.getUUID());
|
||||
if (requireNonnegative) statement.setInt(3, -delta);
|
||||
known = false;
|
||||
int affected = statement.executeUpdate();
|
||||
known = true;
|
||||
return affected == 1;
|
||||
} catch (SQLException failure) {
|
||||
logFailure(failure);
|
||||
return false;
|
||||
}
|
||||
} finally {
|
||||
discardPointsCache(user, points);
|
||||
boolean refreshed = SharedMysqlCacheReconciler.tryInvalidateAndRefreshOnWorker(plugin, user.getUUID(), points);
|
||||
finishPointPublication(publication, user, points, known, refreshed);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -946,53 +1047,74 @@ final class SharedMysqlPointMutator {
|
||||
}
|
||||
|
||||
private AddResult addAndReadCommittedResult(VotingPluginUser user, int amount, String points) {
|
||||
drainCache(user, points);
|
||||
MySQL table = plugin.getMysql();
|
||||
String uuidMatch = table.qi("uuid") + (table.getDbType() == DbType.POSTGRESQL ? " = ?::uuid" : " = ?");
|
||||
String update = "UPDATE " + table.qi(table.getTableName()) + " SET " + table.qi(points) + " = COALESCE("
|
||||
+ table.qi(points) + ", 0) + ? WHERE " + uuidMatch;
|
||||
String read = "SELECT " + table.qi(points) + " FROM " + table.qi(table.getTableName()) + " WHERE " + uuidMatch;
|
||||
boolean updateCommitted = false;
|
||||
Integer committedTotal = null;
|
||||
try (Connection connection = requireConnection(table);
|
||||
PreparedStatement updateStatement = connection.prepareStatement(update);
|
||||
PreparedStatement readStatement = connection.prepareStatement(read)) {
|
||||
updateStatement.setInt(1, amount);
|
||||
updateStatement.setString(2, user.getUUID());
|
||||
if (updateStatement.executeUpdate() == 1) {
|
||||
// With JDBC auto-commit, executeUpdate returning one means the mutation
|
||||
// completed. A later read may still fail after the points have been
|
||||
// committed, so never turn that outcome into a retryable failure.
|
||||
updateCommitted = true;
|
||||
readStatement.setString(1, user.getUUID());
|
||||
try (java.sql.ResultSet result = readStatement.executeQuery()) {
|
||||
if (result.next()) committedTotal = result.getInt(1);
|
||||
}
|
||||
PlaceHolders publication = beginPointPublication(user);
|
||||
// Classify this arithmetic statement; an earlier uncertain operation stays fenced.
|
||||
boolean known = true;
|
||||
boolean refreshed = false;
|
||||
try {
|
||||
try {
|
||||
drainCache(user, points);
|
||||
} catch (RuntimeException preparationFailure) {
|
||||
// No arithmetic statement was submitted. Cache retirement may itself
|
||||
// perform I/O; its failure is not proof this addition ran.
|
||||
plugin.debug(preparationFailure);
|
||||
return new AddResult(MutationOutcome.REJECTED, 0);
|
||||
}
|
||||
} catch (SQLException failure) {
|
||||
logFailure(failure);
|
||||
MySQL table = plugin.getMysql();
|
||||
String uuidMatch = table.qi("uuid") + (table.getDbType() == DbType.POSTGRESQL ? " = ?::uuid" : " = ?");
|
||||
String update = "UPDATE " + table.qi(table.getTableName()) + " SET " + table.qi(points) + " = COALESCE("
|
||||
+ table.qi(points) + ", 0) + ? WHERE " + uuidMatch;
|
||||
String read = "SELECT " + table.qi(points) + " FROM " + table.qi(table.getTableName()) + " WHERE " + uuidMatch;
|
||||
boolean updateCommitted = false;
|
||||
Integer committedTotal = null;
|
||||
try (Connection connection = requireConnection(table);
|
||||
PreparedStatement updateStatement = connection.prepareStatement(update);
|
||||
PreparedStatement readStatement = connection.prepareStatement(read)) {
|
||||
updateStatement.setInt(1, amount);
|
||||
updateStatement.setString(2, user.getUUID());
|
||||
known = false;
|
||||
int affected = updateStatement.executeUpdate();
|
||||
known = true;
|
||||
if (affected == 1) {
|
||||
// With JDBC auto-commit, executeUpdate returning one means the mutation
|
||||
// completed. A later read may still fail after the points have been
|
||||
// committed, so never turn that outcome into a retryable failure.
|
||||
updateCommitted = true;
|
||||
readStatement.setString(1, user.getUUID());
|
||||
try (java.sql.ResultSet result = readStatement.executeQuery()) {
|
||||
if (result.next()) committedTotal = result.getInt(1);
|
||||
}
|
||||
}
|
||||
} catch (SQLException failure) {
|
||||
logFailure(failure);
|
||||
} finally {
|
||||
refreshed = SharedMysqlCacheReconciler.tryInvalidateAndRefreshOnWorker(plugin, user.getUUID(), points);
|
||||
}
|
||||
// Do not evaluate the fallback while the JDBC handle is still held. With a
|
||||
// one-connection pool, getPoints() may need that same handle after a missing
|
||||
// row or a failed follow-up read.
|
||||
if (committedTotal != null) return new AddResult(true, committedTotal);
|
||||
// A failed acquisition cannot support the fallback read either. Report the
|
||||
// mutation failure without checking out a second connection and let callers
|
||||
// complete their callback deterministically.
|
||||
if (!updateCommitted) return new AddResult(known ? MutationOutcome.REJECTED : MutationOutcome.INDETERMINATE, 0);
|
||||
// A live mode reload can change getPointsPath() while this queued write is
|
||||
// running. Keep the fallback on the column that received the credit.
|
||||
if (!points.equals(user.getPointsPath())) return new AddResult(true, user.getUserData().getInt(points));
|
||||
return new AddResult(true, user.getPoints());
|
||||
} finally {
|
||||
discardPointsCache(user, points);
|
||||
finishPointPublication(publication, user, points, known, refreshed);
|
||||
}
|
||||
// Do not evaluate the fallback while the JDBC handle is still held. With a
|
||||
// one-connection pool, getPoints() may need that same handle after a missing
|
||||
// row or a failed follow-up read.
|
||||
if (committedTotal != null) return new AddResult(true, committedTotal);
|
||||
// A failed acquisition cannot support the fallback read either. Report the
|
||||
// mutation failure without checking out a second connection and let callers
|
||||
// complete their callback deterministically.
|
||||
if (!updateCommitted) return new AddResult(false, 0);
|
||||
// A live mode reload can change getPointsPath() while this queued write is
|
||||
// running. Keep the fallback on the column that received the credit.
|
||||
if (!points.equals(user.getPointsPath())) return new AddResult(true, user.getUserData().getInt(points));
|
||||
return new AddResult(true, user.getPoints());
|
||||
}
|
||||
|
||||
enum MutationOutcome { CONFIRMED, REJECTED, INDETERMINATE }
|
||||
|
||||
record AddResult(MutationOutcome outcome, int total) {
|
||||
record AddResult(MutationOutcome outcome, int total, boolean sourceRefreshed) {
|
||||
AddResult(MutationOutcome outcome, int total) {
|
||||
this(outcome, total, false);
|
||||
}
|
||||
AddResult(boolean success, int total) {
|
||||
this(success ? MutationOutcome.CONFIRMED : MutationOutcome.INDETERMINATE, total);
|
||||
this(success ? MutationOutcome.CONFIRMED : MutationOutcome.INDETERMINATE, total, false);
|
||||
}
|
||||
boolean success() { return outcome == MutationOutcome.CONFIRMED; }
|
||||
}
|
||||
@@ -1002,21 +1124,29 @@ final class SharedMysqlPointMutator {
|
||||
}
|
||||
|
||||
private boolean setAbsolute(VotingPluginUser user, int value, String points) {
|
||||
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;
|
||||
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;
|
||||
}
|
||||
} finally {
|
||||
discardPointsCache(user, points);
|
||||
boolean refreshed = SharedMysqlCacheReconciler.tryInvalidateAndRefreshOnWorker(plugin, user.getUUID(), points);
|
||||
finishPointPublication(publication, user, points, known, refreshed);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1025,20 +1155,28 @@ final class SharedMysqlPointMutator {
|
||||
}
|
||||
|
||||
private void capAt(VotingPluginUser user, int maximum, String points) {
|
||||
drainCache(user, points);
|
||||
MySQL table = plugin.getMysql();
|
||||
String sql = "UPDATE " + table.qi(table.getTableName()) + " SET " + table.qi(points) + " = LEAST(COALESCE("
|
||||
+ table.qi(points) + ", 0), ?) WHERE " + table.qi("uuid")
|
||||
+ (table.getDbType() == DbType.POSTGRESQL ? " = ?::uuid" : " = ?");
|
||||
try (Connection connection = requireConnection(table);
|
||||
PreparedStatement statement = connection.prepareStatement(sql)) {
|
||||
statement.setInt(1, maximum);
|
||||
statement.setString(2, user.getUUID());
|
||||
statement.executeUpdate();
|
||||
} catch (SQLException failure) {
|
||||
logFailure(failure);
|
||||
PlaceHolders publication = beginPointPublication(user);
|
||||
// Classify this arithmetic statement; an earlier uncertain operation stays fenced.
|
||||
boolean known = true;
|
||||
try {
|
||||
drainCache(user, points);
|
||||
MySQL table = plugin.getMysql();
|
||||
String sql = "UPDATE " + table.qi(table.getTableName()) + " SET " + table.qi(points) + " = LEAST(COALESCE("
|
||||
+ table.qi(points) + ", 0), ?) WHERE " + table.qi("uuid")
|
||||
+ (table.getDbType() == DbType.POSTGRESQL ? " = ?::uuid" : " = ?");
|
||||
try (Connection connection = requireConnection(table);
|
||||
PreparedStatement statement = connection.prepareStatement(sql)) {
|
||||
statement.setInt(1, maximum);
|
||||
statement.setString(2, user.getUUID());
|
||||
known = false;
|
||||
statement.executeUpdate();
|
||||
known = true;
|
||||
} catch (SQLException failure) {
|
||||
logFailure(failure);
|
||||
}
|
||||
} finally {
|
||||
discardPointsCache(user, points);
|
||||
boolean refreshed = SharedMysqlCacheReconciler.tryInvalidateAndRefreshOnWorker(plugin, user.getUUID(), points);
|
||||
finishPointPublication(publication, user, points, known, refreshed);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1047,21 +1185,29 @@ final class SharedMysqlPointMutator {
|
||||
}
|
||||
|
||||
private void addAndCapAt(VotingPluginUser user, int amount, int maximum, String points) {
|
||||
drainCache(user, points);
|
||||
MySQL table = plugin.getMysql();
|
||||
String sql = "UPDATE " + table.qi(table.getTableName()) + " SET " + table.qi(points) + " = LEAST(COALESCE("
|
||||
+ table.qi(points) + ", 0) + ?, ?) WHERE " + table.qi("uuid")
|
||||
+ (table.getDbType() == DbType.POSTGRESQL ? " = ?::uuid" : " = ?");
|
||||
try (Connection connection = requireConnection(table);
|
||||
PreparedStatement statement = connection.prepareStatement(sql)) {
|
||||
statement.setInt(1, amount);
|
||||
statement.setInt(2, maximum);
|
||||
statement.setString(3, user.getUUID());
|
||||
statement.executeUpdate();
|
||||
} catch (SQLException failure) {
|
||||
logFailure(failure);
|
||||
PlaceHolders publication = beginPointPublication(user);
|
||||
// Classify this arithmetic statement; an earlier uncertain operation stays fenced.
|
||||
boolean known = true;
|
||||
try {
|
||||
drainCache(user, points);
|
||||
MySQL table = plugin.getMysql();
|
||||
String sql = "UPDATE " + table.qi(table.getTableName()) + " SET " + table.qi(points) + " = LEAST(COALESCE("
|
||||
+ table.qi(points) + ", 0) + ?, ?) WHERE " + table.qi("uuid")
|
||||
+ (table.getDbType() == DbType.POSTGRESQL ? " = ?::uuid" : " = ?");
|
||||
try (Connection connection = requireConnection(table);
|
||||
PreparedStatement statement = connection.prepareStatement(sql)) {
|
||||
statement.setInt(1, amount);
|
||||
statement.setInt(2, maximum);
|
||||
statement.setString(3, user.getUUID());
|
||||
known = false;
|
||||
statement.executeUpdate();
|
||||
known = true;
|
||||
} catch (SQLException failure) {
|
||||
logFailure(failure);
|
||||
}
|
||||
} finally {
|
||||
discardPointsCache(user, points);
|
||||
boolean refreshed = SharedMysqlCacheReconciler.tryInvalidateAndRefreshOnWorker(plugin, user.getUUID(), points);
|
||||
finishPointPublication(publication, user, points, known, refreshed);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1101,6 +1247,27 @@ 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());
|
||||
}
|
||||
|
||||
+101
-74
@@ -28,6 +28,14 @@ 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";
|
||||
/*
|
||||
@@ -144,51 +152,59 @@ final class SharedPointTransferJournal {
|
||||
*/
|
||||
boolean reserve(String transferId, String sourceUuid, String sourcePointsColumn, int debitPoints, String targetUuid,
|
||||
int requestedCreditPoints, long now) throws SQLException {
|
||||
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();
|
||||
|
||||
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;
|
||||
boolean pointWriteAttempted = false;
|
||||
try {
|
||||
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();
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
} catch (SQLException failure) {
|
||||
if (failure instanceof PreparationFailure) throw failure;
|
||||
if (!pointWriteAttempted) throw new PreparationFailure(failure);
|
||||
throw failure;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -286,42 +302,50 @@ final class SharedPointTransferJournal {
|
||||
*/
|
||||
boolean refundReserved(String transferId, String sourceUuid, String sourcePointsColumn, int debitPoints)
|
||||
throws SQLException {
|
||||
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))) {
|
||||
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) {
|
||||
connection.rollback();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
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);
|
||||
}
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -340,6 +364,7 @@ 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)) {
|
||||
@@ -363,6 +388,7 @@ 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;
|
||||
@@ -378,6 +404,7 @@ final class SharedPointTransferJournal {
|
||||
}
|
||||
return commitAndConfirm(connection, transferId, REFUNDED);
|
||||
} catch (SQLException failure) {
|
||||
if (!pointWriteAttempted) throw new PreparationFailure(failure);
|
||||
throw failure;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,11 @@ package com.bencodez.votingplugin.user;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.UUID;
|
||||
import java.util.UUID;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
import com.bencodez.votingplugin.placeholders.PlaceholderPlayerPresence.LiveIdentity;
|
||||
|
||||
import org.bukkit.OfflinePlayer;
|
||||
import org.bukkit.entity.Player;
|
||||
@@ -22,7 +26,8 @@ import com.bencodez.votingplugin.topvoter.TopVoter;
|
||||
* Manages VotingPlugin user operations and data.
|
||||
*/
|
||||
public class UserManager {
|
||||
private VotingPluginMain plugin;
|
||||
private VotingPluginMain plugin;
|
||||
private final Set<UUID> warnedOfflineUuidPlayers = ConcurrentHashMap.newKeySet();
|
||||
private boolean sharedPointTransferRecoveryScheduled;
|
||||
|
||||
/**
|
||||
@@ -257,18 +262,50 @@ 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) {
|
||||
return new VotingPluginUser(plugin, 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;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a VotingPluginUser by UUID with optional name loading.
|
||||
* 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.
|
||||
* @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);
|
||||
@@ -285,6 +322,24 @@ 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.
|
||||
*/
|
||||
|
||||
+2189
-1971
File diff suppressed because it is too large.
Load diff
+13
@@ -18,6 +18,19 @@ public final class BukkitCompletionScheduler {
|
||||
public static boolean isSuccessfulEntityTaskResult(Object status) {
|
||||
return status instanceof Enum<?> result && "SUCCESS".equals(result.name());
|
||||
}
|
||||
|
||||
/** Event flags are not a reliable execution-context check, including Folia region threads. */
|
||||
public static boolean isPlatformOwnedThread() {
|
||||
try { if (org.bukkit.Bukkit.isPrimaryThread()) return true; } catch (RuntimeException ignored) { }
|
||||
Object server = org.bukkit.Bukkit.getServer();
|
||||
if (server != null) try {
|
||||
if (Boolean.TRUE.equals(server.getClass().getMethod("isGlobalTickThread").invoke(server))) return true;
|
||||
} catch (ReflectiveOperationException | RuntimeException ignored) { }
|
||||
for (String name : new String[] { "ca.spottedleaf.moonrise.common.util.TickThread", "io.papermc.paper.util.TickThread" }) try {
|
||||
if (Boolean.TRUE.equals(Class.forName(name).getMethod("isTickThread").invoke(null))) return true;
|
||||
} catch (ReflectiveOperationException | LinkageError | RuntimeException ignored) { }
|
||||
return false;
|
||||
}
|
||||
private BukkitCompletionScheduler() {
|
||||
}
|
||||
|
||||
|
||||
+217
@@ -0,0 +1,217 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
+26
-19
@@ -7,7 +7,6 @@ public final class ServiceSiteValidator {
|
||||
/** Maximum accepted UTF-16 length for a service-site identifier. */
|
||||
public static final int MAX_LENGTH = 2048;
|
||||
private static final int MAX_LOG_LENGTH = 128;
|
||||
private static final String FORMATTING_BOUNDARY = "\u2060";
|
||||
|
||||
private ServiceSiteValidator() {
|
||||
}
|
||||
@@ -17,9 +16,18 @@ public final class ServiceSiteValidator {
|
||||
*
|
||||
* @param serviceSite service-site name supplied by a vote source
|
||||
* @return {@code true} for a bounded, visible service-site name that does not
|
||||
* contain structural formatting delimiters or control characters
|
||||
* contain unsupported delimiters
|
||||
*/
|
||||
public static boolean isValid(String serviceSite) {
|
||||
return isValid(serviceSite, false);
|
||||
}
|
||||
|
||||
/** Bounded legacy identifier validation; only use for an already-configured site. */
|
||||
public static boolean isValidConfiguredLegacyIdentifier(String serviceSite) {
|
||||
return isValid(serviceSite, true);
|
||||
}
|
||||
|
||||
private static boolean isValid(String serviceSite, boolean allowLegacyDelimiters) {
|
||||
if (serviceSite == null || serviceSite.length() > MAX_LENGTH) {
|
||||
return false;
|
||||
}
|
||||
@@ -27,7 +35,7 @@ public final class ServiceSiteValidator {
|
||||
boolean hasVisibleCharacter = false;
|
||||
for (int offset = 0; offset < serviceSite.length();) {
|
||||
int codePoint = serviceSite.codePointAt(offset);
|
||||
if (isDisallowed(codePoint)) {
|
||||
if (isDisallowed(codePoint) && !(allowLegacyDelimiters && isLegacyDelimiter(codePoint))) {
|
||||
return false;
|
||||
}
|
||||
if (isVisibleBaseCharacter(codePoint)) {
|
||||
@@ -66,27 +74,26 @@ public final class ServiceSiteValidator {
|
||||
return sanitized.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Keeps a validated external identifier visually unchanged while preventing a
|
||||
* surrounding trusted template from completing a formatting token across a
|
||||
* substitution boundary.
|
||||
*/
|
||||
/** Display-only representation; raw identifiers remain authoritative for matching/actions.
|
||||
* Uses printable ASCII labels and space boundaries rather than font-dependent guards.
|
||||
* Boundaries prevent surrounding template text from completing interpreter tokens. */
|
||||
public static String inertForFormatting(String value) {
|
||||
if (value == null || value.isEmpty()) return value == null ? "" : value;
|
||||
StringBuilder inert = new StringBuilder(value.length() + 2).append(FORMATTING_BOUNDARY);
|
||||
for (int offset = 0; offset < value.length();) {
|
||||
int codePoint = value.codePointAt(offset);
|
||||
inert.appendCodePoint(codePoint);
|
||||
if (codePoint == '%' || codePoint == '&') inert.append(FORMATTING_BOUNDARY);
|
||||
offset += Character.charCount(codePoint);
|
||||
}
|
||||
return inert.append(FORMATTING_BOUNDARY).toString();
|
||||
if (value == null || value.isEmpty()) return "";
|
||||
return " " + value.replace("&", "(ampersand)").replace("%", "(percent)")
|
||||
.replace("§", "(section)").replace("{", "(open brace)").replace("}", "(close brace)")
|
||||
.replace("[", "(open bracket)").replace("]", "(close bracket)")
|
||||
.replace("\"", "(double quote)").replace("'", "(quote)")
|
||||
.replace("`", "(backtick)").replace("\\", "(backslash)") + " ";
|
||||
}
|
||||
|
||||
private static boolean isLegacyDelimiter(int codePoint) {
|
||||
return codePoint == '[' || codePoint == ']' || codePoint == '\'' || codePoint == '"'
|
||||
|| codePoint == '`' || codePoint == '\\' || codePoint == '\u00A7';
|
||||
}
|
||||
|
||||
private static boolean isDisallowed(int codePoint) {
|
||||
if (codePoint == '[' || codePoint == ']' || codePoint == '\'' || codePoint == '"' || codePoint == '`'
|
||||
|| codePoint == '\u00A7'
|
||||
|| codePoint == '\\' || codePoint == '{' || codePoint == '}') {
|
||||
|| codePoint == '\\' || codePoint == '\u00A7') {
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@@ -13,11 +13,12 @@ public final class VoteTaskAdmission {
|
||||
/**
|
||||
* Attempts to submit a one-shot vote task without running it on the caller.
|
||||
*
|
||||
* @param executor bounded vote executor
|
||||
* @param executor bounded vote executor, or null before startup/after shutdown
|
||||
* @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;
|
||||
@@ -29,13 +30,14 @@ public final class VoteTaskAdmission {
|
||||
/**
|
||||
* Attempts to schedule a one-shot vote task without blocking the caller.
|
||||
*
|
||||
* @param executor bounded vote executor
|
||||
* @param executor bounded vote executor, or null before startup/after shutdown
|
||||
* @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;
|
||||
|
||||
+1
-4
@@ -7,7 +7,6 @@ import org.bukkit.event.EventPriority;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.player.PlayerQuitEvent;
|
||||
|
||||
import com.bencodez.advancedcore.api.rewards.RewardDisplayPlaceholders;
|
||||
import com.bencodez.advancedcore.listeners.AdvancedCoreLoginEvent;
|
||||
import com.bencodez.votingplugin.VotingPluginMain;
|
||||
import com.bencodez.votingplugin.events.PlayerPostVoteEvent;
|
||||
@@ -38,8 +37,7 @@ public class VoteRemindersListener implements Listener {
|
||||
*/
|
||||
@EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR)
|
||||
public void onPostVote(PlayerPostVoteEvent event) {
|
||||
plugin.getVoteRemindersManager().onVoteCast(event.getUser(), event.getVoteSite().getDisplayName(),
|
||||
event.getVoteSite().getDisplayNameForFormatting());
|
||||
plugin.getVoteRemindersManager().onVoteCast(event.getUser(), event.getVoteSite().getDisplayName());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -84,7 +82,6 @@ public class VoteRemindersListener implements Listener {
|
||||
public void onCoolDownEnd(PlayerVoteSiteCoolDownEndEvent event) {
|
||||
HashMap<String, String> placeholders = new HashMap<>();
|
||||
placeholders.put("votesite", event.getSite().getDisplayName());
|
||||
RewardDisplayPlaceholders.put(placeholders, "votesite", event.getSite().getDisplayNameForFormatting());
|
||||
placeholders.put("votesite_id", event.getSite().getKey());
|
||||
plugin.getVoteRemindersManager().onCooldownTrigger(event.getPlayer(), VoteReminderType.COOLDOWN_END_ANY_SITE,
|
||||
placeholders);
|
||||
|
||||
+5
-6
@@ -26,7 +26,6 @@ import org.bukkit.Bukkit;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
import com.bencodez.advancedcore.api.rewards.RewardBuilder;
|
||||
import com.bencodez.advancedcore.api.rewards.RewardDisplayPlaceholders;
|
||||
import com.bencodez.simpleapi.time.ParsedDuration;
|
||||
import com.bencodez.votingplugin.VotingPluginMain;
|
||||
import com.bencodez.votingplugin.user.VotingPluginUser;
|
||||
@@ -488,10 +487,6 @@ public final class VoteRemindersManager {
|
||||
}
|
||||
|
||||
public void onVoteCast(VotingPluginUser user, String siteKey) {
|
||||
onVoteCast(user, siteKey, siteKey);
|
||||
}
|
||||
|
||||
public void onVoteCast(VotingPluginUser user, String siteKey, String displaySite) {
|
||||
if (!isEnabled() || user == null) {
|
||||
return;
|
||||
}
|
||||
@@ -507,13 +502,17 @@ public final class VoteRemindersManager {
|
||||
HashMap<String, String> ph = new HashMap<>();
|
||||
if (siteKey != null && !siteKey.isEmpty()) {
|
||||
ph.put("site", siteKey);
|
||||
RewardDisplayPlaceholders.put(ph, "site", displaySite);
|
||||
}
|
||||
|
||||
queueTrigger(user, VoteReminderType.VOTE_CAST, ph);
|
||||
flushSoon(user.getJavaUUID(), user.getPlayerName());
|
||||
}
|
||||
|
||||
/** Compatibility overload; reminders use the original release site value. */
|
||||
public void onVoteCast(VotingPluginUser user, String siteKey, String displaySite) {
|
||||
onVoteCast(user, siteKey);
|
||||
}
|
||||
|
||||
public void onCooldownTrigger(VotingPluginUser user, VoteReminderType type, Map<String, String> placeholders) {
|
||||
if (!isEnabled() || user == null) {
|
||||
return;
|
||||
|
||||
+153
-121
@@ -29,6 +29,14 @@ 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";
|
||||
@@ -119,60 +127,68 @@ 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 {
|
||||
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);
|
||||
if (debitStatement.executeUpdate() != 1) {
|
||||
rollback(connection);
|
||||
return false;
|
||||
}
|
||||
return commitAndConfirm(connection, purchaseId, PENDING);
|
||||
}
|
||||
} catch (SQLException failure) {
|
||||
rollback(connection);
|
||||
throw failure;
|
||||
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();
|
||||
|
||||
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);
|
||||
}
|
||||
} catch (SQLException failure) {
|
||||
rollback(connection);
|
||||
throw failure;
|
||||
}
|
||||
}
|
||||
} catch (SQLException failure) {
|
||||
if (failure instanceof PreparationFailure) throw failure;
|
||||
if (!pointWriteAttempted) throw new PreparationFailure(failure);
|
||||
throw failure;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -370,65 +386,73 @@ final class SharedMysqlPurchaseJournal {
|
||||
private RefundedPurchase setTerminalDetails(String purchaseId, String terminalState, long now,
|
||||
String... refundableStates)
|
||||
throws SQLException {
|
||||
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));
|
||||
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) {
|
||||
rollback(connection);
|
||||
return null;
|
||||
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) {
|
||||
throw failure;
|
||||
}
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -442,20 +466,28 @@ final class SharedMysqlPurchaseJournal {
|
||||
|
||||
private void refund(Connection connection, String uuid, String pointsColumn, String limitColumn, int cost,
|
||||
boolean refundLimit) throws SQLException {
|
||||
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");
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+68
-36
@@ -186,15 +186,24 @@ 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;
|
||||
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()));
|
||||
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);
|
||||
}
|
||||
if (debit.result() != VoteShopPurchaseResult.SUCCESS) {
|
||||
completePurchaseResult(player, completion, debit.result());
|
||||
@@ -207,6 +216,7 @@ public class VoteShopPurchaseService {
|
||||
}
|
||||
});
|
||||
} catch (RuntimeException persistenceRejected) {
|
||||
if (admission != null) admission.accept(false);
|
||||
plugin.debug(persistenceRejected);
|
||||
completeFailedPurchase(player, completion);
|
||||
}
|
||||
@@ -479,20 +489,29 @@ 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 {
|
||||
if (debit.journal().refundCompensatingReward(debit.purchaseId())) {
|
||||
refreshPurchaseCache(user, debit.pointsColumn(), debit.limitColumn());
|
||||
}
|
||||
debit.journal().refundCompensatingReward(debit.purchaseId());
|
||||
known = true;
|
||||
} 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -738,37 +757,50 @@ public class VoteShopPurchaseService {
|
||||
|
||||
private SharedPurchaseDebit reserveSharedMysqlPurchase(VotingPluginUser user, VoteShopItem item,
|
||||
LimitGeneration limitGeneration) {
|
||||
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);
|
||||
}
|
||||
var publication = plugin.getPlaceholders();
|
||||
UUID pointUuid = UUID.fromString(user.getUUID());
|
||||
if (publication != null) publication.beginSharedPointDebit(pointUuid);
|
||||
boolean known = true;
|
||||
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);
|
||||
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);
|
||||
}
|
||||
} 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);
|
||||
} finally {
|
||||
if (publication != null) publication.finishSharedPointDebit(pointUuid, known, false);
|
||||
}
|
||||
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. */
|
||||
|
||||
@@ -12,7 +12,6 @@ import com.bencodez.simpleapi.messages.MessageAPI;
|
||||
import com.bencodez.simpleapi.time.ParsedDuration;
|
||||
import com.bencodez.votingplugin.VotingPluginMain;
|
||||
import com.bencodez.votingplugin.user.VotingPluginUser;
|
||||
import com.bencodez.votingplugin.util.ServiceSiteValidator;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
@@ -20,7 +19,6 @@ import lombok.Setter;
|
||||
public class VoteSite {
|
||||
@Getter
|
||||
private String displayName;
|
||||
private boolean displayNameFallback;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@@ -159,12 +157,9 @@ public class VoteSite {
|
||||
|
||||
private RewardBuilder createRewardBuilder(String path, boolean online, boolean bungee) {
|
||||
// Reward placeholders also feed commands and other exact-value actions. The
|
||||
// service identifier is already validated at ingress, so preserve it here;
|
||||
// display-only callers use getServiceSiteForFormatting() instead.
|
||||
// service identifier is already validated at ingress, so preserve it here.
|
||||
return new RewardBuilder(plugin.getConfigVoteSites().getData(), path).setOnline(online)
|
||||
.withPlaceHolder("ServiceSite", getServiceSite()).withPlaceHolder("SiteName", getDisplayName())
|
||||
.withDisplayPlaceHolder("ServiceSite", getServiceSiteForFormatting())
|
||||
.withDisplayPlaceHolder("SiteName", getDisplayNameForFormatting())
|
||||
.withPlaceHolder("VoteDelay", "" + getVoteDelay()).withPlaceHolder("VoteURL", getVoteURL())
|
||||
.setServer(bungee);
|
||||
}
|
||||
@@ -174,22 +169,21 @@ public class VoteSite {
|
||||
plugin.getConfigVoteSites().getRewardsPath(key));
|
||||
}
|
||||
|
||||
/** Returns the configured service identifier guarded for trusted templates. */
|
||||
/** Compatibility accessor returning the unchanged release formatting input. */
|
||||
public String getServiceSiteForFormatting() {
|
||||
return ServiceSiteValidator.inertForFormatting(getServiceSite());
|
||||
return getServiceSite();
|
||||
}
|
||||
|
||||
/** Sets an administrator-controlled display name. */
|
||||
public void setDisplayName(String displayName) {
|
||||
this.displayName = displayName;
|
||||
this.displayNameFallback = false;
|
||||
}
|
||||
|
||||
/** Returns the site label guarded only when it falls back to an external site key. */
|
||||
/** Returns the configured or fallback label without additional formatting guards. */
|
||||
public String getDisplayNameForFormatting() {
|
||||
return displayNameFallback ? ServiceSiteValidator.inertForFormatting(getDisplayName()) : getDisplayName();
|
||||
return getDisplayName();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Inits the.
|
||||
*/
|
||||
@@ -200,8 +194,7 @@ public class VoteSite {
|
||||
setEnabled(plugin.getConfigVoteSites().getVoteSiteEnabled(key));
|
||||
setPriority(plugin.getConfigVoteSites().getPriority(key));
|
||||
displayName = plugin.getConfigVoteSites().getDisplayName(key);
|
||||
displayNameFallback = displayName == null || displayName.equals("");
|
||||
if (displayNameFallback) {
|
||||
if (displayName == null || displayName.equals("")) {
|
||||
displayName = key;
|
||||
}
|
||||
item = plugin.getConfigVoteSites().getItem(key);
|
||||
|
||||
@@ -188,6 +188,7 @@ 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
|
||||
@@ -196,9 +197,12 @@ AutoCreateVoteSites: true
|
||||
# https://github.com/BenCodez/VotingPlugin/wiki/Bedrock-Player-Support
|
||||
BedrockPlayerPrefix: '.'
|
||||
|
||||
# If false plugin will use offline player UUIDs
|
||||
# Keep enabled when mixing UUIDs (Premium and cracked)
|
||||
# More info: https://github.com/BenCodez/VotingPlugin/wiki/Online-Offline-Mode
|
||||
# Controls how VotingPlugin resolves player UUIDs.
|
||||
# true: Use Mojang-authenticated UUIDs (premium-only servers).
|
||||
# false: Use name-based offline UUIDs (cracked or mixed premium/cracked servers).
|
||||
# Use the same setting on all servers sharing VotingPlugin data, including proxies.
|
||||
# Changing this setting on an existing server may require migrating player data.
|
||||
# More info: https://wiki.bencodez.com/en/VotingPlugin/Online-Offline-Mode
|
||||
OnlineMode: true
|
||||
|
||||
# If true, /vote will open /vote gui by default
|
||||
@@ -208,6 +212,14 @@ 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
|
||||
@@ -439,6 +451,14 @@ 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:
|
||||
|
||||
@@ -294,6 +294,10 @@ 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
|
||||
|
||||
@@ -397,3 +397,45 @@ DailyAwards:
|
||||
Rewards:
|
||||
Messages:
|
||||
Player: '&aYou came in second place in %TopVoter%!'
|
||||
|
||||
# Owner-defined dated events. This example is DISABLED by default.
|
||||
# Set your own dates/rewards, then enable the event. No automatic recurring reset.
|
||||
# Keep the event ID stable to retain progress; never delete its ledger and reuse it.
|
||||
# After accounting starts, use a NEW ID for changes to dates, timezone, thresholds,
|
||||
# VoteSites or AccountingServer. Unsafe edits are rejected, preserving progress.
|
||||
# DisplayName and Enabled may change without resetting counts.
|
||||
# Full configuration and durability limits: docs/date-vote-milestones.md
|
||||
DateVoteMilestones:
|
||||
example_event:
|
||||
Enabled: false
|
||||
# Count admin/test votes for this event? Existing normal vote policies are unchanged.
|
||||
CountFakeVotes: true
|
||||
DisplayName: 'Example voting event'
|
||||
# Local ISO date-times interpreted in the explicit IANA timezone below.
|
||||
Start: '2026-10-01T00:00:00' # Inclusive: occurrences at this instant count.
|
||||
End: '2026-11-01T00:00:00' # Exclusive: occurrences at this instant do not count.
|
||||
Timezone: 'UTC'
|
||||
# Ledger owner: empty/omitted means local accounting on standalone servers.
|
||||
# With UseBungeecord enabled, empty/omitted disables new date accounting.
|
||||
# Proxy: set the exact, case-sensitive BungeeSettings.yml Server name of ONE
|
||||
# backend, identically on every backend, with identified all-server delivery.
|
||||
# Reward delivery follows the existing reward settings. Keep matching event
|
||||
# IDs and milestone reward sections on backends that may resolve rewards.
|
||||
AccountingServer: ''
|
||||
# Configured VoteSites.yml keys (not service names); empty means all sites.
|
||||
VoteSites: []
|
||||
# Named milestones use At (one count, list, or bounded range) / Every.
|
||||
# Existing numeric keys with Rewards remain supported; see the guide.
|
||||
Milestones:
|
||||
TenVotes:
|
||||
Enabled: true
|
||||
At: 10
|
||||
Rewards:
|
||||
Messages:
|
||||
Player: '&aYou reached 10 votes in %DateVoteEvent%!'
|
||||
TwentyFiveVotes:
|
||||
Enabled: true
|
||||
At: 25
|
||||
Rewards:
|
||||
Messages:
|
||||
Player: '&aYou reached 25 votes in %DateVoteEvent%!'
|
||||
Loaded 100 of 405 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user