75 lines
7.3 KiB
Java
75 lines
7.3 KiB
Java
package games.dmg.fantasystick.events;
|
|
|
|
import com.google.gson.Gson;
|
|
import com.google.gson.JsonElement;
|
|
import com.google.gson.JsonObject;
|
|
import com.google.gson.JsonParser;
|
|
import java.io.IOException;
|
|
import java.nio.channels.FileChannel;
|
|
import java.nio.charset.StandardCharsets;
|
|
import java.nio.file.Files;
|
|
import java.nio.file.LinkOption;
|
|
import java.nio.file.Path;
|
|
import java.nio.file.StandardCopyOption;
|
|
import java.nio.file.StandardOpenOption;
|
|
import java.time.Instant;
|
|
import java.util.ArrayList;
|
|
import java.util.LinkedHashMap;
|
|
import java.util.List;
|
|
import java.util.Map;
|
|
import java.util.UUID;
|
|
|
|
/** Owner-local observation facts, never a gameplay phase, permission or reset receipt. Worker-only I/O. */
|
|
final class AdventureDayResetFactsStore {
|
|
record Facts(UUID operation,UUID generation,Instant started,EventInput.Context context,Map<String,Object> data,Instant completedAt){
|
|
Facts{data=new EventInput(operation,operation,started,"adventure.day.reset",context,data).data();}
|
|
}
|
|
private static final int MAX_BYTES=65_536;
|
|
private final Path directory;
|
|
AdventureDayResetFactsStore(Path data){directory=data.toAbsolutePath().resolve("adventure-day-reset-facts");}
|
|
List<Facts> load()throws IOException{
|
|
if(!Files.exists(directory,LinkOption.NOFOLLOW_LINKS))return List.of();safeDirectory();var result=new ArrayList<Facts>();
|
|
try(var paths=Files.list(directory)){for(var path:paths.filter(value->value.getFileName().toString().matches("[0-9a-f-]{36}\\.facts")).sorted().toList()){
|
|
if(!Files.isRegularFile(path,LinkOption.NOFOLLOW_LINKS))throw new IOException("Unsafe reset facts file");
|
|
byte[] bytes;try(var input=Files.newInputStream(path,LinkOption.NOFOLLOW_LINKS)){bytes=input.readNBytes(MAX_BYTES+1);}if(bytes.length>MAX_BYTES)throw new IOException("Oversized reset facts");
|
|
try{
|
|
var root=JsonParser.parseString(new String(bytes,StandardCharsets.UTF_8)).getAsJsonObject();if(!text(root,"format").equals("adventure_day_reset_facts_v1"))throw new IOException("Unknown reset facts format");
|
|
UUID operation=UUID.fromString(text(root,"operation"));if(!path.getFileName().toString().equals(operation+".facts"))throw new IOException("Reset facts identity mismatch");
|
|
EventInput.Context context=null;if(root.has("context")){
|
|
var value=root.getAsJsonObject("context");EventInput.Location location=null;
|
|
if(value.has("world_id"))location=new EventInput.Location(UUID.fromString(text(value,"world_id")),text(value,"world_name"),value.get("x").getAsDouble(),value.get("y").getAsDouble(),value.get("z").getAsDouble(),Instant.parse(text(value,"captured_at")),text(value,"quality"));
|
|
context=new EventInput.Context(UUID.fromString(text(value,"player_id")),text(value,"player_name"),uuid(value,"character_id"),value.has("character_name")?text(value,"character_name"):null,uuid(value,"session_id"),location);
|
|
}
|
|
result.add(new Facts(operation,UUID.fromString(text(root,"generation")),Instant.parse(text(root,"started_at")),context,object(root.getAsJsonObject("data"),0),root.has("completed_at")?Instant.parse(text(root,"completed_at")):null));
|
|
}catch(RuntimeException failure){throw new IOException("Invalid reset observation facts",failure);}
|
|
}}return List.copyOf(result);
|
|
}
|
|
void save(Facts facts)throws IOException{
|
|
if(Files.exists(directory,LinkOption.NOFOLLOW_LINKS))safeDirectory();else Files.createDirectories(directory);
|
|
var root=new JsonObject();root.addProperty("format","adventure_day_reset_facts_v1");root.addProperty("operation",facts.operation().toString());root.addProperty("generation",facts.generation().toString());root.addProperty("started_at",facts.started().toString());
|
|
if(facts.completedAt()!=null)root.addProperty("completed_at",facts.completedAt().toString());
|
|
if(facts.context()!=null){var c=facts.context();var value=new JsonObject();value.addProperty("player_id",c.playerId().toString());value.addProperty("player_name",c.playerName());
|
|
if(c.characterId()!=null){value.addProperty("character_id",c.characterId().toString());value.addProperty("character_name",c.characterName());value.addProperty("session_id",c.sessionId().toString());}
|
|
if(c.location()!=null){var l=c.location();value.addProperty("world_id",l.worldId().toString());value.addProperty("world_name",l.worldName());value.addProperty("x",l.x());value.addProperty("y",l.y());value.addProperty("z",l.z());value.addProperty("captured_at",l.capturedAt().toString());value.addProperty("quality",l.quality());}root.add("context",value);
|
|
}
|
|
root.add("data",new Gson().toJsonTree(facts.data()));byte[] bytes=root.toString().getBytes(StandardCharsets.UTF_8);if(bytes.length>MAX_BYTES)throw new IOException("Oversized reset facts");
|
|
var target=directory.resolve(facts.operation()+".facts");if(Files.exists(target,LinkOption.NOFOLLOW_LINKS)&&!Files.isRegularFile(target,LinkOption.NOFOLLOW_LINKS))throw new IOException("Unsafe reset facts target");
|
|
var temporary=Files.createTempFile(directory,".reset-facts-",".tmp");try{
|
|
try(var channel=FileChannel.open(temporary,StandardOpenOption.WRITE)){var buffer=java.nio.ByteBuffer.wrap(bytes);while(buffer.hasRemaining())channel.write(buffer);channel.force(true);}
|
|
Files.move(temporary,target,StandardCopyOption.ATOMIC_MOVE,StandardCopyOption.REPLACE_EXISTING);forceDirectory();
|
|
}finally{Files.deleteIfExists(temporary);}
|
|
}
|
|
void remove(UUID operation)throws IOException{if(!Files.exists(directory,LinkOption.NOFOLLOW_LINKS))return;safeDirectory();if(Files.deleteIfExists(directory.resolve(operation+".facts")))forceDirectory();}
|
|
private void safeDirectory()throws IOException{if(!Files.isDirectory(directory,LinkOption.NOFOLLOW_LINKS))throw new IOException("Unsafe reset facts directory");}
|
|
private void forceDirectory()throws IOException{try(var channel=FileChannel.open(directory,StandardOpenOption.READ)){channel.force(true);}}
|
|
private static String text(JsonObject value,String key){return value.get(key).getAsString();}
|
|
private static UUID uuid(JsonObject value,String key){return value.has(key)?UUID.fromString(text(value,key)):null;}
|
|
private static Map<String,Object> object(JsonObject value,int depth)throws IOException{var map=new LinkedHashMap<String,Object>();for(var entry:value.entrySet())map.put(entry.getKey(),decode(entry.getValue(),depth+1));return Map.copyOf(map);}
|
|
private static Object decode(JsonElement value,int depth)throws IOException{
|
|
if(depth>8||value.isJsonNull())throw new IOException("Unsafe reset facts value");if(value.isJsonObject())return object(value.getAsJsonObject(),depth);if(value.isJsonArray()){var result=new ArrayList<>();for(var item:value.getAsJsonArray())result.add(decode(item,depth+1));return List.copyOf(result);}
|
|
var primitive=value.getAsJsonPrimitive();if(primitive.isBoolean())return primitive.getAsBoolean();if(primitive.isString())return primitive.getAsString();
|
|
if(primitive.isNumber()){String text=primitive.getAsString();if(text.matches("-?[0-9]+"))return Integer.valueOf(text);double number=primitive.getAsDouble();if(!Double.isFinite(number))throw new IOException("Non-finite reset facts number");return number;}
|
|
throw new IOException("Unsupported reset facts value");
|
|
}
|
|
}
|