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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ Players shape a world of provinces and titles, organise settlements and guilds,

- **Provinces and titles** — govern territories with natural-shaped borders and titles such as duchies and kingdoms.
- **Layered diplomacy** — form alliances, establish subject and overlord relationships, negotiate treaties, and impose trade embargoes.
- **National economies** — manage wealth and taxation, including income moving through relationships between members, nations, and overlords.
- **National economies** — manage wealth and taxation, including income moving through relationships between members, nations, and overlords. A new day, when banks take their daily income and pay upkeep, starts every day at 12:00 CET (Europe/Paris, so CEST in summer). If the server is down at noon, the day settles as soon as it is back up; several missed noons settle as one day.
- **Settlements and guilds** — establish named cities and capitals and organise groups within a nation.
- **Military infrastructure** — construct forts, ports, airports, and train stations; transport networks extend guild trade and production.
- **Espionage** — appoint a Spymaster, keep regiments and vehicles secret, and obtain shared daily intelligence estimates.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -660,7 +660,7 @@ void saveFactionsForShutdown() {
void saveLoadedFactions() {
// An early enable failure must not overwrite partially restored faction state.
if (!FactionManager.isLoaded()) return;
db.saveTimer(FactionManager.getTimer(), FactionManager.getDay());
db.saveTimer(FactionManager.getTimer(), FactionManager.getDay(), FactionManager.lastNewDay);
for (Faction faction : FactionManager.factions) db.saveFaction(faction);
}

Expand Down
34 changes: 17 additions & 17 deletions src/main/java/net/tfminecraft/simplefactions/database/Database.java
Original file line number Diff line number Diff line change
Expand Up @@ -45,34 +45,33 @@
public class Database {

public int getTimer() {
try {
File file = new File("plugins/SimpleFactions/Cache", "data.json");
if (!file.exists()) return 0;
TimerData data = readTimerData();
return data != null ? data.time : 0;
}

TimerData data = JsonUtil.readJson(file, TimerData.class);
return data != null ? data.time : 0;
public int getDay() {
TimerData data = readTimerData();
return data != null ? data.day : 0;
}

} catch (Exception e) {
e.printStackTrace();
return 0;
}
/** Zero when no new day has been settled since new days followed the calendar. */
public long getLastNewDay() {
TimerData data = readTimerData();
return data != null ? data.lastNewDay : 0;
}

public int getDay() {
private TimerData readTimerData() {
try {
File file = new File("plugins/SimpleFactions/Cache", "data.json");
if (!file.exists()) return 0;

TimerData data = JsonUtil.readJson(file, TimerData.class);
return data != null ? data.day : 0;

if (!file.exists()) return null;
return JsonUtil.readJson(file, TimerData.class);
} catch (Exception e) {
e.printStackTrace();
return 0;
return null;
}
}

public void saveTimer(int time, int day) {
public void saveTimer(int time, int day, long lastNewDay) {
try {
File folder = new File("plugins/SimpleFactions/Cache");
if (!folder.exists()) folder.mkdirs();
Expand All @@ -82,6 +81,7 @@ public void saveTimer(int time, int day) {
TimerData data = new TimerData();
data.time = time;
data.day = day;
data.lastNewDay = lastNewDay;

JsonUtil.writeJson(file, data);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,6 @@
public class TimerData {
public int time = 0;
public int day = 0;
/** When the last new day settled, in epoch milliseconds. Zero in files saved before new days followed the calendar. */
public long lastNewDay = 0;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package net.tfminecraft.simplefactions.economy.settlement;

import java.time.Instant;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;

/**
* A new day starts at noon CET (Europe/Paris, so CEST in summer) by the calendar, not after a
* day of server uptime: a crash or a lagging server no longer moves it.
*/
public final class NewDaySchedule {
public static final ZoneId ZONE = ZoneId.of("Europe/Paris");
public static final LocalTime TIME = LocalTime.NOON;

private NewDaySchedule() {}

/** The latest new-day start at or before this instant, in epoch milliseconds. */
public static long latestAtOrBefore(long millis) {
ZonedDateTime at = Instant.ofEpochMilli(millis).atZone(ZONE);
ZonedDateTime start = at.toLocalDate().atTime(TIME).atZone(ZONE);
return (start.isAfter(at) ? start.minusDays(1) : start).toInstant().toEpochMilli();
}

/** The first new-day start after this instant, in epoch milliseconds. */
public static long nextAfter(long millis) {
// plusDays keeps noon local time across a daylight saving change.
return Instant.ofEpochMilli(latestAtOrBefore(millis)).atZone(ZONE).plusDays(1).toInstant().toEpochMilli();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -92,10 +92,14 @@ public RealmSettlementEffects(Path folder, Database database, PlayerEconomyManag
changes.playerIncome.forEach((character, flows) -> flows.forEach((source, amount) ->
economy.getLedger(character).add(PlayerCashflow.valueOf(source), amount)));
TimerData timer = new TimerData();
// The cadence counter runs on through a new day so its hourly and five-minute ticks keep their phase.
timer.time = FactionManager.timer;
timer.day = Math.toIntExact(plan.day() + 1);
// The day settles for the latest noon already passed, so the next one is the coming noon.
timer.lastNewDay = Math.max(FactionManager.lastNewDay, NewDaySchedule.latestAtOrBefore(FactionManager.now()));
DurableJson.write(folder.resolve("Cache/data.json"), timer);
FactionManager.day = Math.max(FactionManager.day, timer.day);
FactionManager.timer = 0;
FactionManager.lastNewDay = timer.lastNewDay;
notices.forEach(Runnable::run);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,5 @@ public void settle(long day) throws IOException {
if (result != Result.APPLIED) throw new IOException("Realm settlement " + day + " remains " + result);
preparation.complete(day);
FactionManager.day = Math.max(FactionManager.day, Math.toIntExact(day + 1));
FactionManager.timer = 0;
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package net.tfminecraft.simplefactions.managers;

import net.tfminecraft.simplefactions.identity.Members;
import net.tfminecraft.simplefactions.economy.settlement.NewDaySchedule;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
Expand Down Expand Up @@ -62,10 +63,13 @@
import net.tfminecraft.denareconomy.enums.Accounts;

public class FactionManager implements Listener{
private static final int DAY_LENGTH_SECONDS = 86400;
/** Seconds of uptime, saved across restarts, for the hourly and five-minute cadences. A new day leaves it alone. */
public static int timer = 0;
/** Completed day rollovers. Counts server uptime, not calendar days. */
/** Completed day rollovers. */
public static int day = 0;
/** When the realm last settled a new day, in epoch milliseconds; see {@link NewDaySchedule}. */
public static long lastNewDay = 0;
private static java.time.Clock clock = java.time.Clock.systemUTC();
private static boolean loaded = false;
/** True while Database.loadFactions is populating the list. See updateAllPrestige. */
public static boolean loading = false;
Expand All @@ -85,8 +89,26 @@ public static int getTimer(){
return timer;
}

public static void useClock(java.time.Clock replacement) {
clock = replacement;
}

public static long now() {
return clock.millis();
}

/** When the next new day starts, in epoch milliseconds. */
public static long getNextNewDay() {
return NewDaySchedule.nextAfter(lastNewDay);
}

/** Zero while a due new day waits to settle. */
public static int getSecondsUntilNewDay() {
return DAY_LENGTH_SECONDS - Math.clamp(timer, 0, DAY_LENGTH_SECONDS);
return (int) Math.max(0L, Math.ceilDiv(getNextNewDay() - now(), 1000L));
}

public static int getDayProgressSeconds() {
return (int) Math.max(0L, (now() - lastNewDay) / 1000L);
}

public static int getDay(){
Expand Down Expand Up @@ -537,7 +559,7 @@ public void time() {
SimpleFactions.getInstance().getVehicleUpkeepService()
.warnBankShortfalls(Bukkit.getOnlinePlayers(), getSecondsUntilNewDay());
}
if (timer >= DAY_LENGTH_SECONDS) settleIncome();
if (now() >= getNextNewDay()) settleIncome();
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}

public void settleIncome() {
Expand All @@ -555,6 +577,9 @@ public void prepare() {
Database database = new Database();
timer = database.getTimer();
day = database.getDay();
lastNewDay = database.getLastNewDay();
// A timer saved before new days followed the calendar: the day in progress began timer seconds ago.
if (lastNewDay <= 0) lastNewDay = NewDaySchedule.latestAtOrBefore(now() - timer * 1000L);
loadRelations();
for (Faction f : factions) {
f.getLawHandler().apply();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public static JsonObject build() {
return ChronicleSnapshot.build(
FactionManager.factions,
FactionManager.getDay(),
FactionManager.getTimer(),
FactionManager.getDayProgressSeconds(),
Instant.now());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -296,7 +296,7 @@ void startupRegistersGameplayAndShutdownSavesLoadedState() throws Exception {
UUID.randomUUID(), "cart-1", "cart", OwnershipMode.PERSONAL, "dock"));
plugin.onDisable();
Database db = dependency("db", Database.class);
verify(db).saveTimer(100, 4);
verify(db).saveTimer(eq(100), eq(4), anyLong());
verify(db).saveFaction(faction);
verify(db).saveWar(war);
verify(dependency("sessionManager", SessionManager.class)).end();
Expand Down Expand Up @@ -497,7 +497,7 @@ void failedStartupDisablesThePluginBeforeStartingRuntimeLoops(String step) throw
verify(dependency("inventoryManager", InventoryManager.class), never()).start();
plugin.onDisable();
assertSavedStateUnchanged(saved);
verify(dependency("db", Database.class), never()).saveTimer(anyInt(), anyInt());
verify(dependency("db", Database.class), never()).saveTimer(anyInt(), anyInt(), anyLong());
verify(dependency("db", Database.class), never()).saveFaction(any());
verify(dependency("db", Database.class), never()).saveWar(any());
scoped(BattlePersistenceService.class).verify(BattlePersistenceService::saveAll, never());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ class SimpleFactionsShutdownTest {
manager.when(FactionManager::getTimer).thenReturn(100);
manager.when(FactionManager::getDay).thenReturn(4);
plugin.saveLoadedFactions();
verify(database).saveTimer(100, 4);
verify(database).saveTimer(100, 4, FactionManager.lastNewDay);
verify(database).saveFaction(faction);
} finally { FactionManager.factions = previous; }
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,12 +60,14 @@ class DatabaseCoverageTest {
}

@Test void timerAndDayRoundTripAndMissingNullOrMalformedDataUseZero() throws Exception {
assertEquals(0,database.getTimer());assertEquals(0,database.getDay());
database.saveTimer(543,7);assertEquals(543,database.getTimer());assertEquals(7,database.getDay());
disk.write("Cache/data.json","null");assertEquals(0,database.getTimer());assertEquals(0,database.getDay());
disk.write("Cache/data.json","not-json{");assertEquals(0,database.getTimer());assertEquals(0,database.getDay());
assertEquals(0,database.getTimer());assertEquals(0,database.getDay());assertEquals(0,database.getLastNewDay());
database.saveTimer(543,7,1_796_036_400_000L);assertEquals(543,database.getTimer());assertEquals(7,database.getDay());
assertEquals(1_796_036_400_000L,database.getLastNewDay());
disk.write("Cache/data.json","{\"time\":5,\"day\":3}");assertEquals(0,database.getLastNewDay(),"a file saved before calendar days");
disk.write("Cache/data.json","null");assertEquals(0,database.getTimer());assertEquals(0,database.getDay());assertEquals(0,database.getLastNewDay());
disk.write("Cache/data.json","not-json{");assertEquals(0,database.getTimer());assertEquals(0,database.getDay());assertEquals(0,database.getLastNewDay());
disk.remove("Cache/data.json");Files.createDirectory(disk.root.resolve("Cache/data.json"));
assertDoesNotThrow(() -> database.saveTimer(10,2));
assertDoesNotThrow(() -> database.saveTimer(10,2,0));
assertTrue(Files.isDirectory(disk.root.resolve("Cache/data.json")));
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package net.tfminecraft.simplefactions.economy.settlement;

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

import java.time.Instant;
import org.junit.jupiter.api.Test;

class NewDayScheduleTest {
private static long at(String instant) {
return Instant.parse(instant).toEpochMilli();
}

@Test void aNewDayStartsAtNoonCetInWinter() {
assertEquals(at("2026-12-01T11:00:00Z"), NewDaySchedule.latestAtOrBefore(at("2026-12-02T10:59:59.999Z")));
assertEquals(at("2026-12-02T11:00:00Z"), NewDaySchedule.latestAtOrBefore(at("2026-12-02T11:00:00Z")));
assertEquals(at("2026-12-02T11:00:00Z"), NewDaySchedule.nextAfter(at("2026-12-01T22:54:03Z")));
assertEquals(at("2026-12-03T11:00:00Z"), NewDaySchedule.nextAfter(at("2026-12-02T11:00:00Z")));
}

@Test void aNewDayStartsAtNoonCestInSummerAndAcrossTheClockChange() {
assertEquals(at("2026-07-01T10:00:00Z"), NewDaySchedule.latestAtOrBefore(at("2026-07-01T10:30:00Z")));
// Clocks go forward on 2026-03-29: noon CET, then noon CEST 23 hours later.
assertEquals(at("2026-03-29T10:00:00Z"), NewDaySchedule.nextAfter(at("2026-03-28T11:00:00Z")));
// Clocks go back on 2026-10-25: noon CEST, then noon CET 25 hours later.
assertEquals(at("2026-10-25T11:00:00Z"), NewDaySchedule.nextAfter(at("2026-10-24T10:00:00Z")));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,9 @@ class RealmSettlementEffectsTest {
@Test void partialFactionSaveKeepsClaimsAndClockPendingAndReplaysExactAfterValues() throws Exception {
try (var fixture = new FactionDomainFixture()) {
FactionManager.day = 0;
FactionManager.lastNewDay = 0;
int previousTimer = FactionManager.timer;
FactionManager.timer = 1234;
UUID character = UUID.randomUUID();
var faction = fixture.saved("realm", UUID.randomUUID().toString());
var capital = faction.getOrCreateMainGuild();
Expand All @@ -57,8 +60,14 @@ class RealmSettlementEffectsTest {
effects.apply(plan);
assertEquals(owed, loan.getTotalOwed());
assertEquals(10, economy.getLedger(character).getNetDaily());
assertEquals(3, JsonUtil.GSON.fromJson(java.nio.file.Files.readString(folder.resolve("Cache/data.json")), TimerData.class).day);
var saved = JsonUtil.GSON.fromJson(java.nio.file.Files.readString(folder.resolve("Cache/data.json")), TimerData.class);
assertEquals(3, saved.day);
assertEquals(3, FactionManager.day);
assertEquals(NewDaySchedule.latestAtOrBefore(System.currentTimeMillis()), saved.lastNewDay);
assertEquals(saved.lastNewDay, FactionManager.lastNewDay);
assertEquals(1234, saved.time, "the cadence counter is saved, not reset");
assertEquals(1234, FactionManager.timer);
FactionManager.timer = previousTimer;
verify(deaths, times(2)).apply("sf:settle:2", Map.of());
assertEquals(10, guild.getBank().getWealth(), "Effects never perform money movement");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@ class RealmSettlementServiceTest {
var service = new RealmSettlementService(disk.root, database);
service.recover();
assertEquals(6, FactionManager.day);
assertEquals(0, FactionManager.timer);
verify(fixture.provinces).recalculate();
service.settle(5);
verify(fixture.provinces, times(1)).recalculate();
Expand Down
Loading