diff --git a/src/main/java/net/tfminecraft/simplefactions/map/Compiler.java b/src/main/java/net/tfminecraft/simplefactions/map/Compiler.java index fe453918..a06143d2 100644 --- a/src/main/java/net/tfminecraft/simplefactions/map/Compiler.java +++ b/src/main/java/net/tfminecraft/simplefactions/map/Compiler.java @@ -96,7 +96,8 @@ static JsonObject provinceToJson(Province p, String occupierId) { return o; } - public void exportProvincesToJson(File out) throws Exception { + /** The province payload, read from live state on the server thread; writing it can happen later. */ + public JsonArray provincesJson() { JsonArray arr = new JsonArray(); ProvinceManager pm = SimpleFactions.getInstance().getProvinceManager(); @@ -107,13 +108,11 @@ public void exportProvincesToJson(File out) throws Exception { for (Province p : pm.getProvinces()) { arr.add(provinceToJson(p, occupiedBy.get(p.getId()))); } - - try (FileWriter w = new FileWriter(out)) { - new GsonBuilder().setPrettyPrinting().create().toJson(arr, w); - } + return arr; } - public void exportGuildsToJson(File out) throws Exception { + /** The guild payload, read from live state on the server thread; writing it can happen later. */ + public JsonArray guildsJson() { JsonArray arr = new JsonArray(); for (Guild g : FactionManager.getAllGuilds()) { @@ -134,9 +133,6 @@ public void exportGuildsToJson(File out) throws Exception { arr.add(o); } - - try (FileWriter w = new FileWriter(out)) { - new GsonBuilder().setPrettyPrinting().create().toJson(arr, w); - } + return arr; } } diff --git a/src/main/java/net/tfminecraft/simplefactions/map/MapFile.java b/src/main/java/net/tfminecraft/simplefactions/map/MapFile.java new file mode 100644 index 00000000..978063fd --- /dev/null +++ b/src/main/java/net/tfminecraft/simplefactions/map/MapFile.java @@ -0,0 +1,47 @@ +package net.tfminecraft.simplefactions.map; + +import java.io.File; +import java.io.IOException; +import java.io.Writer; +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.nio.file.StandardOpenOption; +import java.util.UUID; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonElement; + +/** + * A map payload already built on the server thread, to be written to disk later, possibly off it. The tree + * holds only copied values, so writing it never reads live faction state. It is written to a temporary file + * in the same folder and then moved over the target, so an upload never reads a half-written file and two + * overlapping writes of the same payload cannot interleave. + */ +public record MapFile(File file, JsonElement json, boolean pretty) { + + public void write() throws IOException { + Path target = file.toPath().toAbsolutePath(); + Path folder = target.getParent(); + Files.createDirectories(folder); + // Created like a plain new file (umask and the folder's default ACL apply, as with the old in-place + // writer), not with Files.createTempFile, which would make it owner-only on Linux. + Path temp = folder.resolve(target.getFileName() + "." + UUID.randomUUID() + ".tmp"); + try { + try (Writer writer = Files.newBufferedWriter(temp, StandardCharsets.UTF_8, StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE)) { + Gson gson = pretty ? new GsonBuilder().setPrettyPrinting().create() : new Gson(); + gson.toJson(json, writer); + } + try { + Files.move(temp, target, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); + } catch (AtomicMoveNotSupportedException ex) { + Files.move(temp, target, StandardCopyOption.REPLACE_EXISTING); + } + } finally { + Files.deleteIfExists(temp); + } + } +} diff --git a/src/main/java/net/tfminecraft/simplefactions/map/MapSystem.java b/src/main/java/net/tfminecraft/simplefactions/map/MapSystem.java index 3f4ff717..2375b2ae 100644 --- a/src/main/java/net/tfminecraft/simplefactions/map/MapSystem.java +++ b/src/main/java/net/tfminecraft/simplefactions/map/MapSystem.java @@ -92,13 +92,59 @@ public void prepareUploadFiles() { prepareMapFiles(); } - /** Cheap payloads that change continuously and ship on every cycle (main thread). */ + /** Cheap payloads that change continuously and ship on every cycle, written right away (main thread). */ public void prepareLiveFiles() { + writeAll(buildLiveFiles()); + } + + /** + * Builds the live payloads from live state (main thread) and returns the ones still to be written, so the + * map cycles can write them off the main thread. Coalitions are small and written here, as before. + */ + List buildLiveFiles() { SimpleFactions.getInstance().getProvinceManager().recalculateIfNeeded(); - exportProvinces(); - exportGuilds(); - exportChronicle(); + List files = new ArrayList<>(); + files.addAll(provincesFile()); + files.addAll(guildsFile()); + files.addAll(chronicleFile()); exportCoalitions(); + return files; + } + + /** One payload built from live state, or none (logged) when building it failed. */ + static List live(String name, java.util.function.Supplier build, boolean pretty) { + try { + return List.of(new MapFile(new File("plugins/SimpleFactions/MapAPI/" + name + ".json"), build.get(), pretty)); + } catch (Exception e) { + Bukkit.getLogger().severe("[SimpleFactions] Failed to export " + name + ".json"); + e.printStackTrace(); + return List.of(); + } + } + + private List provincesFile() { + return live("province_data", compiler::provincesJson, true); + } + + private List guildsFile() { + return live("guilds", compiler::guildsJson, true); + } + + private static List chronicleFile() { + // Not pretty printed: this one ships 288 times a day. + return Cache.chronicleEnabled ? live("chronicle", MapSystem::chronicleJson, false) : List.of(); + } + + /** Writes built payloads; one that fails is logged and does not stop the others. */ + static void writeAll(List files) { + for (MapFile file : files) { + try { + file.write(); + } catch (Exception e) { + Bukkit.getLogger().severe("[SimpleFactions] Failed to export " + file.file().getName()); + e.printStackTrace(); + } + } } /** Nation geometry and markers, only worth regenerating when the map queue has work. */ @@ -160,7 +206,9 @@ public void updateMap() { for(Faction fac : FactionManager.factions) { db.saveFaction(fac); } - prepareUploadFiles(); + // Live payloads are built here and written with the upload, as on the quiet path. + List liveFiles = buildLiveFiles(); + prepareMapFiles(); File queueFile = new File("plugins/SimpleFactions/MapAPI/queue.json"); SimpleFactions plugin = SimpleFactions.getInstance(); // New changes belong to the next publication, including another change to the same nation. @@ -168,6 +216,7 @@ public void updateMap() { mapUploadInProgress = true; Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> { try { + writeAll(liveFiles); RestServer.upload("queue", queueFile); uploadPreparedFiles(); RestServer.commenceRegen("queued"); @@ -183,7 +232,8 @@ public void updateMap() { */ public void updateLiveData() { lastUpdate = 0; - prepareLiveFiles(); + // Built here from live state; serializing and writing them (most of the cost) happens with the upload. + List liveFiles = buildLiveFiles(); // Leader character names live in Data/*.json and ship in nation.json, // which the quiet path otherwise skips. A name learned since the last // cycle re-exports just that file, so it reaches the map within one @@ -199,6 +249,7 @@ public void updateLiveData() { } SimpleFactions plugin = SimpleFactions.getInstance(); Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> { + writeAll(liveFiles); uploadLiveFiles(); if (shipNation) { RestServer.upload("nation", new File("plugins/SimpleFactions/MapAPI/nation.json")); @@ -221,9 +272,11 @@ public void fullRegen() { for(Faction fac : FactionManager.factions) { db.saveFaction(fac); } - prepareUploadFiles(); + List liveFiles = buildLiveFiles(); + prepareMapFiles(); SimpleFactions plugin = SimpleFactions.getInstance(); Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> { + writeAll(liveFiles); uploadPreparedFiles(); RestServer.commenceRegen("fullregen"); }); @@ -361,25 +414,11 @@ public void unclaim(Player p, Faction f, int province) { } public void exportProvinces() { - try { - File out = new File("plugins/SimpleFactions/MapAPI/province_data.json"); - compiler.exportProvincesToJson(out); - //RestServer.upload("provinces", out); not yet - } catch (Exception e) { - Bukkit.getLogger().severe("[SimpleFactions] Failed to export province_data.json"); - e.printStackTrace(); - } + writeAll(provincesFile()); } public void exportGuilds() { - try { - File out = new File("plugins/SimpleFactions/MapAPI/guilds.json"); - compiler.exportGuildsToJson(out); - //RestServer.upload("provinces", out); not yet - } catch (Exception e) { - Bukkit.getLogger().severe("[SimpleFactions] Failed to export guilds.json"); - e.printStackTrace(); - } + writeAll(guildsFile()); } public void exportMarkers() { @@ -392,23 +431,25 @@ public void exportMarkers() { } } - public void exportChronicle() { - if (!Cache.chronicleEnabled) return; - // The snapshot reads every guild's net income, which asks each treasury whether it is - // bankrupt many times over (realm income walks its member guilds' ledgers), and each ask - // was a SQLite query: 0.3-0.5 s on the server thread every live cycle on Main. The export - // only reads, so one answer per treasury and one stability report per faction hold for it. + /** + * The chronicle payload with the per-export memos in place (main thread). The snapshot reads every + * guild's net income, which asks each treasury whether it is bankrupt many times over (realm income + * walks its member guilds' ledgers), and each ask was a SQLite query: 0.3-0.5 s on the server thread + * every live cycle on Main. The export only reads, so one answer per treasury and one stability report + * per faction hold for it. + */ + static com.google.gson.JsonObject chronicleJson() { BankruptcyMemo.Run bankruptcy = BankruptcyMemo.begin(); StabilityMemo.Run stability = StabilityMemo.begin(); try { - File out = new File("plugins/SimpleFactions/MapAPI/chronicle.json"); - ChronicleExport.export(out); - } catch (Exception e) { - Bukkit.getLogger().severe("[SimpleFactions] Failed to export chronicle.json"); - e.printStackTrace(); + return ChronicleExport.build(); } finally { StabilityMemo.end(stability); BankruptcyMemo.end(bankruptcy); } } + + public void exportChronicle() { + writeAll(chronicleFile()); + } } diff --git a/src/main/java/net/tfminecraft/simplefactions/map/export/ChronicleExport.java b/src/main/java/net/tfminecraft/simplefactions/map/export/ChronicleExport.java index 4c280b16..a78c239f 100644 --- a/src/main/java/net/tfminecraft/simplefactions/map/export/ChronicleExport.java +++ b/src/main/java/net/tfminecraft/simplefactions/map/export/ChronicleExport.java @@ -1,15 +1,13 @@ package net.tfminecraft.simplefactions.map.export; import java.io.File; -import java.io.FileWriter; import java.io.IOException; -import java.nio.charset.StandardCharsets; import java.time.Instant; -import com.google.gson.Gson; import com.google.gson.JsonObject; import net.tfminecraft.simplefactions.managers.FactionManager; +import net.tfminecraft.simplefactions.map.MapFile; /** * Writes the chronicle snapshot to disk for upload. Runs on the main thread as part of @@ -20,26 +18,22 @@ private ChronicleExport() { } public static void export(File out) throws IOException { + // Not pretty printed: this one ships 288 times a day. + new MapFile(out, build(), false).write(); + } + + /** The chronicle snapshot, read from live state on the server thread; writing it can happen later. */ + public static JsonObject build() { // Prestige is derived and never recomputed on a timer, so a snapshot taken without // this would carry whatever the last triggering event happened to leave behind. // Wealth is already maintained eagerly on every bank mutation, and looping // updateWealth here would be O(n^2) since it cascades into updateAllPrestige. FactionManager.updateAllPrestigeConverged(); - JsonObject root = ChronicleSnapshot.build( + return ChronicleSnapshot.build( FactionManager.factions, FactionManager.getDay(), FactionManager.getTimer(), Instant.now()); - - File parent = out.getParentFile(); - if (parent != null) { - parent.mkdirs(); - } - - // Not pretty printed: this one ships 288 times a day. - try (FileWriter writer = new FileWriter(out, StandardCharsets.UTF_8)) { - new Gson().toJson(root, writer); - } } } diff --git a/src/test/java/net/tfminecraft/simplefactions/map/MapFileTest.java b/src/test/java/net/tfminecraft/simplefactions/map/MapFileTest.java new file mode 100644 index 00000000..4a106e4f --- /dev/null +++ b/src/test/java/net/tfminecraft/simplefactions/map/MapFileTest.java @@ -0,0 +1,94 @@ +package net.tfminecraft.simplefactions.map; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; + +import java.io.File; +import java.nio.file.AtomicMoveNotSupportedException; +import java.nio.file.CopyOption; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.logging.Logger; + +import org.bukkit.Bukkit; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.mockito.MockedStatic; + +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; + +class MapFileTest { + @TempDir Path dir; + + private static JsonObject payload() { + JsonObject o = new JsonObject(); o.addProperty("id", 7); o.add("list", new JsonArray()); return o; + } + + @Test void writesPrettyOrCompactJsonIntoNewFoldersAndLeavesNoTemporaryFile() throws Exception { + Path pretty = dir.resolve("MapAPI/a.json"), compact = dir.resolve("MapAPI/b.json"); + new MapFile(pretty.toFile(), payload(), true).write(); + new MapFile(compact.toFile(), payload(), false).write(); + assertTrue(Files.readString(pretty).contains("\n")); + assertEquals("{\"id\":7,\"list\":[]}", Files.readString(compact)); + assertEquals(7, JsonParser.parseString(Files.readString(pretty)).getAsJsonObject().get("id").getAsInt()); + // A later write replaces the file in one move. + JsonObject next = new JsonObject(); next.addProperty("id", 8); + new MapFile(compact.toFile(), next, false).write(); + assertEquals("{\"id\":8}", Files.readString(compact)); + if (java.nio.file.FileSystems.getDefault().supportedFileAttributeViews().contains("posix")) { + // Same mode as any plain new file in that folder (not owner-only). + Path plain = Files.writeString(dir.resolve("plain.txt"), "x"); + assertEquals(Files.getPosixFilePermissions(plain), Files.getPosixFilePermissions(compact)); + Files.delete(plain); + } + try (var files = Files.list(dir.resolve("MapAPI"))) { + assertEquals(List.of("a.json", "b.json"), files.map(p -> p.getFileName().toString()).sorted().toList()); + } + } + + @Test void fallsBackToAPlainReplaceWhereAnAtomicMoveIsNotSupported() throws Exception { + Path target = dir.resolve("c.json"); + try (MockedStatic files = mockStatic(Files.class, CALLS_REAL_METHODS)) { + files.when(() -> Files.move(any(Path.class), any(Path.class), any(CopyOption[].class))).thenAnswer(call -> { + Object[] options = call.getRawArguments().length > 2 ? (Object[]) call.getRawArguments()[2] : new Object[0]; + if (List.of(options).contains(java.nio.file.StandardCopyOption.ATOMIC_MOVE)) { + throw new AtomicMoveNotSupportedException("a", "b", "no atomic moves here"); + } + return call.callRealMethod(); + }); + new MapFile(target.toFile(), payload(), false).write(); + } + assertEquals("{\"id\":7,\"list\":[]}", Files.readString(target)); + } + + @Test void aFailingWriteIsLoggedRemovesItsTemporaryFileAndTheOthersStillWrite() throws Exception { + Path blocked = dir.resolve("blocked.json"); + Files.createDirectories(blocked.resolve("inside")); + Path ok = dir.resolve("ok.json"); + Logger logger = mock(Logger.class); + try (MockedStatic bukkit = mockStatic(Bukkit.class)) { + bukkit.when(Bukkit::getLogger).thenReturn(logger); + MapSystem.writeAll(List.of(new MapFile(blocked.toFile(), payload(), false), new MapFile(ok.toFile(), payload(), false))); + } + verify(logger).severe("[SimpleFactions] Failed to export blocked.json"); + assertTrue(Files.isRegularFile(ok)); + try (var files = Files.list(dir)) { + assertTrue(files.noneMatch(p -> p.getFileName().toString().endsWith(".tmp"))); + } + } + + @Test void aPayloadThatCannotBeBuiltIsLoggedAndSkipped() { + Logger logger = mock(Logger.class); + try (MockedStatic bukkit = mockStatic(Bukkit.class)) { + bukkit.when(Bukkit::getLogger).thenReturn(logger); + assertEquals(List.of(), MapSystem.live("guilds", () -> { throw new IllegalStateException("no guilds"); }, true)); + List built = MapSystem.live("guilds", JsonArray::new, true); + assertEquals(new File("plugins/SimpleFactions/MapAPI/guilds.json"), built.get(0).file()); + } + verify(logger).severe("[SimpleFactions] Failed to export guilds.json"); + } +}