187 lines
9.8 KiB
Java
187 lines
9.8 KiB
Java
package games.dmg.fantasystick.persistence;
|
|
|
|
import games.dmg.fantasystick.shop.ArmorMarketRules;
|
|
import java.io.IOException;
|
|
import java.math.BigInteger;
|
|
import java.nio.ByteBuffer;
|
|
import java.nio.channels.FileChannel;
|
|
import java.nio.channels.OverlappingFileLockException;
|
|
import java.nio.charset.StandardCharsets;
|
|
import java.nio.file.*;
|
|
import java.util.*;
|
|
import java.util.concurrent.*;
|
|
import org.yaml.snakeyaml.LoaderOptions;
|
|
import org.yaml.snakeyaml.Yaml;
|
|
import org.yaml.snakeyaml.constructor.SafeConstructor;
|
|
|
|
/** Durable save-before-publication bases, variance and tier stock bounds for future catalogs. */
|
|
public final class GearSettings implements AutoCloseable {
|
|
public static final String LEATHER="gear-price-leather", COPPER="gear-price-copper",
|
|
GOLD="gear-price-gold", IRON="gear-price-iron", DIAMOND="gear-price-diamond",
|
|
NETHERITE="gear-price-netherite", VARIANCE="gear-price-variance-percent";
|
|
private static final Map<GearTier,String> PRICE_KEYS=Map.of(
|
|
GearTier.LEATHER,LEATHER, GearTier.COPPER,COPPER, GearTier.GOLD,GOLD,
|
|
GearTier.IRON,IRON, GearTier.DIAMOND,DIAMOND, GearTier.NETHERITE,NETHERITE);
|
|
private static final Map<GearTier,String> TIER_NAMES=Map.of(
|
|
GearTier.LEATHER,"leather", GearTier.COPPER,"copper", GearTier.GOLD,"gold",
|
|
GearTier.IRON,"iron", GearTier.DIAMOND,"diamond", GearTier.NETHERITE,"netherite");
|
|
private static final Map<String,String> DEFAULTS=defaults();
|
|
private static final List<String> KEYS=DEFAULTS.keySet().stream().sorted().toList();
|
|
|
|
public record Update(String key,String value,Map<String,String> values,long sequence) {
|
|
public Update { values=Map.copyOf(values); }
|
|
}
|
|
|
|
private final Path directory;
|
|
private final ExecutorService worker=Executors.newSingleThreadExecutor(r->new Thread(r,"fantasy-gear-configuration"));
|
|
private volatile Map<String,String> effective;
|
|
private Map<String,String> persisted;
|
|
private long savedSequence,publishedSequence;
|
|
private boolean closed;
|
|
private int pending;
|
|
private final CompletableFuture<Void> drained=new CompletableFuture<>();
|
|
|
|
public GearSettings(Path directory,Map<String,String> initial) {
|
|
this.directory=Objects.requireNonNull(directory).toAbsolutePath();
|
|
var values=new LinkedHashMap<String,String>();
|
|
for(String key:KEYS) values.put(key,Objects.requireNonNull(initial.getOrDefault(key,DEFAULTS.get(key))));
|
|
validate(values);
|
|
effective=Map.copyOf(values);
|
|
persisted=effective;
|
|
}
|
|
|
|
public static List<String> keys(){return KEYS;}
|
|
public static String defaultValue(String key){return DEFAULTS.get(key);}
|
|
public String value(String key){return effective.get(key);}
|
|
public int price(GearTier tier){return wholeNonnegative(effective.get(priceKey(tier)));}
|
|
|
|
public ArmorMarketRules rules() {
|
|
var values=effective;
|
|
var prices=new EnumMap<GearTier,BigInteger>(GearTier.class);
|
|
var stock=new EnumMap<GearTier,ArmorMarketRules.StockRange>(GearTier.class);
|
|
for(var tier:PRICE_KEYS.keySet()) {
|
|
prices.put(tier,new BigInteger(values.get(priceKey(tier))));
|
|
stock.put(tier,new ArmorMarketRules.StockRange(
|
|
wholePositive(values.get(stockKey(tier,true))), wholePositive(values.get(stockKey(tier,false)))));
|
|
}
|
|
return new ArmorMarketRules(prices,wholeVariance(values.get(VARIANCE)),stock);
|
|
}
|
|
|
|
public CompletionStage<Update> set(String key,String raw) {
|
|
if(!KEYS.contains(key)) throw new IllegalArgumentException("Unknown gear market setting");
|
|
String accepted;
|
|
try { accepted=Integer.toString(parseForKey(key,raw)); }
|
|
catch(RuntimeException invalid) { throw new IllegalArgumentException("Invalid gear market setting",invalid); }
|
|
var preview=new LinkedHashMap<>(effective);
|
|
preview.put(key,accepted);
|
|
validate(preview);
|
|
synchronized(this){if(closed)return CompletableFuture.failedStage(new IOException("Configuration closed"));pending++;}
|
|
return CompletableFuture.supplyAsync(()->{
|
|
try {
|
|
var next=new LinkedHashMap<>(persisted);
|
|
next.put(key,accepted);
|
|
validate(next);
|
|
save(key,accepted);
|
|
persisted=Map.copyOf(next);
|
|
return new Update(key,accepted,persisted,++savedSequence);
|
|
} catch(IOException failure) { throw new CompletionException(failure); }
|
|
finally { finished(); }
|
|
},worker).minimalCompletionStage();
|
|
}
|
|
|
|
public synchronized boolean publish(Update update) {
|
|
if(update.sequence()<=publishedSequence)return false;
|
|
validate(update.values());
|
|
effective=update.values();
|
|
publishedSequence=update.sequence();
|
|
return true;
|
|
}
|
|
|
|
private static Map<String,String> defaults() {
|
|
var values=new LinkedHashMap<String,String>();
|
|
values.put(LEATHER,"2"); values.put(COPPER,"10"); values.put(GOLD,"25");
|
|
values.put(IRON,"75"); values.put(DIAMOND,"150"); values.put(NETHERITE,"500");
|
|
values.put(VARIANCE,"10");
|
|
int[][] ranges={{25,50},{20,40},{15,30},{10,20},{5,10},{1,3}};
|
|
GearTier[] tiers={GearTier.LEATHER,GearTier.COPPER,GearTier.GOLD,GearTier.IRON,GearTier.DIAMOND,GearTier.NETHERITE};
|
|
for(int i=0;i<tiers.length;i++) {
|
|
values.put(stockKey(tiers[i],true),Integer.toString(ranges[i][0]));
|
|
values.put(stockKey(tiers[i],false),Integer.toString(ranges[i][1]));
|
|
}
|
|
return Map.copyOf(values);
|
|
}
|
|
|
|
private static void validate(Map<String,String> values) {
|
|
for(var tier:PRICE_KEYS.keySet()) {
|
|
wholeNonnegative(values.get(priceKey(tier)));
|
|
int minimum=wholePositive(values.get(stockKey(tier,true)));
|
|
int maximum=wholePositive(values.get(stockKey(tier,false)));
|
|
if(minimum>maximum)throw new IllegalArgumentException("Stock minimum exceeds maximum");
|
|
}
|
|
wholeVariance(values.get(VARIANCE));
|
|
}
|
|
|
|
private static int parseForKey(String key,String value) {
|
|
if(key.equals(VARIANCE))return wholeVariance(value);
|
|
if(key.startsWith("gear-stock-"))return wholePositive(value);
|
|
return wholeNonnegative(value);
|
|
}
|
|
private static int wholeNonnegative(String value){return bounded(value,0,Integer.MAX_VALUE);}
|
|
private static int wholePositive(String value){return bounded(value,1,Integer.MAX_VALUE);}
|
|
private static int wholeVariance(String value){return bounded(value,0,100);}
|
|
private static int bounded(String value,int minimum,int maximum) {
|
|
var number=new BigInteger(Objects.requireNonNull(value));
|
|
if(number.compareTo(BigInteger.valueOf(minimum))<0||number.compareTo(BigInteger.valueOf(maximum))>0)
|
|
throw new IllegalArgumentException();
|
|
return number.intValueExact();
|
|
}
|
|
private static String priceKey(GearTier tier) {
|
|
var key=PRICE_KEYS.get(tier);
|
|
if(key==null)throw new IllegalArgumentException("None is not purchasable");
|
|
return key;
|
|
}
|
|
public static String stockKey(GearTier tier,boolean minimum) {
|
|
var name=TIER_NAMES.get(tier);
|
|
if(name==null)throw new IllegalArgumentException("None is not purchasable");
|
|
return "gear-stock-"+name+(minimum?"-min":"-max");
|
|
}
|
|
|
|
private void save(String key,String value)throws IOException {
|
|
Files.createDirectories(directory);
|
|
var file=directory.resolve("config.yml");
|
|
var lockFile=directory.resolve(".config.lock");
|
|
try(var channel=FileChannel.open(lockFile,StandardOpenOption.CREATE,StandardOpenOption.WRITE,LinkOption.NOFOLLOW_LINKS);
|
|
var lock=channel.tryLock()) {
|
|
if(lock==null)throw new IOException("Configuration busy");
|
|
var options=new LoaderOptions(); options.setAllowDuplicateKeys(false); options.setMaxAliasesForCollections(20);
|
|
options.setCodePointLimit(1_048_576);
|
|
var yaml=new Yaml(new SafeConstructor(options));
|
|
Map<String,Object> document=new LinkedHashMap<>();
|
|
if(Files.exists(file,LinkOption.NOFOLLOW_LINKS)) {
|
|
if(!Files.isRegularFile(file,LinkOption.NOFOLLOW_LINKS))throw new IOException("Unsafe configuration");
|
|
byte[] bytes;
|
|
try(var input=Files.newInputStream(file,LinkOption.NOFOLLOW_LINKS)){bytes=input.readNBytes(1_048_577);}
|
|
if(bytes.length>1_048_576)throw new IOException("Configuration too large");
|
|
Object loaded=yaml.load(StandardCharsets.UTF_8.newDecoder().decode(ByteBuffer.wrap(bytes)).toString());
|
|
if(loaded instanceof Map<?,?> map)for(var entry:map.entrySet()) {
|
|
if(!(entry.getKey() instanceof String savedKey))throw new IOException("Invalid key");
|
|
document.put(savedKey,entry.getValue());
|
|
}
|
|
}
|
|
document.put(key,Integer.parseInt(value));
|
|
byte[] bytes=yaml.dump(document).getBytes(StandardCharsets.UTF_8);
|
|
Path temporary=Files.createTempFile(directory,".config-",".tmp");
|
|
try {
|
|
Files.write(temporary,bytes,StandardOpenOption.TRUNCATE_EXISTING);
|
|
try(var output=FileChannel.open(temporary,StandardOpenOption.WRITE)){output.force(true);}
|
|
Files.move(temporary,file,StandardCopyOption.ATOMIC_MOVE,StandardCopyOption.REPLACE_EXISTING);
|
|
DurableFiles.forceDirectory(directory);
|
|
} finally { Files.deleteIfExists(temporary); }
|
|
} catch(OverlappingFileLockException busy) { throw new IOException("Configuration busy",busy); }
|
|
}
|
|
|
|
private synchronized void finished(){pending--;if(closed&&pending==0)drained.complete(null);}
|
|
public CompletionStage<Void> drained(){return drained.minimalCompletionStage();}
|
|
@Override public synchronized void close(){closed=true;worker.shutdown();if(pending==0)drained.complete(null);}
|
|
}
|