Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -21,25 +21,27 @@
* Guild treasuries, held tax, node upkeep, espionage stability and inactive members read once
* on the main thread. DenarEconomy, Dowsing and TLibs character identity refuse reads from
* other threads, so income previews that run async read these instead.
*
* <p>Whose earnings the held tax came from is not captured: no income reads it, and the ledger
* answers it from every tax credit since the last settlement (about 0.65 s a minute on Main).
*/
public final class FrozenReads {
private static final ThreadLocal<FrozenReads> CURRENT = new ThreadLocal<>();

private final Map<String, Long> cents;
private final Map<UUID, Map<UUID, Long>> taxContributors;
private final Map<UUID, Double> nodeUpkeep;
private final Map<String, List<StabilityModifier>> espionage;
private final Set<String> inactive;
private final long capturedAt;

private FrozenReads(
Map<String, Long> cents, Map<UUID, Map<UUID, Long>> taxContributors,
Map<UUID, Double> nodeUpkeep, Map<String, List<StabilityModifier>> espionage,
Set<String> inactive) {
Map<String, Long> cents, Map<UUID, Double> nodeUpkeep,
Map<String, List<StabilityModifier>> espionage, Set<String> inactive, long capturedAt) {
this.cents = Map.copyOf(cents);
this.taxContributors = Map.copyOf(taxContributors);
this.nodeUpkeep = Map.copyOf(nodeUpkeep);
this.espionage = Map.copyOf(espionage);
this.inactive = Set.copyOf(inactive);
this.capturedAt = capturedAt;
}

/**
Expand All @@ -60,7 +62,6 @@ public static FrozenReads capture() {
}
}
Map<String, Long> cents = new HashMap<>();
Map<UUID, Map<UUID, Long>> taxContributors = new HashMap<>();
Map<UUID, Double> nodeUpkeep = new HashMap<>();
for (Guild guild : FactionManager.getAllGuilds()) {
Bank bank = guild == null ? null : guild.getBank();
Expand All @@ -72,13 +73,17 @@ public static FrozenReads capture() {
if (incarnation != null) {
String taxAccount = Denars.guildTax(incarnation);
cents.put(taxAccount, Denars.balance(taxAccount));
taxContributors.put(incarnation, Map.copyOf(Denars.taxContributors(incarnation)));
nodeUpkeep.put(incarnation, Ledger.liveNodeUpkeep(guild));
}
}
// Member shares (stability, upkeep) skip inactive members; whether one is online asks TLibs.
Set<String> inactive = InactivityService.captureInactiveMembers();
return new FrozenReads(cents, taxContributors, nodeUpkeep, espionage, inactive);
return new FrozenReads(cents, nodeUpkeep, espionage, inactive, now);
}

/** When these reads were taken, in epoch milliseconds. */
public long capturedAt() {
return capturedAt;
}

/** Runs the work with these reads standing in for the live state on this thread. */
Expand All @@ -105,12 +110,17 @@ public static long balance(String account) {
return Denars.balance(account);
}

/** Held tax by earning character, frozen with the balance for async previews and settlement. */
/**
* Held tax by earning character, for the ledger menu and settlement. Always live.
*
* @throws IllegalStateException inside {@link #read}, which does not capture it
*/
public static Map<UUID, Long> taxContributors(UUID incarnation) {
if (incarnation == null) return Map.of();
FrozenReads current = CURRENT.get();
return current == null ? Denars.taxContributors(incarnation)
: current.taxContributors.getOrDefault(incarnation, Map.of());
if (CURRENT.get() != null) {
throw new IllegalStateException("Tax contributors are not captured for previews");
}
return Denars.taxContributors(incarnation);
}

/** The frozen node upkeep inside {@link #read}, otherwise the live upkeep. */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,12 +32,13 @@ private BranchIncomePreview() {}

public static final class Prepared {
private final ProvinceManager snapshot;
private final FrozenReads reads = FrozenReads.capture();
private final FrozenReads reads;
private final long inputs = TradeInputs.fingerprint();
private final Map<Object, Estimate> estimates = new ConcurrentHashMap<>();

private Prepared(ProvinceManager snapshot) {
private Prepared(ProvinceManager snapshot, FrozenReads reads) {
this.snapshot = snapshot;
this.reads = reads;
}

/** Main-thread state as it was when this copy was made, for work off the main thread. */
Expand Down Expand Up @@ -96,9 +97,12 @@ public static boolean current(Prepared prepared) {

/** Copy province trade data once. Later estimates only read this copy. */
public static Prepared prepare(ProvinceManager live) {
ProvinceManager snapshot = live.createSnapshotShell();
snapshot.copyAllDataFrom(live);
return new Prepared(snapshot);
return prepare(live, FrozenReads.capture());
}

/** As {@link #prepare(ProvinceManager)}, with reads a flood of the same trade already captured. */
public static Prepared prepare(ProvinceManager live, FrozenReads reads) {
return new Prepared(copy(live), reads);
}

public static double estimate(ProvinceManager live, Guild guild, Branch branch, int levelDelta) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,11 @@ private BackgroundFlood(ProvinceManager live) {
version = live.stateVersion;
}

/** Main-thread state as it was when this flood was prepared; its trade comes from it. */
public FrozenReads reads() {
return reads;
}

/** Stops a run that is no longer wanted at the next guild; it then never adopts. */
public void cancel() {
cancelled = true;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import org.bukkit.persistence.PersistentDataType;

import net.tfminecraft.simplefactions.Cache;
import net.tfminecraft.simplefactions.economy.FrozenReads;
import net.tfminecraft.simplefactions.guild.branch.Branch;
import net.tfminecraft.simplefactions.guild.income.BranchIncomePreview;
import net.tfminecraft.simplefactions.guild.Guild;
Expand Down Expand Up @@ -51,6 +52,10 @@ private record SharedPreview(ProvinceManager manager, BranchIncomePreview.Prepar
private static final long PREVIEW_TTL_MS = 30_000;
private static final long RECALC_DELAY_TICKS = 20;
private SharedPreview preview;
/** Reads of the flood this paint started or installed, for a preview copy made in the same paint. */
private FrozenReads floodReads;
/** Replaced by tests that outlast a preview. */
java.util.function.LongSupplier clock = System::currentTimeMillis;
private org.bukkit.scheduler.BukkitTask pendingRecalc;
private long recalcRuns;
/** The run whose background flood is in flight, or 0. */
Expand Down Expand Up @@ -135,10 +140,14 @@ private void paintBranches(Player player, Guild guild, Inventory i) {

/** Province copy shared by branch previews until the next full recalculation, or for a short while. */
private BranchIncomePreview.Prepared tradePreview() {
long now = System.currentTimeMillis();
long now = clock.getAsLong();
if (preview == null || preview.manager() != manager || now - preview.at() > PREVIEW_TTL_MS
|| !BranchIncomePreview.current(preview.prepared())) {
preview = new SharedPreview(manager, BranchIncomePreview.prepare(manager), now);
// Reads a flood took stand in for a second capture while they are still fresh; the copy
// ages from when they were taken.
preview = floodReads == null || now - floodReads.capturedAt() > PREVIEW_TTL_MS
? new SharedPreview(manager, BranchIncomePreview.prepare(manager), now)
: new SharedPreview(manager, BranchIncomePreview.prepare(manager, floodReads), floodReads.capturedAt());
}
return preview.prepared();
}
Expand All @@ -164,11 +173,14 @@ private void recalculateAfterClicks(Guild guild) {
/**
* One full recalculation off the server thread for a menu just opened, then menus showing the
* guild repaint. Joins a recalculation that is already waiting or running.
*
* @return the reads of the flood started now, or null when none was
*/
private void refreshInBackground(Guild guild) {
private FrozenReads refreshInBackground(Guild guild) {
pendingRepaint.add(guild.getId());
if (pendingRecalc != null || (floodingRun != 0 && floodingRun == recalcRuns)) return;
if (pendingRecalc != null || (floodingRun != 0 && floodingRun == recalcRuns)) return null;
floodInBackground(++recalcRuns, true);
return flooding == null ? null : flooding.reads();
}

/**
Expand All @@ -186,7 +198,7 @@ private void floodInBackground(long run, boolean retry) {
floodingRun = 0;
flooding = null;
live.recalculate();
repaintAfterRecalc();
repaintAfterRecalc(null);
return;
}
floodingRun = run;
Expand Down Expand Up @@ -215,16 +227,33 @@ private void floodInBackground(long run, boolean retry) {
return;
}
live.recalculate();
repaintAfterRecalc(null);
return;
}
repaintAfterRecalc();
repaintAfterRecalc(flood.reads());
});
});
}

private void repaintAfterRecalc() {
/** {@code reads} are those the installed trade was computed from, or null to capture them again. */
private void repaintAfterRecalc(FrozenReads reads) {
java.util.Set<String> guilds = new java.util.HashSet<>(pendingRepaint);
pendingRepaint.clear();
preview = null;
paintWith(reads, () -> repaint(guilds));
}

private void paintWith(FrozenReads reads, Runnable paint) {
FrozenReads outer = floodReads;
floodReads = reads;
try {
paint.run();
} finally {
floodReads = outer;
}
}

private void repaint(java.util.Set<String> guilds) {
for (Player viewer : org.bukkit.Bukkit.getOnlinePlayers()) {
Inventory top = viewer.getOpenInventory().getTopInventory();
if (!(top.getHolder(false) instanceof SFInventoryHolder holder) || holder.getType() != SFGUI.GUILD_VIEW) continue;
Expand Down Expand Up @@ -353,18 +382,17 @@ public void guildView(Player player, Guild guild, Inventory i, boolean refreshId
return;
}
if(manager == null) setProvinceManager(SimpleFactions.getInstance().getProvinceManager());
if(guild.hasCapital()) {
// Trade a guild with no income may be stale, and movement power, civil war and pillage
// read it too. Refresh it off the server thread; the menus repaint when it lands.
if(refreshIdleTrade && guild.getTradeBreakdown().getIncome() == 0) refreshInBackground(guild);
manager.getIncome(guild);
}
// Trade a guild with no income may be stale, and movement power, civil war and pillage
// read it too. Refresh it off the server thread; the menus repaint when it lands.
boolean idle = refreshIdleTrade && guild.hasCapital() && guild.getTradeBreakdown().getIncome() == 0;
FrozenReads reads = idle ? refreshInBackground(guild) : floodReads;
if(guild.hasCapital()) manager.getIncome(guild);
manager.recalculateIfNeeded();
// The menu only reads, but its items ask every guild's net income (the trade breakdown
// ranks all guilds), and each answer read treasuries from SQLite many times over: about
// 185 ms per redraw on Dev. One answer per treasury and one stability report per faction
// hold for one render, as for the chronicle export.
withReadMemos(() -> render(player, guild, i));
paintWith(reads, () -> withReadMemos(() -> render(player, guild, i)));
}

private static void withReadMemos(Runnable reads) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,13 @@
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.CALLS_REAL_METHODS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.when;

import java.time.Instant;
Expand Down Expand Up @@ -52,9 +54,7 @@ class FrozenReadsTest {
private Guild guild;

private org.mockito.MockedStatic<Denars> mockDenars() {
var denars = mockStatic(Denars.class, CALLS_REAL_METHODS);
denars.when(() -> Denars.taxContributors(any())).thenReturn(Map.of());
return denars;
return mockStatic(Denars.class, CALLS_REAL_METHODS);
}

@BeforeEach
Expand Down Expand Up @@ -89,7 +89,6 @@ void asyncReadsUseBalancesCapturedOnTheMainThread() throws Exception {
// Static mocks stay on the test thread, so only the frozen balance can give the worker 12.34.
assertEquals(12.34, CompletableFuture.supplyAsync(() -> frozen.read(() -> guild.getBank().getWealth())).get());
assertEquals(0L, frozen.read(() -> FrozenReads.balance("unknown")));
assertEquals(Map.of(), frozen.read(() -> FrozenReads.taxContributors(UUID.randomUUID())));
assertEquals(Map.of(), FrozenReads.taxContributors(null));
}

Expand All @@ -101,21 +100,25 @@ void asyncCitizenTaxUsesTheHoldingBalanceCapturedOnTheMainThread() throws Except
String holding = Denars.guildTax(guild.getIncarnationId());
FrozenReads frozen;
UUID contributor = UUID.randomUUID();
var contributors = new java.util.HashMap<>(Map.of(contributor, 1000L));
long before = System.currentTimeMillis();
try (var denars = mockDenars()) {
denars.when(() -> Denars.balance(anyString())).thenReturn(0L);
denars.when(() -> Denars.balance(holding)).thenReturn(1234L);
denars.when(() -> Denars.taxContributors(guild.getIncarnationId())).thenReturn(contributors);
denars.when(() -> Denars.taxContributors(guild.getIncarnationId())).thenReturn(Map.of(contributor, 2000L));
frozen = FrozenReads.capture();
// No income reads the names, and each guild's cost a scan of its held tax credits.
denars.verify(() -> Denars.taxContributors(any()), never());
denars.when(() -> Denars.balance(holding)).thenReturn(5000L);
contributors.put(contributor, 2000L);
assertEquals(50.0, ledger.getIncome(Cashflow.CITIZENS));
assertEquals(Map.of(contributor.toString(), 20.0, "Other citizen taxes", 30.0), ledger.getCitizenTaxBreakdown());
}

assertEquals(12.34, CompletableFuture.supplyAsync(() -> frozen.read(() -> ledger.getIncome(Cashflow.CITIZENS))).get());
assertEquals(Map.of(contributor.toString(), 10.0, "Other citizen taxes", 2.34), CompletableFuture
.supplyAsync(() -> frozen.read(ledger::getCitizenTaxBreakdown)).get());
// The names stay live-only: a preview asking for them fails instead of reading the ledger off-thread.
ExecutionException names = assertThrows(ExecutionException.class,
() -> CompletableFuture.supplyAsync(() -> frozen.read(ledger::getCitizenTaxBreakdown)).get());
assertInstanceOf(IllegalStateException.class, names.getCause());
assertTrue(frozen.capturedAt() >= before);
}

@Test
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package net.tfminecraft.simplefactions.guild.income;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
Expand All @@ -23,6 +24,7 @@
import org.junit.jupiter.api.Test;

import net.tfminecraft.simplefactions.Cache;
import net.tfminecraft.simplefactions.economy.FrozenReads;
import net.tfminecraft.simplefactions.enums.GuildModifier;
import net.tfminecraft.simplefactions.enums.Terrain;
import net.tfminecraft.simplefactions.government.proposal.TaxTarget;
Expand Down Expand Up @@ -113,6 +115,25 @@ void upgradeAndDowngradeKeepLiveStateAndMoveIncome() {
verify(guild, never()).getTradeBreakdown();
}

@Test
void aCopyMadeWithAFloodsReadsGivesTheSameEstimates() {
FrozenReads reads = FrozenReads.capture();
BranchIncomePreview.Prepared shared = BranchIncomePreview.prepare(live, reads);
BranchIncomePreview.Prepared own = BranchIncomePreview.prepare(live);
Map<GuildModifier, Double> current = BranchIncomePreview.modifiers(guild);

assertSame(reads, shared.reads());
assertTrue(BranchIncomePreview.current(shared));
for (int delta : new int[] {1, -1}) {
Map<GuildModifier, Double> changed = BranchIncomePreview.adjust(current, branch, branch.getLevel(), delta);
BranchIncomePreview.Estimate expected = own.reads().read(
() -> BranchIncomePreview.estimate(own, guild, current, changed));
assertTrue(expected.own() != 0);
assertEquals(expected, shared.reads().read(
() -> BranchIncomePreview.estimate(shared, guild, current, changed)));
}
}

@Test
void guildTaxMovesIncomeToTheTreasuryWithoutChangingTheRealmTotal() {
BranchIncomePreview.Prepared prepared = BranchIncomePreview.prepare(live);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,7 @@ void backgroundFloodInstallsTheSameTradeAsTheServerThreadFlood() {

ProvinceManager.BackgroundFlood flood = provinces.prepareBackgroundFlood();
flood.run();
org.junit.jupiter.api.Assertions.assertNotNull(flood.reads());
assertEquals(0, trade(22));
assertTrue(provinces.adopt(flood));
assertEquals(8, trade(22), 1e-9);
Expand Down
Loading