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
16 changes: 6 additions & 10 deletions src/main/java/net/tfminecraft/simplefactions/map/Compiler.java
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand All @@ -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()) {
Expand All @@ -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;
}
}
47 changes: 47 additions & 0 deletions src/main/java/net/tfminecraft/simplefactions/map/MapFile.java
Original file line number Diff line number Diff line change
@@ -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);
}
}
}
109 changes: 75 additions & 34 deletions src/main/java/net/tfminecraft/simplefactions/map/MapSystem.java
Original file line number Diff line number Diff line change
Expand Up @@ -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());
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}

/**
* 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<MapFile> buildLiveFiles() {
SimpleFactions.getInstance().getProvinceManager().recalculateIfNeeded();
exportProvinces();
exportGuilds();
exportChronicle();
List<MapFile> 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<MapFile> live(String name, java.util.function.Supplier<com.google.gson.JsonElement> 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<MapFile> provincesFile() {
return live("province_data", compiler::provincesJson, true);
}

private List<MapFile> guildsFile() {
return live("guilds", compiler::guildsJson, true);
}

private static List<MapFile> 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<MapFile> 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. */
Expand Down Expand Up @@ -160,14 +206,17 @@ 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<MapFile> 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.
queues = new HashMap<>();
mapUploadInProgress = true;
Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
try {
writeAll(liveFiles);
RestServer.upload("queue", queueFile);
uploadPreparedFiles();
RestServer.commenceRegen("queued");
Expand All @@ -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<MapFile> 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
Expand All @@ -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"));
Expand All @@ -221,9 +272,11 @@ public void fullRegen() {
for(Faction fac : FactionManager.factions) {
db.saveFaction(fac);
}
prepareUploadFiles();
List<MapFile> liveFiles = buildLiveFiles();
prepareMapFiles();
SimpleFactions plugin = SimpleFactions.getInstance();
Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
writeAll(liveFiles);
uploadPreparedFiles();
RestServer.commenceRegen("fullregen");
});
Expand Down Expand Up @@ -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() {
Expand All @@ -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());
}
}
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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);
}
}
}
Loading