Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c960dbcf7b |
No files matched your search
@@ -59,6 +59,7 @@ public final class FantasyStickPlugin extends JavaPlugin {
|
||||
private games.dmg.fantasystick.shop.RareShop rareShop;
|
||||
private games.dmg.fantasystick.shop.RareShopMenus rareShopMenus;
|
||||
private games.dmg.fantasystick.shop.RarePotionService rarePotions;
|
||||
private games.dmg.fantasystick.shop.RareReskillService rareReskills;
|
||||
private org.bukkit.scheduler.BukkitTask rareMarketPulse,rareMenuPulse;
|
||||
private games.dmg.fantasystick.party.PartyCombat partyCombat;
|
||||
private EquipmentAdminCommand admin;
|
||||
@@ -579,7 +580,8 @@ public final class FantasyStickPlugin extends JavaPlugin {
|
||||
rareMarket.attachListener(catalog->{if(lifetime!=generation)return;try{nextTick.accept(()->{if(lifetime==generation)localRareMenus.refreshOpen();});}catch(RuntimeException failure){if(lifetime==generation)getLogger().log(Level.WARNING,"Rare Items menu refresh failed",failure);}});
|
||||
rareMerchantController=new games.dmg.fantasystick.shop.RareMerchantController(this,rareMerchants,rareShopMenus::open);
|
||||
rarePotions=new games.dmg.fantasystick.shop.RarePotionService(rareInventory,rareSettings,characters,sessions,event->getServer().getPluginManager().callEvent(event),nextTick,failure->getLogger().log(Level.WARNING,"Rare potion use failed",failure));
|
||||
rarePotions.install();books.attachRareInventory(rareInventory,rarePotions);
|
||||
rareReskills=new games.dmg.fantasystick.shop.RareReskillService(rareInventory,characters,sessions,nextTick,record->{for(String ability:record.learned())abilityEngine.remove(record.id(),ability);speedI.sweep();lowLightVision.sweep();},failure->getLogger().log(Level.WARNING,"Rare Reskill use failed",failure));
|
||||
rarePotions.install();rareReskills.install();books.attachRareInventory(rareInventory,rarePotions,rareReskills);
|
||||
adventureQuestController = new games.dmg.fantasystick.adventure.AdventureQuestController(this,
|
||||
adventureQuests, adventureQuestSettings, sessions, parties, characters, rules, nextTick,
|
||||
Clock.systemUTC(), java.util.random.RandomGenerator.getDefault(), particleDelivery);
|
||||
@@ -789,7 +791,7 @@ public final class FantasyStickPlugin extends JavaPlugin {
|
||||
var closingArmorMenuPulse=armorMenuPulse;armorMenuPulse=null;
|
||||
var closingRareSettings=rareSettings;rareSettings=null;var closingRareInventory=rareInventory;rareInventory=null;
|
||||
var closingRareMerchants=rareMerchants;rareMerchants=null;var closingRareMerchantController=rareMerchantController;rareMerchantController=null;
|
||||
var closingRareMarket=rareMarket;rareMarket=null;var closingRareShopMenus=rareShopMenus;rareShopMenus=null;rareShop=null;rarePotions=null;
|
||||
var closingRareMarket=rareMarket;rareMarket=null;var closingRareShopMenus=rareShopMenus;rareShopMenus=null;rareShop=null;rarePotions=null;rareReskills=null;
|
||||
var closingRareMarketPulse=rareMarketPulse;rareMarketPulse=null;var closingRareMenuPulse=rareMenuPulse;rareMenuPulse=null;
|
||||
var closingCrafting = crafting; crafting = null;
|
||||
var closingGuard = guard; guard = null;
|
||||
|
||||
@@ -31,7 +31,7 @@ public record AbilityDefinition(String id, String name, Material icon, List<Stri
|
||||
Objects.requireNonNull(effect);
|
||||
lore = List.copyOf(lore); requirements = Map.copyOf(requirements); parameters = Map.copyOf(parameters);
|
||||
if (!ID.matcher(id).matches() || name.isBlank() || icon.isAir() || lore.isEmpty()
|
||||
|| lore.stream().anyMatch(String::isBlank) || instructions.isBlank() || pointCost.signum() <= 0
|
||||
|| lore.stream().anyMatch(String::isBlank) || instructions.isBlank() || !pointCost.equals(BigInteger.ONE)
|
||||
|| cooldown.isNegative() || cooldown.compareTo(Duration.ofDays(365)) > 0 || requirements.values().stream().anyMatch(value -> value.compareTo(BigInteger.TEN) < 0)
|
||||
|| parameters.entrySet().stream().anyMatch(entry -> !PARAMETER.matcher(entry.getKey()).matches()
|
||||
|| entry.getValue().signum() < 0 || !Double.isFinite(entry.getValue().doubleValue()))) {
|
||||
|
||||
@@ -32,6 +32,7 @@ public final class CharacterBookController implements Consumer<ControlInput>, Au
|
||||
private games.dmg.fantasystick.adventure.FishingDirectory fishing;
|
||||
private games.dmg.fantasystick.shop.RareInventoryDirectory rareInventory;
|
||||
private games.dmg.fantasystick.shop.RarePotionService rarePotions;
|
||||
private games.dmg.fantasystick.shop.RareReskillService rareReskills;
|
||||
private final org.bukkit.Server server;
|
||||
private final Map<UUID, Object> pending = new ConcurrentHashMap<>();
|
||||
private final Map<UUID, Object> adminPending = new ConcurrentHashMap<>();
|
||||
@@ -48,10 +49,12 @@ public final class CharacterBookController implements Consumer<ControlInput>, Au
|
||||
private static final net.kyori.adventure.key.Key PASSIVE_UNLOCK = net.kyori.adventure.key.Key.key("fantasystick", "passive_unlock");
|
||||
private static final net.kyori.adventure.key.Key PASSIVE_UNLEARN = net.kyori.adventure.key.Key.key("fantasystick", "passive_unlearn");
|
||||
private static final net.kyori.adventure.key.Key RARE_USE = net.kyori.adventure.key.Key.key("fantasystick", "rare_use");
|
||||
private static final net.kyori.adventure.key.Key RARE_RESKILL_CONFIRM = net.kyori.adventure.key.Key.key("fantasystick", "rare_reskill_confirm");
|
||||
private static final java.util.regex.Pattern PAGE_PAYLOAD = java.util.regex.Pattern.compile("\"([a-f0-9-]{36}):([01])\"");
|
||||
private static final java.util.regex.Pattern STAT_PAYLOAD = java.util.regex.Pattern.compile("\"([a-f0-9-]{36}):(STR|DEX|CON|INT|WIS|CHR)\"");
|
||||
private static final java.util.regex.Pattern ABILITY_PAYLOAD = java.util.regex.Pattern.compile("\"([a-f0-9-]{36}):([a-z][a-z0-9_]{0,63})\"");
|
||||
private static final java.util.regex.Pattern RARE_PAYLOAD = java.util.regex.Pattern.compile("\"([a-f0-9-]{36}):([a-z][a-z0-9-]{0,63})\"");
|
||||
private static final java.util.regex.Pattern RARE_CONFIRM_PAYLOAD = java.util.regex.Pattern.compile("\"([a-f0-9-]{36})\"");
|
||||
private record View(String nonce, ControlInput input, int previous, int next) { }
|
||||
private record AdminView(String nonce, UUID administrator, org.bukkit.entity.Player target,
|
||||
games.dmg.fantasystick.session.EquipmentSessions.Active active,
|
||||
@@ -61,11 +64,13 @@ public final class CharacterBookController implements Consumer<ControlInput>, Au
|
||||
private record AbilityView(String nonce, ControlInput input, java.math.BigInteger revision, java.util.Set<String> ids) { }
|
||||
private record PassiveView(String nonce, ControlInput input, java.math.BigInteger revision, java.util.Set<String> ids) { }
|
||||
private record RareView(String nonce,ControlInput input,java.util.Map<String,java.math.BigInteger> quantities){}
|
||||
private record ReskillView(String nonce,ControlInput input,games.dmg.fantasystick.shop.RareReskillService.Preview preview){}
|
||||
private final Map<UUID, View> views = new ConcurrentHashMap<>();
|
||||
private final Map<UUID, StatView> statViews = new ConcurrentHashMap<>();
|
||||
private final Map<UUID, AbilityView> abilityViews = new ConcurrentHashMap<>();
|
||||
private final Map<UUID, PassiveView> passiveViews = new ConcurrentHashMap<>();
|
||||
private final Map<UUID,RareView> rareViews=new ConcurrentHashMap<>();
|
||||
private final Map<UUID,ReskillView> reskillViews=new ConcurrentHashMap<>();
|
||||
|
||||
/** Scheduler must always defer to the server thread. Diagnostics must not access players or throw. */
|
||||
public CharacterBookController(CharacterStorage characters, ProgressionRules rules,
|
||||
@@ -109,7 +114,7 @@ public final class CharacterBookController implements Consumer<ControlInput>, Au
|
||||
}
|
||||
|
||||
public void attachFishingInventory(games.dmg.fantasystick.adventure.FishingDirectory fishing){if(closed||this.fishing!=null)throw new IllegalStateException("Fishing inventory already attached or books closed");this.fishing=Objects.requireNonNull(fishing);}
|
||||
public void attachRareInventory(games.dmg.fantasystick.shop.RareInventoryDirectory inventory,games.dmg.fantasystick.shop.RarePotionService potions){if(closed||rareInventory!=null)throw new IllegalStateException("Rare inventory already attached or books closed");rareInventory=Objects.requireNonNull(inventory);rarePotions=Objects.requireNonNull(potions);}
|
||||
public void attachRareInventory(games.dmg.fantasystick.shop.RareInventoryDirectory inventory,games.dmg.fantasystick.shop.RarePotionService potions,games.dmg.fantasystick.shop.RareReskillService reskills){if(closed||rareInventory!=null)throw new IllegalStateException("Rare inventory already attached or books closed");rareInventory=Objects.requireNonNull(inventory);rarePotions=Objects.requireNonNull(potions);rareReskills=Objects.requireNonNull(reskills);}
|
||||
|
||||
@Override public void accept(ControlInput input) { load(input, 0); }
|
||||
|
||||
@@ -237,6 +242,7 @@ public final class CharacterBookController implements Consumer<ControlInput>, Au
|
||||
abilityViews.remove(owner);
|
||||
passiveViews.remove(owner);
|
||||
rareViews.remove(owner);
|
||||
reskillViews.remove(owner);
|
||||
Object ticket = new Object();
|
||||
pending.put(owner, ticket);
|
||||
characters.find(input.session().character()).whenComplete((record, failure) -> {
|
||||
@@ -905,7 +911,12 @@ public final class CharacterBookController implements Consumer<ControlInput>, Au
|
||||
}
|
||||
|
||||
@org.bukkit.event.EventHandler
|
||||
public void rareAction(io.papermc.paper.event.player.PlayerCustomClickEvent event){if(closed||rarePotions==null||!RARE_USE.equals(event.getIdentifier())||!(event.getCommonConnection() instanceof io.papermc.paper.connection.PlayerGameConnection connection)||event.getTag()==null)return;var player=connection.getPlayer();var view=rareViews.get(player.getUniqueId());if(view==null||view.input().player()!=player)return;String raw=event.getTag().string();if(raw.length()>120)return;var match=RARE_PAYLOAD.matcher(raw);var product=match.matches()?games.dmg.fantasystick.shop.RareProduct.find(match.group(2)).orElse(null):null;if(product==null||!view.nonce().equals(match.group(1))||!view.quantities().getOrDefault(product.id(),java.math.BigInteger.ZERO).equals(rarePotions.quantity(view.input().session().character(),product))||!rareViews.remove(player.getUniqueId(),view)||!view.input().stillCurrent())return;rarePotions.use(player,product,outcome->{if(closed||!view.input().stillCurrent())return;player.sendMessage(switch(outcome.status()){case APPLIED->"Used "+product.displayName()+" and restored "+outcome.healed().toPlainString()+" health.";case FULL_HEALTH->"Potion use refused: health is already full.";case NO_EFFECT->"Potion use refused: no positive healing was accepted.";case NOT_AVAILABLE->"Potion use refused: that item is no longer available.";case STALE->"Potion use refused: the character, session or quantity changed.";case FAILED->"Potion use could not be acknowledged; retained proof prevents replay.";});load(view.input(),0);});}
|
||||
public void rareAction(io.papermc.paper.event.player.PlayerCustomClickEvent event){if(closed||rarePotions==null||rareReskills==null||!RARE_USE.equals(event.getIdentifier())||!(event.getCommonConnection() instanceof io.papermc.paper.connection.PlayerGameConnection connection)||event.getTag()==null)return;var player=connection.getPlayer();var view=rareViews.get(player.getUniqueId());if(view==null||view.input().player()!=player)return;String raw=event.getTag().string();if(raw.length()>120)return;var match=RARE_PAYLOAD.matcher(raw);var product=match.matches()?games.dmg.fantasystick.shop.RareProduct.find(match.group(2)).orElse(null):null;if(product==null||!view.nonce().equals(match.group(1))||!view.quantities().getOrDefault(product.id(),java.math.BigInteger.ZERO).equals(rareInventory.quantity(view.input().session().character(),product))||!rareViews.remove(player.getUniqueId(),view)||!view.input().stillCurrent())return;if(product==games.dmg.fantasystick.shop.RareProduct.RESKILL){var preview=rareReskills.preview(player);if(preview.isEmpty()){player.sendMessage("Reskill preview refused: the character, session or quantity changed.");return;}if(preview.orElseThrow().refund().signum()==0){player.sendMessage("Reskill use refused: this character has no investments to reset.");load(view.input(),0);return;}var confirmation=new ReskillView(UUID.randomUUID().toString(),view.input(),preview.orElseThrow());reskillViews.put(player.getUniqueId(),confirmation);player.openBook(reskillConfirmation(confirmation));return;}if(!product.heals())return;rarePotions.use(player,product,outcome->{if(closed||!view.input().stillCurrent())return;player.sendMessage(switch(outcome.status()){case APPLIED->"Used "+product.displayName()+" and restored "+outcome.healed().toPlainString()+" health.";case FULL_HEALTH->"Potion use refused: health is already full.";case NO_EFFECT->"Potion use refused: no positive healing was accepted.";case NOT_AVAILABLE->"Potion use refused: that item is no longer available.";case STALE->"Potion use refused: the character, session or quantity changed.";case FAILED->"Potion use could not be acknowledged; retained proof prevents replay.";});load(view.input(),0);});}
|
||||
|
||||
private static ItemStack reskillConfirmation(ReskillView view){var item=new ItemStack(Material.WRITTEN_BOOK);var meta=(BookMeta)item.getItemMeta();meta.setTitle("Confirm Reskill");meta.setAuthor("Fantasy Stick");var page=Component.text("Confirm Reskill\n\nRefund: "+view.preview().refund()+" points\nStats → 0\nAbilities/passives removed\nHealth only clamps to the new maximum\nCooldowns retained\n\n").append(Component.text("[Confirm Reskill]",net.kyori.adventure.text.format.NamedTextColor.DARK_RED).clickEvent(net.kyori.adventure.text.event.ClickEvent.custom(RARE_RESKILL_CONFIRM,net.kyori.adventure.nbt.api.BinaryTagHolder.binaryTagHolder("\""+view.nonce()+"\""))));meta.pages(java.util.List.of(page));item.setItemMeta(meta);return item;}
|
||||
|
||||
@org.bukkit.event.EventHandler
|
||||
public void reskillConfirm(io.papermc.paper.event.player.PlayerCustomClickEvent event){if(closed||rareReskills==null||!RARE_RESKILL_CONFIRM.equals(event.getIdentifier())||!(event.getCommonConnection() instanceof io.papermc.paper.connection.PlayerGameConnection connection)||event.getTag()==null)return;var player=connection.getPlayer();var view=reskillViews.get(player.getUniqueId());String raw=event.getTag().string();if(view==null||view.input().player()!=player||raw.length()>80)return;var match=RARE_CONFIRM_PAYLOAD.matcher(raw);if(!match.matches()||!view.nonce().equals(match.group(1))||!reskillViews.remove(player.getUniqueId(),view)||!view.input().stillCurrent())return;rareReskills.confirm(player,view.preview(),outcome->{if(closed)return;player.sendMessage(switch(outcome.status()){case APPLIED->"Used Reskill; all purchased stats, abilities and passives were refunded.";case NOTHING_TO_RESET->"Reskill use refused: this character has no investments to reset.";case NOT_AVAILABLE->"Reskill use refused: that item is no longer available.";case STALE->"Reskill use refused: the character, session, build or quantity changed.";case FAILED->"Reskill could not be acknowledged; retained proof prevents replay.";});if(view.input().stillCurrent())load(view.input(),0);});}
|
||||
|
||||
@org.bukkit.event.EventHandler
|
||||
public void partyAction(io.papermc.paper.event.player.PlayerCustomClickEvent event) { partyControls.click(event); }
|
||||
@@ -922,10 +933,11 @@ public final class CharacterBookController implements Consumer<ControlInput>, Au
|
||||
abilityViews.remove(owner);
|
||||
passiveViews.remove(owner);
|
||||
rareViews.remove(owner);
|
||||
reskillViews.remove(owner);
|
||||
partyControls.forget(owner);
|
||||
}
|
||||
|
||||
@Override public void close() {
|
||||
closed = true; pending.clear(); adminPending.clear(); adminViews.clear(); savedViews.clear(); views.clear(); statViews.clear(); abilityViews.clear(); passiveViews.clear(); rareViews.clear(); partyControls.close();
|
||||
closed = true; pending.clear(); adminPending.clear(); adminViews.clear(); savedViews.clear(); views.clear(); statViews.clear(); abilityViews.clear(); passiveViews.clear(); rareViews.clear(); reskillViews.clear(); partyControls.close();
|
||||
}
|
||||
}
|
||||
@@ -472,6 +472,11 @@ public final class CharacterStorage implements AutoCloseable {
|
||||
/** One character-file transaction owns a rare purchase's exact idempotent coin debit. */
|
||||
public CompletableFuture<RarePurchase> purchaseRare(UUID characterId,BigInteger expectedRevision,UUID operationId,BigInteger price){Objects.requireNonNull(characterId);Objects.requireNonNull(expectedRevision);Objects.requireNonNull(operationId);Objects.requireNonNull(price);if(price.signum()<=0)throw new IllegalArgumentException("Invalid rare purchase");return submit(()->{var found=repository.load(characterId);if(found.isEmpty()||found.orElseThrow().dead())return new RarePurchase(RarePurchaseStatus.UNAVAILABLE,Optional.empty());var old=found.orElseThrow();if(old.rewardReceipts().contains(operationId))return new RarePurchase(RarePurchaseStatus.DUPLICATE,Optional.of(old));if(!old.revision().equals(expectedRevision))return new RarePurchase(RarePurchaseStatus.STALE,Optional.of(old));if(old.coins().compareTo(price)<0)return new RarePurchase(RarePurchaseStatus.INSUFFICIENT,Optional.of(old));var receipts=new java.util.HashSet<>(old.rewardReceipts());if(receipts.size()>=4096)receipts.remove(receipts.stream().min(UUID::compareTo).orElseThrow());receipts.add(operationId);var saved=new CharacterRecord(old.id(),old.name(),old.revision().add(BigInteger.ONE),old.stats(),old.level(),old.experience(),old.unspentPoints(),old.health(),old.learned(),old.loadout(),old.passives(),old.cooldowns(),old.restrictedKills(),false,old.deathId(),old.diedAt(),old.coins().subtract(price),true,receipts,old.pvpCoinEscrow(),old.gear(),old.sheetGeneration());repository.replace(saved,old.revision());return new RarePurchase(RarePurchaseStatus.APPLIED,Optional.of(saved));});}
|
||||
|
||||
public enum ReskillStatus { APPLIED,DUPLICATE,NOTHING_TO_RESET,STALE,UNAVAILABLE }
|
||||
public record Reskill(ReskillStatus status,Optional<CharacterRecord> record){}
|
||||
/** Reset every one-point character investment and preserve identity/progress/deadlines in one revision. */
|
||||
public CompletableFuture<Reskill> reskill(UUID characterId,BigInteger expectedRevision,UUID operationId,java.math.BigDecimal nativeHealthLimit){Objects.requireNonNull(characterId);Objects.requireNonNull(expectedRevision);Objects.requireNonNull(operationId);Objects.requireNonNull(nativeHealthLimit);if(nativeHealthLimit.signum()<=0)throw new IllegalArgumentException("Invalid native health limit");return submit(()->{var found=repository.load(characterId);if(found.isEmpty()||found.orElseThrow().dead())return new Reskill(ReskillStatus.UNAVAILABLE,Optional.empty());var old=found.orElseThrow();if(old.rewardReceipts().contains(operationId))return new Reskill(ReskillStatus.DUPLICATE,Optional.of(old));if(!old.revision().equals(expectedRevision))return new Reskill(ReskillStatus.STALE,Optional.of(old));BigInteger refund=old.stats().values().stream().reduce(BigInteger.ZERO,BigInteger::add).add(BigInteger.valueOf(old.learned().size())).add(BigInteger.valueOf(old.passives().stream().filter(id->!id.isEmpty()).distinct().count()));if(refund.signum()==0)return new Reskill(ReskillStatus.NOTHING_TO_RESET,Optional.of(old));var stats=new java.util.EnumMap<Stat,BigInteger>(Stat.class);for(var stat:Stat.values())stats.put(stat,BigInteger.ZERO);var receipts=new java.util.HashSet<>(old.rewardReceipts());if(receipts.size()>=4096)receipts.remove(receipts.stream().min(UUID::compareTo).orElseThrow());receipts.add(operationId);var health=old.health().min(java.math.BigDecimal.TEN.min(nativeHealthLimit));var saved=new CharacterRecord(old.id(),old.name(),old.revision().add(BigInteger.ONE),stats,old.level(),old.experience(),old.unspentPoints().add(refund),health,Set.of(),List.of("","","","","","",""),List.of("","",""),old.cooldowns(),old.restrictedKills(),false,old.deathId(),old.diedAt(),old.coins(),old.coinsInitialized(),receipts,old.pvpCoinEscrow(),old.gear(),old.sheetGeneration());repository.replace(saved,old.revision());return new Reskill(ReskillStatus.APPLIED,Optional.of(saved));});}
|
||||
|
||||
public enum CombatAwardStatus { APPLIED, SPACING_BLOCKED, AT_CAP, UNCHANGED, DUPLICATE, STALE, UNAVAILABLE }
|
||||
public record CombatAward(CombatAwardStatus status, Optional<CharacterRecord> record, int levels) { }
|
||||
|
||||
@@ -609,7 +614,7 @@ public final class CharacterStorage implements AutoCloseable {
|
||||
java.util.Map<Stat, BigInteger> requirements, BigInteger cost) {
|
||||
Objects.requireNonNull(characterId); Objects.requireNonNull(expectedRevision); Objects.requireNonNull(ability);
|
||||
Objects.requireNonNull(requirements); Objects.requireNonNull(cost);
|
||||
if (ability.isBlank() || cost.signum() <= 0 || requirements.entrySet().stream().anyMatch(entry -> entry.getValue().compareTo(BigInteger.TEN) < 0)) {
|
||||
if (ability.isBlank() || !cost.equals(BigInteger.ONE) || requirements.entrySet().stream().anyMatch(entry -> entry.getValue().compareTo(BigInteger.TEN) < 0)) {
|
||||
throw new IllegalArgumentException("Invalid ability unlock");
|
||||
}
|
||||
return submit(() -> {
|
||||
|
||||
@@ -22,12 +22,12 @@ public final class RareSettings implements AutoCloseable {
|
||||
private final Path directory;private final ExecutorService worker=Executors.newSingleThreadExecutor(task->new Thread(task,"fantasy-rare-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 RareSettings(Path directory,Map<String,String> initial){this.directory=directory.toAbsolutePath();var values=new LinkedHashMap<String,String>();for(var 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 RareMarketRules rules(){var values=effective;var prices=new EnumMap<RareProduct,BigInteger>(RareProduct.class);var stock=new EnumMap<RareProduct,RareMarketRules.StockRange>(RareProduct.class);var healing=new EnumMap<RareProduct,Integer>(RareProduct.class);for(var product:RareProduct.values()){prices.put(product,new BigInteger(values.get(priceKey(product))));stock.put(product,new RareMarketRules.StockRange(whole(values.get(stockKey(product,true)),0,Integer.MAX_VALUE),whole(values.get(stockKey(product,false)),0,Integer.MAX_VALUE)));healing.put(product,whole(values.get(healingKey(product)),0,100));}return new RareMarketRules(prices,whole(values.get(VARIANCE),0,100),stock,healing);}
|
||||
public RareMarketRules rules(){var values=effective;var prices=new EnumMap<RareProduct,BigInteger>(RareProduct.class);var stock=new EnumMap<RareProduct,RareMarketRules.StockRange>(RareProduct.class);var healing=new EnumMap<RareProduct,Integer>(RareProduct.class);for(var product:RareProduct.values()){prices.put(product,new BigInteger(values.get(priceKey(product))));stock.put(product,new RareMarketRules.StockRange(whole(values.get(stockKey(product,true)),0,Integer.MAX_VALUE),whole(values.get(stockKey(product,false)),0,Integer.MAX_VALUE)));if(product.heals())healing.put(product,whole(values.get(healingKey(product)),0,100));}return new RareMarketRules(prices,whole(values.get(VARIANCE),0,100),stock,healing);}
|
||||
public CompletionStage<Update> set(String key,String raw){if(!KEYS.contains(key))throw new IllegalArgumentException("Unknown rare setting");String accepted=Integer.toString(whole(raw,0,key.equals(VARIANCE)||key.endsWith("-healing-percent")?100:Integer.MAX_VALUE));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;}
|
||||
public static String priceKey(RareProduct product){return "rare-price-"+product.id();}public static String stockKey(RareProduct product,boolean minimum){return "rare-stock-"+product.id()+(minimum?"-min":"-max");}public static String healingKey(RareProduct product){return "rare-"+product.id()+"-healing-percent";}
|
||||
private static Map<String,String> defaults(){var values=new LinkedHashMap<String,String>();values.put(VARIANCE,"10");for(var product:RareProduct.values()){values.put(priceKey(product),Integer.toString(product.basePrice()));values.put(stockKey(product,true),"0");values.put(stockKey(product,false),Integer.toString(product.maximumStock()));values.put(healingKey(product),Integer.toString(product.defaultHealingPercent()));}return Map.copyOf(values);}
|
||||
private static void validate(Map<String,String> values){whole(values.get(VARIANCE),0,100);for(var product:RareProduct.values()){whole(values.get(priceKey(product)),0,Integer.MAX_VALUE);int min=whole(values.get(stockKey(product,true)),0,Integer.MAX_VALUE),max=whole(values.get(stockKey(product,false)),0,Integer.MAX_VALUE);if(min>max)throw new IllegalArgumentException("Stock minimum exceeds maximum");whole(values.get(healingKey(product)),0,100);}}
|
||||
private static Map<String,String> defaults(){var values=new LinkedHashMap<String,String>();values.put(VARIANCE,"10");for(var product:RareProduct.values()){values.put(priceKey(product),Integer.toString(product.basePrice()));values.put(stockKey(product,true),"0");values.put(stockKey(product,false),Integer.toString(product.maximumStock()));if(product.heals())values.put(healingKey(product),Integer.toString(product.defaultHealingPercent()));}return Map.copyOf(values);}
|
||||
private static void validate(Map<String,String> values){whole(values.get(VARIANCE),0,100);for(var product:RareProduct.values()){whole(values.get(priceKey(product)),0,Integer.MAX_VALUE);int min=whole(values.get(stockKey(product,true)),0,Integer.MAX_VALUE),max=whole(values.get(stockKey(product,false)),0,Integer.MAX_VALUE);if(min>max)throw new IllegalArgumentException("Stock minimum exceeds maximum");if(product.heals())whole(values.get(healingKey(product)),0,100);}}
|
||||
private static int whole(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 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-rare-",".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);}
|
||||
|
||||
@@ -17,11 +17,12 @@ import org.yaml.snakeyaml.constructor.SafeConstructor;
|
||||
public final class YamlRareInventoryRepository {
|
||||
private final Path file;
|
||||
public YamlRareInventoryRepository(Path data){file=data.toAbsolutePath().resolve("rare-inventory.yml");}
|
||||
public RareInventoryState load()throws IOException{if(Files.notExists(file))return new RareInventoryState();try{if(Files.size(file)>1_048_576)throw new IllegalArgumentException();Object decoded=yaml().load(Files.readString(file,StandardCharsets.UTF_8));if(!(decoded instanceof Map<?,?> root)||Integer.parseInt(String.valueOf(root.get("schema-version")))!=1)throw new IllegalArgumentException();var items=new LinkedHashMap<UUID,Map<String,BigInteger>>();for(Object value:list(root.get("characters"))){var row=map(value);var goods=new LinkedHashMap<String,BigInteger>();for(Object itemValue:list(row.get("items"))){var item=map(itemValue);goods.put(text(item,"product"),new BigInteger(text(item,"quantity")));}items.put(UUID.fromString(text(row,"character")),goods);}var receipts=new LinkedHashMap<UUID,RareInventoryState.PurchaseReceipt>();for(Object value:list(root.get("purchase-receipts"))){var row=map(value);receipts.put(UUID.fromString(text(row,"operation")),new RareInventoryState.PurchaseReceipt(UUID.fromString(text(row,"character")),text(row,"product")));}var uses=new LinkedHashMap<UUID,RareInventoryState.Use>();for(Object value:list(root.get("uses"))){var row=map(value);UUID operation=UUID.fromString(text(row,"operation"));uses.put(operation,new RareInventoryState.Use(operation,UUID.fromString(text(row,"character")),text(row,"product"),new BigInteger(text(row,"expected-quantity")),new BigDecimal(text(row,"health-before")),new BigDecimal(text(row,"maximum")),Integer.parseInt(text(row,"percent")),RareInventoryState.UsePhase.valueOf(text(row,"phase"))));}return new RareInventoryState(items,receipts,uses);}catch(RuntimeException invalid){throw new IOException("Invalid rare inventory",invalid);}}
|
||||
public void save(RareInventoryState state)throws IOException{Map<String,Object> root=new LinkedHashMap<>();root.put("schema-version",1);root.put("characters",state.items().entrySet().stream().sorted(Map.Entry.comparingByKey()).map(entry->{Map<String,Object> row=new LinkedHashMap<>();row.put("character",entry.getKey().toString());row.put("items",entry.getValue().entrySet().stream().sorted(Map.Entry.comparingByKey()).map(item->{Map<String,Object> value=new LinkedHashMap<>();value.put("product",item.getKey());value.put("quantity",item.getValue().toString());return value;}).toList());return row;}).toList());root.put("purchase-receipts",state.purchaseReceipts().entrySet().stream().sorted(Map.Entry.comparingByKey()).map(entry->{Map<String,Object> row=new LinkedHashMap<>();row.put("operation",entry.getKey().toString());row.put("character",entry.getValue().character().toString());row.put("product",entry.getValue().product());return row;}).toList());root.put("uses",state.uses().values().stream().sorted(Comparator.comparing(RareInventoryState.Use::operation)).map(use->{Map<String,Object> row=new LinkedHashMap<>();row.put("operation",use.operation().toString());row.put("character",use.character().toString());row.put("product",use.product());row.put("expected-quantity",use.expectedQuantity().toString());row.put("health-before",use.healthBefore().toPlainString());row.put("maximum",use.maximum().toPlainString());row.put("percent",Integer.toString(use.percent()));row.put("phase",use.phase().name());return row;}).toList());write(yaml().dump(root));}
|
||||
public RareInventoryState load()throws IOException{if(Files.notExists(file))return new RareInventoryState();try{if(Files.size(file)>1_048_576)throw new IllegalArgumentException();Object decoded=yaml().load(Files.readString(file,StandardCharsets.UTF_8));if(!(decoded instanceof Map<?,?> root)||(Integer.parseInt(String.valueOf(root.get("schema-version")))<1||Integer.parseInt(String.valueOf(root.get("schema-version")))>2))throw new IllegalArgumentException();var items=new LinkedHashMap<UUID,Map<String,BigInteger>>();for(Object value:list(root.get("characters"))){var row=map(value);var goods=new LinkedHashMap<String,BigInteger>();for(Object itemValue:list(row.get("items"))){var item=map(itemValue);goods.put(text(item,"product"),new BigInteger(text(item,"quantity")));}items.put(UUID.fromString(text(row,"character")),goods);}var receipts=new LinkedHashMap<UUID,RareInventoryState.PurchaseReceipt>();for(Object value:list(root.get("purchase-receipts"))){var row=map(value);receipts.put(UUID.fromString(text(row,"operation")),new RareInventoryState.PurchaseReceipt(UUID.fromString(text(row,"character")),text(row,"product")));}var uses=new LinkedHashMap<UUID,RareInventoryState.Use>();for(Object value:list(root.get("uses"))){var row=map(value);UUID operation=UUID.fromString(text(row,"operation"));uses.put(operation,new RareInventoryState.Use(operation,UUID.fromString(text(row,"character")),text(row,"product"),new BigInteger(text(row,"expected-quantity")),decimal(row,"health-before"),decimal(row,"maximum"),row.get("percent")==null?0:Integer.parseInt(text(row,"percent")),RareInventoryState.UsePhase.valueOf(text(row,"phase"))));}return new RareInventoryState(items,receipts,uses);}catch(RuntimeException invalid){throw new IOException("Invalid rare inventory",invalid);}}
|
||||
public void save(RareInventoryState state)throws IOException{Map<String,Object> root=new LinkedHashMap<>();root.put("schema-version",2);root.put("characters",state.items().entrySet().stream().sorted(Map.Entry.comparingByKey()).map(entry->{Map<String,Object> row=new LinkedHashMap<>();row.put("character",entry.getKey().toString());row.put("items",entry.getValue().entrySet().stream().sorted(Map.Entry.comparingByKey()).map(item->{Map<String,Object> value=new LinkedHashMap<>();value.put("product",item.getKey());value.put("quantity",item.getValue().toString());return value;}).toList());return row;}).toList());root.put("purchase-receipts",state.purchaseReceipts().entrySet().stream().sorted(Map.Entry.comparingByKey()).map(entry->{Map<String,Object> row=new LinkedHashMap<>();row.put("operation",entry.getKey().toString());row.put("character",entry.getValue().character().toString());row.put("product",entry.getValue().product());return row;}).toList());root.put("uses",state.uses().values().stream().sorted(Comparator.comparing(RareInventoryState.Use::operation)).map(use->{Map<String,Object> row=new LinkedHashMap<>();row.put("operation",use.operation().toString());row.put("character",use.character().toString());row.put("product",use.product());row.put("expected-quantity",use.expectedQuantity().toString());if(use.healthBefore()!=null){row.put("health-before",use.healthBefore().toPlainString());row.put("maximum",use.maximum().toPlainString());row.put("percent",Integer.toString(use.percent()));}row.put("phase",use.phase().name());return row;}).toList());write(yaml().dump(root));}
|
||||
private void write(String content)throws IOException{Files.createDirectories(file.getParent());Path temporary=Files.createTempFile(file.getParent(),"rare-inventory-",".tmp");try{byte[] bytes=content.getBytes(StandardCharsets.UTF_8);try(var output=FileChannel.open(temporary,StandardOpenOption.WRITE)){var buffer=ByteBuffer.wrap(bytes);while(buffer.hasRemaining())output.write(buffer);output.force(true);}try{Files.move(temporary,file,StandardCopyOption.ATOMIC_MOVE,StandardCopyOption.REPLACE_EXISTING);}catch(AtomicMoveNotSupportedException unavailable){throw new IOException("Atomic rare inventory persistence unavailable",unavailable);}DurableFiles.forceDirectory(file.getParent());}finally{Files.deleteIfExists(temporary);}}
|
||||
private static Yaml yaml(){var options=new LoaderOptions();options.setAllowDuplicateKeys(false);options.setMaxAliasesForCollections(0);options.setCodePointLimit(1_048_576);return new Yaml(new SafeConstructor(options));}
|
||||
private static List<?> list(Object value){if(value==null)return List.of();if(value instanceof List<?> values)return values;throw new IllegalArgumentException();}
|
||||
private static Map<?,?> map(Object value){if(value instanceof Map<?,?> values)return values;throw new IllegalArgumentException();}
|
||||
private static String text(Map<?,?> map,String key){Object value=map.get(key);if(value instanceof String text)return text;throw new IllegalArgumentException("Invalid "+key);}
|
||||
private static BigDecimal decimal(Map<?,?> map,String key){return map.get(key)==null?null:new BigDecimal(text(map,key));}
|
||||
}
|
||||
@@ -17,7 +17,8 @@ public record RareCatalog(LocalDate day,UUID revision,Instant refreshedAt,Refres
|
||||
public record Offer(BigInteger price,int remaining){public Offer{Objects.requireNonNull(price);if(price.signum()<=0||remaining<0)throw new IllegalArgumentException("Invalid offer");}}
|
||||
public record Transaction(RareProduct product,TransactionState state){public Transaction{Objects.requireNonNull(product);Objects.requireNonNull(state);}}
|
||||
public RareCatalog(LocalDate day,UUID revision,Instant refreshedAt,RefreshReason reason,Map<RareProduct,Offer> products){this(day,revision,refreshedAt,reason,products,Map.of());}
|
||||
public RareCatalog{Objects.requireNonNull(day);Objects.requireNonNull(revision);Objects.requireNonNull(refreshedAt);Objects.requireNonNull(reason);var copy=new EnumMap<RareProduct,Offer>(RareProduct.class);copy.putAll(products);if(copy.size()!=RareProduct.values().length)throw new IllegalArgumentException("Catalog must contain every delivered product");products=Map.copyOf(copy);transactions=Map.copyOf(transactions);}
|
||||
public RareCatalog{Objects.requireNonNull(day);Objects.requireNonNull(revision);Objects.requireNonNull(refreshedAt);Objects.requireNonNull(reason);var copy=new EnumMap<RareProduct,Offer>(RareProduct.class);copy.putAll(products);products=Map.copyOf(copy);transactions=Map.copyOf(transactions);}
|
||||
public boolean available(RareProduct product){return products.containsKey(Objects.requireNonNull(product));}
|
||||
public Offer offer(RareProduct product){var offer=products.get(Objects.requireNonNull(product));if(offer==null)throw new IllegalArgumentException("Product unavailable");return offer;}
|
||||
public RareCatalog reserve(UUID operation,RareProduct product){var existing=transactions.get(operation);if(existing!=null){if(existing.product()!=product)throw new IllegalArgumentException("Operation collision");return this;}var offer=offer(product);if(offer.remaining()==0)throw new IllegalStateException("Sold out");var nextProducts=new LinkedHashMap<>(products);nextProducts.put(product,new Offer(offer.price(),offer.remaining()-1));var nextTransactions=new LinkedHashMap<>(transactions);nextTransactions.put(operation,new Transaction(product,TransactionState.RESERVED));return new RareCatalog(day,revision,refreshedAt,reason,nextProducts,nextTransactions);}
|
||||
public RareCatalog settle(UUID operation,boolean consumed){var transaction=transactions.get(operation);if(transaction==null||transaction.state()!=TransactionState.RESERVED)return this;var nextProducts=new LinkedHashMap<>(products);if(!consumed){var offer=offer(transaction.product());nextProducts.put(transaction.product(),new Offer(offer.price(),Math.addExact(offer.remaining(),1)));}var nextTransactions=new LinkedHashMap<>(transactions);nextTransactions.put(operation,new Transaction(transaction.product(),consumed?TransactionState.CONSUMED:TransactionState.CANCELLED));return new RareCatalog(day,revision,refreshedAt,reason,nextProducts,nextTransactions);}
|
||||
|
||||
@@ -24,7 +24,8 @@ public final class RareInventoryDirectory implements AutoCloseable {
|
||||
public BigInteger quantity(UUID character,RareProduct product){return snapshot.quantity(character,product.id());}
|
||||
public java.util.List<Item> inventory(UUID character){return snapshot.items().getOrDefault(character,Map.of()).entrySet().stream().sorted(Map.Entry.comparingByKey()).map(entry->{var product=RareProduct.find(entry.getKey());return new Item(entry.getKey(),product.map(RareProduct::displayName).orElse(entry.getKey()),entry.getValue(),product.isPresent());}).toList();}
|
||||
public CompletableFuture<AddStatus> add(UUID character,RareProduct product,UUID operation){Objects.requireNonNull(character);Objects.requireNonNull(product);Objects.requireNonNull(operation);return submit(()->{var receipt=snapshot.purchaseReceipts().get(operation);if(receipt!=null){if(!receipt.character().equals(character)||!receipt.product().equals(product.id()))throw new IOException("Rare purchase operation collision");return AddStatus.DUPLICATE;}var items=mutableItems(snapshot.items());var goods=items.computeIfAbsent(character,ignored->new LinkedHashMap<>());goods.merge(product.id(),BigInteger.ONE,BigInteger::add);var receipts=new LinkedHashMap<>(snapshot.purchaseReceipts());receipts.put(operation,new RareInventoryState.PurchaseReceipt(character,product.id()));save(new RareInventoryState(items,receipts,snapshot.uses()));return AddStatus.APPLIED;});}
|
||||
public CompletableFuture<UseOutcome> reserveUse(UUID character,RareProduct product,UUID operation,BigInteger expectedQuantity,BigDecimal healthBefore,BigDecimal maximum,int percent){Objects.requireNonNull(character);Objects.requireNonNull(product);Objects.requireNonNull(operation);return submit(()->{var existing=snapshot.uses().get(operation);if(existing!=null){if(!existing.character().equals(character)||!existing.product().equals(product.id()))throw new IOException("Rare use operation collision");return new UseOutcome(status(existing.phase()),existing);}var current=snapshot.quantity(character,product.id());if(current.signum()<=0)return new UseOutcome(UseStatus.NOT_AVAILABLE,null);if(!current.equals(expectedQuantity))return new UseOutcome(UseStatus.STALE,null);RareInventoryState.Use use;try{use=new RareInventoryState.Use(operation,character,product.id(),expectedQuantity,healthBefore,maximum,percent,RareInventoryState.UsePhase.RESERVED);}catch(IllegalArgumentException refused){return new UseOutcome(UseStatus.NOT_AVAILABLE,null);}var items=mutableItems(snapshot.items());var goods=items.get(character);var remaining=current.subtract(BigInteger.ONE);if(remaining.signum()==0)goods.remove(product.id());else goods.put(product.id(),remaining);if(goods.isEmpty())items.remove(character);var uses=new LinkedHashMap<>(snapshot.uses());uses.put(operation,use);save(new RareInventoryState(items,snapshot.purchaseReceipts(),uses));return new UseOutcome(UseStatus.RESERVED,use);});}
|
||||
public CompletableFuture<UseOutcome> reserveUse(UUID character,RareProduct product,UUID operation,BigInteger expectedQuantity){if(product.heals())throw new IllegalArgumentException("Healing use requires captured health policy");return reserveUse(character,product,operation,expectedQuantity,null,null,0);}
|
||||
public CompletableFuture<UseOutcome> reserveUse(UUID character,RareProduct product,UUID operation,BigInteger expectedQuantity,BigDecimal healthBefore,BigDecimal maximum,int percent){Objects.requireNonNull(character);Objects.requireNonNull(product);Objects.requireNonNull(operation);if(!product.heals()&&(healthBefore!=null||maximum!=null||percent!=0))throw new IllegalArgumentException("Non-healing use cannot carry healing policy");return submit(()->{var existing=snapshot.uses().get(operation);if(existing!=null){if(!existing.character().equals(character)||!existing.product().equals(product.id()))throw new IOException("Rare use operation collision");return new UseOutcome(status(existing.phase()),existing);}var current=snapshot.quantity(character,product.id());if(current.signum()<=0)return new UseOutcome(UseStatus.NOT_AVAILABLE,null);if(!current.equals(expectedQuantity))return new UseOutcome(UseStatus.STALE,null);RareInventoryState.Use use;try{use=new RareInventoryState.Use(operation,character,product.id(),expectedQuantity,healthBefore,maximum,percent,RareInventoryState.UsePhase.RESERVED);}catch(IllegalArgumentException refused){return new UseOutcome(UseStatus.NOT_AVAILABLE,null);}var items=mutableItems(snapshot.items());var goods=items.get(character);var remaining=current.subtract(BigInteger.ONE);if(remaining.signum()==0)goods.remove(product.id());else goods.put(product.id(),remaining);if(goods.isEmpty())items.remove(character);var uses=new LinkedHashMap<>(snapshot.uses());uses.put(operation,use);save(new RareInventoryState(items,snapshot.purchaseReceipts(),uses));return new UseOutcome(UseStatus.RESERVED,use);});}
|
||||
public CompletableFuture<UseStatus> commitUse(UUID operation){return updateUse(operation,true);}
|
||||
public CompletableFuture<UseStatus> refundUse(UUID operation){return updateUse(operation,false);}
|
||||
private CompletableFuture<UseStatus> updateUse(UUID operation,boolean commit){return submit(()->{var use=snapshot.uses().get(operation);if(use==null)return UseStatus.NOT_AVAILABLE;if(use.phase()!=RareInventoryState.UsePhase.RESERVED)return status(use.phase());var phase=commit?RareInventoryState.UsePhase.COMMITTED:RareInventoryState.UsePhase.REFUNDED;var changed=new RareInventoryState.Use(use.operation(),use.character(),use.product(),use.expectedQuantity(),use.healthBefore(),use.maximum(),use.percent(),phase);var uses=new LinkedHashMap<>(snapshot.uses());uses.put(operation,changed);var items=mutableItems(snapshot.items());if(!commit)items.computeIfAbsent(use.character(),ignored->new LinkedHashMap<>()).merge(use.product(),BigInteger.ONE,BigInteger::add);save(new RareInventoryState(items,snapshot.purchaseReceipts(),uses));return status(phase);});}
|
||||
|
||||
@@ -15,7 +15,7 @@ public record RareInventoryState(Map<UUID,Map<String,BigInteger>> items,
|
||||
public record PurchaseReceipt(UUID character,String product){public PurchaseReceipt{Objects.requireNonNull(character);if(product==null||product.isBlank())throw new IllegalArgumentException("Invalid product");}}
|
||||
public record Use(UUID operation,UUID character,String product,BigInteger expectedQuantity,
|
||||
BigDecimal healthBefore,BigDecimal maximum,int percent,UsePhase phase){
|
||||
public Use{Objects.requireNonNull(operation);Objects.requireNonNull(character);Objects.requireNonNull(product);Objects.requireNonNull(expectedQuantity);Objects.requireNonNull(healthBefore);Objects.requireNonNull(maximum);Objects.requireNonNull(phase);if(expectedQuantity.signum()<=0||healthBefore.signum()<0||maximum.signum()<=0||healthBefore.compareTo(maximum)>=0||percent<=0||percent>100)throw new IllegalArgumentException("Invalid rare item use");}
|
||||
public Use{Objects.requireNonNull(operation);Objects.requireNonNull(character);Objects.requireNonNull(product);Objects.requireNonNull(expectedQuantity);Objects.requireNonNull(phase);boolean healing=healthBefore!=null||maximum!=null||percent!=0;if(expectedQuantity.signum()<=0||RareProduct.find(product).map(RareProduct::heals).filter(value->value!=healing).isPresent()||healing&&(healthBefore==null||maximum==null||healthBefore.signum()<0||maximum.signum()<=0||healthBefore.compareTo(maximum)>=0||percent<=0||percent>100))throw new IllegalArgumentException("Invalid rare item use");}
|
||||
}
|
||||
public RareInventoryState(){this(Map.of(),Map.of(),Map.of());}
|
||||
public RareInventoryState{var itemCopy=new LinkedHashMap<UUID,Map<String,BigInteger>>();for(var entry:items.entrySet()){var values=new LinkedHashMap<String,BigInteger>();for(var value:entry.getValue().entrySet()){if(value.getKey().isBlank()||value.getValue().signum()<0)throw new IllegalArgumentException("Invalid inventory");if(value.getValue().signum()>0)values.put(value.getKey(),value.getValue());}if(!values.isEmpty())itemCopy.put(entry.getKey(),Map.copyOf(values));}items=Map.copyOf(itemCopy);purchaseReceipts=Map.copyOf(purchaseReceipts);uses=Map.copyOf(uses);}
|
||||
|
||||
@@ -20,7 +20,7 @@ public final class RareMarket implements AutoCloseable {
|
||||
public static Instant nextScheduledRestock(Instant now){return now.atZone(ZoneOffset.UTC).toLocalDate().plusDays(1).atStartOfDay(ZoneOffset.UTC).toInstant();}
|
||||
public CompletionStage<PurchaseOutcome> purchase(UUID character,BigInteger expectedCharacterRevision,UUID expectedCatalogRevision,RareProduct product){return readiness.thenCompose(ignored->submit(()->purchaseBlocking(character,expectedCharacterRevision,expectedCatalogRevision,product)));}
|
||||
private void initialize()throws Exception{snapshot=catalogs.load().orElse(null);var plans=operations.load().toCompletableFuture().join();if(snapshot==null&&!plans.isEmpty())throw new IOException("Rare catalog missing for pending purchases");for(var plan:plans)execute(plan);if(snapshot!=null&&!snapshot.transactions().isEmpty()){var next=snapshot;for(var entry:snapshot.transactions().entrySet()){if(entry.getValue().state()==RareCatalog.TransactionState.RESERVED)throw new IOException("Orphan reserved rare purchase "+entry.getKey());next=next.prune(entry.getKey());}persist(next,false);}ensureCurrent(RareCatalog.RefreshReason.STARTUP);initialized=true;}
|
||||
private PurchaseOutcome purchaseBlocking(UUID character,BigInteger expectedCharacterRevision,UUID expectedCatalogRevision,RareProduct product)throws Exception{var catalog=ensureCurrent(RareCatalog.RefreshReason.SCHEDULED);if(!catalog.transactions().isEmpty())return new PurchaseOutcome(PurchaseStatus.FAILED,Optional.empty(),catalog);if(!catalog.revision().equals(expectedCatalogRevision))return new PurchaseOutcome(PurchaseStatus.STALE,Optional.empty(),catalog);if(catalog.offer(product).remaining()==0)return new PurchaseOutcome(PurchaseStatus.SOLD_OUT,Optional.empty(),catalog);var plan=new RarePurchaseOperationStore.Plan(UUID.randomUUID(),character,expectedCharacterRevision,catalog.revision(),product,catalog.offer(product).price());operations.prepare(plan).toCompletableFuture().join();return execute(plan);}
|
||||
private PurchaseOutcome purchaseBlocking(UUID character,BigInteger expectedCharacterRevision,UUID expectedCatalogRevision,RareProduct product)throws Exception{var catalog=ensureCurrent(RareCatalog.RefreshReason.SCHEDULED);if(!catalog.transactions().isEmpty())return new PurchaseOutcome(PurchaseStatus.FAILED,Optional.empty(),catalog);if(!catalog.revision().equals(expectedCatalogRevision))return new PurchaseOutcome(PurchaseStatus.STALE,Optional.empty(),catalog);if(!catalog.available(product))return new PurchaseOutcome(PurchaseStatus.UNAVAILABLE,Optional.empty(),catalog);if(catalog.offer(product).remaining()==0)return new PurchaseOutcome(PurchaseStatus.SOLD_OUT,Optional.empty(),catalog);var plan=new RarePurchaseOperationStore.Plan(UUID.randomUUID(),character,expectedCharacterRevision,catalog.revision(),product,catalog.offer(product).price());operations.prepare(plan).toCompletableFuture().join();return execute(plan);}
|
||||
private PurchaseOutcome execute(RarePurchaseOperationStore.Plan plan)throws Exception{var catalog=Objects.requireNonNull(snapshot,"Rare catalog unavailable");if(!catalog.revision().equals(plan.catalogRevision()))throw new IOException("Pending rare purchase belongs to another catalog");var transaction=catalog.transactions().get(plan.id());if(transaction==null){try{catalog=catalog.reserve(plan.id(),plan.product());}catch(IllegalStateException soldOut){operations.complete(plan.id()).toCompletableFuture().join();return new PurchaseOutcome(PurchaseStatus.SOLD_OUT,Optional.empty(),catalog);}persist(catalog,false);transaction=catalog.transactions().get(plan.id());}if(transaction.product()!=plan.product())throw new IOException("Rare reservation product mismatch");if(transaction.state()!=RareCatalog.TransactionState.RESERVED){if(transaction.state()==RareCatalog.TransactionState.CONSUMED)inventory.add(plan.character(),plan.product(),plan.id()).join();operations.complete(plan.id()).toCompletableFuture().join();var pruned=catalog.prune(plan.id());persist(pruned,false);return new PurchaseOutcome(transaction.state()==RareCatalog.TransactionState.CONSUMED?PurchaseStatus.APPLIED:PurchaseStatus.FAILED,characters.find(plan.character()).join(),pruned);}var purchase=characters.purchaseRare(plan.character(),plan.expectedCharacterRevision(),plan.id(),plan.price()).join();boolean consumed=purchase.status()==CharacterStorage.RarePurchaseStatus.APPLIED||purchase.status()==CharacterStorage.RarePurchaseStatus.DUPLICATE;if(consumed)inventory.add(plan.character(),plan.product(),plan.id()).join();catalog=catalog.settle(plan.id(),consumed);persist(catalog,consumed);operations.complete(plan.id()).toCompletableFuture().join();catalog=catalog.prune(plan.id());persist(catalog,false);var status=switch(purchase.status()){case APPLIED,DUPLICATE->PurchaseStatus.APPLIED;case INSUFFICIENT->PurchaseStatus.INSUFFICIENT;case STALE->PurchaseStatus.STALE;case UNAVAILABLE->PurchaseStatus.UNAVAILABLE;};return new PurchaseOutcome(status,purchase.record(),catalog);}
|
||||
private RareCatalog ensureCurrent(RareCatalog.RefreshReason reason)throws IOException{var today=LocalDate.now(clock.withZone(ZoneOffset.UTC));if(snapshot!=null&&snapshot.day().equals(today))return snapshot;if(snapshot!=null&&!snapshot.transactions().isEmpty())throw new IOException("Rare purchases unresolved at rollover");var generated=RareCatalogGenerator.generate(today,clock.instant().truncatedTo(java.time.temporal.ChronoUnit.SECONDS),reason,rules.get(),random);persist(generated,true);return generated;}
|
||||
private void persist(RareCatalog catalog,boolean notify)throws IOException{catalogs.save(catalog);snapshot=catalog;if(notify&&initialized)try{listener.accept(catalog);}catch(RuntimeException ignored){}}
|
||||
|
||||
@@ -16,9 +16,9 @@ public record RareMarketRules(Map<RareProduct,BigInteger> basePrices,int varianc
|
||||
for(var product:RareProduct.values()){
|
||||
var price=Objects.requireNonNull(basePrices.get(product),"Missing price");if(price.signum()<0)throw new IllegalArgumentException("Negative price");prices.put(product,price);
|
||||
ranges.put(product,Objects.requireNonNull(stock.get(product),"Missing stock"));
|
||||
int percent=Objects.requireNonNull(healingPercent.get(product),"Missing healing");if(percent<0||percent>100)throw new IllegalArgumentException("Invalid healing percent");healing.put(product,percent);
|
||||
if(product.heals()){int percent=Objects.requireNonNull(healingPercent.get(product),"Missing healing");if(percent<0||percent>100)throw new IllegalArgumentException("Invalid healing percent");healing.put(product,percent);}
|
||||
}
|
||||
basePrices=Map.copyOf(prices);stock=Map.copyOf(ranges);healingPercent=Map.copyOf(healing);
|
||||
}
|
||||
public static RareMarketRules defaults(){var prices=new EnumMap<RareProduct,BigInteger>(RareProduct.class);var stock=new EnumMap<RareProduct,StockRange>(RareProduct.class);var healing=new EnumMap<RareProduct,Integer>(RareProduct.class);for(var product:RareProduct.values()){prices.put(product,BigInteger.valueOf(product.basePrice()));stock.put(product,new StockRange(0,product.maximumStock()));healing.put(product,product.defaultHealingPercent());}return new RareMarketRules(prices,10,stock,healing);}
|
||||
public static RareMarketRules defaults(){var prices=new EnumMap<RareProduct,BigInteger>(RareProduct.class);var stock=new EnumMap<RareProduct,StockRange>(RareProduct.class);var healing=new EnumMap<RareProduct,Integer>(RareProduct.class);for(var product:RareProduct.values()){prices.put(product,BigInteger.valueOf(product.basePrice()));stock.put(product,new StockRange(0,product.maximumStock()));if(product.heals())healing.put(product,product.defaultHealingPercent());}return new RareMarketRules(prices,10,stock,healing);}
|
||||
}
|
||||
@@ -23,9 +23,9 @@ public final class RarePotionService {
|
||||
private final RareInventoryDirectory inventory;private final RareSettings settings;private final CharacterStorage characters;private final EquipmentSessions sessions;private final Consumer<EntityRegainHealthEvent> healingEvents;private final Consumer<Runnable> nextTick;private final Consumer<Throwable> failures;
|
||||
public RarePotionService(RareInventoryDirectory inventory,RareSettings settings,CharacterStorage characters,EquipmentSessions sessions,Consumer<EntityRegainHealthEvent> healingEvents,Consumer<Runnable> nextTick,Consumer<Throwable> failures){this.inventory=Objects.requireNonNull(inventory);this.settings=Objects.requireNonNull(settings);this.characters=Objects.requireNonNull(characters);this.sessions=Objects.requireNonNull(sessions);this.healingEvents=Objects.requireNonNull(healingEvents);this.nextTick=Objects.requireNonNull(nextTick);this.failures=Objects.requireNonNull(failures);}
|
||||
/** Ambiguous pre-restart native delivery is consumed but never replayed onto a replacement holder. */
|
||||
public void install(){for(var use:inventory.unresolvedUses())inventory.commitUse(use.operation()).exceptionally(failure->{report(failure);return RareInventoryDirectory.UseStatus.RESERVED;});}
|
||||
public void install(){for(var use:inventory.unresolvedUses())if(RareProduct.find(use.product()).map(RareProduct::heals).orElse(false))inventory.commitUse(use.operation()).exceptionally(failure->{report(failure);return RareInventoryDirectory.UseStatus.RESERVED;});}
|
||||
public BigInteger quantity(UUID character,RareProduct product){return inventory.quantity(character,product);}
|
||||
public void use(Player player,RareProduct product,Consumer<Outcome> result){var context=context(player);if(context.isEmpty()){result.accept(new Outcome(Status.STALE,BigDecimal.ZERO));return;}var captured=context.orElseThrow();var attribute=player.getAttribute(Attribute.MAX_HEALTH);double current=player.getHealth(),maximum=attribute==null?Double.NaN:attribute.getValue();if(!Double.isFinite(current)||!Double.isFinite(maximum)||maximum<=0||current>=maximum){result.accept(new Outcome(Status.FULL_HEALTH,BigDecimal.ZERO));return;}int percent=settings.rules().healingPercent().get(product);double proposed=Math.min(maximum-current,maximum*percent/100d);if(!Double.isFinite(proposed)||proposed<=0){result.accept(new Outcome(Status.NO_EFFECT,BigDecimal.ZERO));return;}var event=new EntityRegainHealthEvent(player,proposed,EntityRegainHealthEvent.RegainReason.CUSTOM);healingEvents.accept(event);double accepted=Math.min(proposed,Math.min(maximum-current,event.getAmount()));if(event.isCancelled()||!Double.isFinite(accepted)||accepted<=0){result.accept(new Outcome(Status.NO_EFFECT,BigDecimal.ZERO));return;}UUID operation=UUID.randomUUID();BigInteger expectedQuantity=inventory.quantity(captured.record().id(),product);BigDecimal before=BigDecimal.valueOf(current),limit=BigDecimal.valueOf(maximum).min(NativeHealthLimit.read()),target=BigDecimal.valueOf(current+accepted).min(limit);inventory.reserveUse(captured.record().id(),product,operation,expectedQuantity,before,limit,percent).whenComplete((reservation,reserveFailure)->{if(reserveFailure!=null){report(reserveFailure);publish(()->result.accept(new Outcome(Status.FAILED,BigDecimal.ZERO)));return;}if(reservation.status()!=RareInventoryDirectory.UseStatus.RESERVED){publish(()->result.accept(new Outcome(reservation.status()==RareInventoryDirectory.UseStatus.NOT_AVAILABLE?Status.NOT_AVAILABLE:Status.STALE,BigDecimal.ZERO)));return;}characters.saveHealth(captured.record().id(),captured.record().revision(),target,limit).whenComplete((saved,saveFailure)->publish(()->complete(player,captured,operation,accepted,saved,saveFailure,result)));});}
|
||||
public void use(Player player,RareProduct product,Consumer<Outcome> result){if(!product.heals()){result.accept(new Outcome(Status.NO_EFFECT,BigDecimal.ZERO));return;}var context=context(player);if(context.isEmpty()){result.accept(new Outcome(Status.STALE,BigDecimal.ZERO));return;}var captured=context.orElseThrow();var attribute=player.getAttribute(Attribute.MAX_HEALTH);double current=player.getHealth(),maximum=attribute==null?Double.NaN:attribute.getValue();if(!Double.isFinite(current)||!Double.isFinite(maximum)||maximum<=0||current>=maximum){result.accept(new Outcome(Status.FULL_HEALTH,BigDecimal.ZERO));return;}int percent=settings.rules().healingPercent().get(product);double proposed=Math.min(maximum-current,maximum*percent/100d);if(!Double.isFinite(proposed)||proposed<=0){result.accept(new Outcome(Status.NO_EFFECT,BigDecimal.ZERO));return;}var event=new EntityRegainHealthEvent(player,proposed,EntityRegainHealthEvent.RegainReason.CUSTOM);healingEvents.accept(event);double accepted=Math.min(proposed,Math.min(maximum-current,event.getAmount()));if(event.isCancelled()||!Double.isFinite(accepted)||accepted<=0){result.accept(new Outcome(Status.NO_EFFECT,BigDecimal.ZERO));return;}UUID operation=UUID.randomUUID();BigInteger expectedQuantity=inventory.quantity(captured.record().id(),product);BigDecimal before=BigDecimal.valueOf(current),limit=BigDecimal.valueOf(maximum).min(NativeHealthLimit.read()),target=BigDecimal.valueOf(current+accepted).min(limit);inventory.reserveUse(captured.record().id(),product,operation,expectedQuantity,before,limit,percent).whenComplete((reservation,reserveFailure)->{if(reserveFailure!=null){report(reserveFailure);publish(()->result.accept(new Outcome(Status.FAILED,BigDecimal.ZERO)));return;}if(reservation.status()!=RareInventoryDirectory.UseStatus.RESERVED){publish(()->result.accept(new Outcome(reservation.status()==RareInventoryDirectory.UseStatus.NOT_AVAILABLE?Status.NOT_AVAILABLE:Status.STALE,BigDecimal.ZERO)));return;}characters.saveHealth(captured.record().id(),captured.record().revision(),target,limit).whenComplete((saved,saveFailure)->publish(()->complete(player,captured,operation,accepted,saved,saveFailure,result)));});}
|
||||
private void complete(Player player,Context captured,UUID operation,double accepted,Optional<CharacterRecord> saved,Throwable failure,Consumer<Outcome> result){if(failure!=null||saved==null||saved.isEmpty()){if(failure!=null)report(failure);inventory.refundUse(operation).whenComplete((ignored,refundFailure)->{if(refundFailure!=null)report(refundFailure);publish(()->result.accept(new Outcome(Status.FAILED,BigDecimal.ZERO)));});return;}var persisted=saved.orElseThrow();var current=context(player);boolean acknowledged=false;try{acknowledged=current.isPresent()&¤t.orElseThrow().active().session().equals(captured.active().session())&&sessions.acknowledgeProgress(captured.active(),captured.record().revision(),persisted);}catch(RuntimeException uncertain){report(uncertain);}if(!acknowledged){inventory.commitUse(operation).whenComplete((ignored,commitFailure)->{if(commitFailure!=null)report(commitFailure);publish(()->result.accept(new Outcome(Status.STALE,BigDecimal.ZERO)));});return;}var attribute=player.getAttribute(Attribute.MAX_HEALTH);double now=player.getHealth(),maximum=attribute==null?Double.NaN:attribute.getValue(),desired=Math.min(maximum,persisted.health().doubleValue()),restored=Math.min(accepted,desired-now);if(!Double.isFinite(now)||!Double.isFinite(maximum)||!Double.isFinite(restored)||restored<=0){inventory.refundUse(operation).whenComplete((ignored,refundFailure)->{if(refundFailure!=null)report(refundFailure);publish(()->result.accept(new Outcome(Status.NO_EFFECT,BigDecimal.ZERO)));});return;}try{player.setHealth(Math.min(maximum,now+restored));}catch(RuntimeException uncertain){report(uncertain);inventory.commitUse(operation);result.accept(new Outcome(Status.FAILED,BigDecimal.ZERO));return;}inventory.commitUse(operation).whenComplete((status,commitFailure)->{if(commitFailure!=null){report(commitFailure);publish(()->result.accept(new Outcome(Status.FAILED,BigDecimal.ZERO)));return;}publish(()->result.accept(new Outcome(Status.APPLIED,BigDecimal.valueOf(restored).stripTrailingZeros())));});}
|
||||
private Optional<Context> context(Player player){var active=sessions.active(player.getUniqueId()).filter(sessions::current).orElse(null);var record=active==null?null:sessions.currentRecord(active).filter(value->!value.dead()).orElse(null);return record==null?Optional.empty():Optional.of(new Context(active,record));}
|
||||
private void publish(Runnable action){try{nextTick.accept(action);}catch(RuntimeException failure){report(failure);}}private void report(Throwable failure){try{failures.accept(failure);}catch(RuntimeException ignored){}}
|
||||
|
||||
@@ -7,15 +7,16 @@ import java.util.Optional;
|
||||
public enum RareProduct {
|
||||
LESSER_HEALTH_POTION("lesser-health-potion", "Lesser Health Potion", 50, 10, 25),
|
||||
HEALTH_POTION("health-potion", "Health Potion", 150, 5, 50),
|
||||
GREATER_HEALTH_POTION("greater-health-potion", "Greater Health Potion", 500, 2, 100);
|
||||
GREATER_HEALTH_POTION("greater-health-potion", "Greater Health Potion", 500, 2, 100),
|
||||
RESKILL("reskill", "Reskill", 2000, 1, null);
|
||||
|
||||
private final String id;
|
||||
private final String displayName;
|
||||
private final int basePrice;
|
||||
private final int maximumStock;
|
||||
private final int defaultHealingPercent;
|
||||
private final Integer defaultHealingPercent;
|
||||
|
||||
RareProduct(String id, String displayName, int basePrice, int maximumStock, int defaultHealingPercent) {
|
||||
RareProduct(String id, String displayName, int basePrice, int maximumStock, Integer defaultHealingPercent) {
|
||||
this.id=id;this.displayName=displayName;this.basePrice=basePrice;
|
||||
this.maximumStock=maximumStock;this.defaultHealingPercent=defaultHealingPercent;
|
||||
}
|
||||
@@ -23,6 +24,7 @@ public enum RareProduct {
|
||||
public String displayName(){return displayName;}
|
||||
public int basePrice(){return basePrice;}
|
||||
public int maximumStock(){return maximumStock;}
|
||||
public int defaultHealingPercent(){return defaultHealingPercent;}
|
||||
public boolean heals(){return defaultHealingPercent!=null;}
|
||||
public int defaultHealingPercent(){if(defaultHealingPercent==null)throw new IllegalStateException("Product does not heal");return defaultHealingPercent;}
|
||||
public static Optional<RareProduct> find(String id){return Arrays.stream(values()).filter(value->value.id.equals(id)).findFirst();}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
package games.dmg.fantasystick.shop;
|
||||
|
||||
import games.dmg.fantasystick.persistence.CharacterRecord;
|
||||
import games.dmg.fantasystick.persistence.CharacterStorage;
|
||||
import games.dmg.fantasystick.session.EquipmentSessions;
|
||||
import games.dmg.fantasystick.session.NativeHealthLimit;
|
||||
import java.math.BigInteger;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Consumer;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
/** Confirmed, recoverable one-item reset for the exact living active character. */
|
||||
public final class RareReskillService {
|
||||
public enum Status { APPLIED, NOTHING_TO_RESET, NOT_AVAILABLE, STALE, FAILED }
|
||||
public record Preview(UUID operation, EquipmentSessions.Active active, CharacterRecord record,
|
||||
BigInteger quantity, BigInteger refund) { }
|
||||
public record Outcome(Status status, Optional<CharacterRecord> record) { }
|
||||
private record Context(EquipmentSessions.Active active, CharacterRecord record) { }
|
||||
|
||||
private final RareInventoryDirectory inventory;
|
||||
private final CharacterStorage characters;
|
||||
private final EquipmentSessions sessions;
|
||||
private final Consumer<Runnable> nextTick;
|
||||
private final Consumer<CharacterRecord> cleanup;
|
||||
private final Consumer<Throwable> failures;
|
||||
|
||||
public RareReskillService(RareInventoryDirectory inventory, CharacterStorage characters,
|
||||
EquipmentSessions sessions, Consumer<Runnable> nextTick,
|
||||
Consumer<CharacterRecord> cleanup, Consumer<Throwable> failures) {
|
||||
this.inventory = Objects.requireNonNull(inventory);
|
||||
this.characters = Objects.requireNonNull(characters);
|
||||
this.sessions = Objects.requireNonNull(sessions);
|
||||
this.nextTick = Objects.requireNonNull(nextTick);
|
||||
this.cleanup = Objects.requireNonNull(cleanup);
|
||||
this.failures = Objects.requireNonNull(failures);
|
||||
}
|
||||
|
||||
public Optional<Preview> preview(Player player) {
|
||||
var context = context(player).orElse(null);
|
||||
if (context == null) return Optional.empty();
|
||||
var quantity = inventory.quantity(context.record().id(), RareProduct.RESKILL);
|
||||
if (quantity.signum() <= 0) return Optional.empty();
|
||||
return Optional.of(new Preview(UUID.randomUUID(), context.active(), context.record(), quantity,
|
||||
refund(context.record())));
|
||||
}
|
||||
|
||||
public void confirm(Player player, Preview preview, Consumer<Outcome> result) {
|
||||
Objects.requireNonNull(player); Objects.requireNonNull(preview); Objects.requireNonNull(result);
|
||||
var current = context(player).orElse(null);
|
||||
if (current == null || !current.active().session().equals(preview.active().session())
|
||||
|| !current.record().revision().equals(preview.record().revision())
|
||||
|| !inventory.quantity(current.record().id(), RareProduct.RESKILL).equals(preview.quantity())) {
|
||||
result.accept(new Outcome(Status.STALE, Optional.ofNullable(current).map(Context::record)));
|
||||
return;
|
||||
}
|
||||
if (preview.refund().signum() == 0) {
|
||||
result.accept(new Outcome(Status.NOTHING_TO_RESET, Optional.of(current.record())));
|
||||
return;
|
||||
}
|
||||
var nativeLimit = NativeHealthLimit.read();
|
||||
inventory.reserveUse(current.record().id(), RareProduct.RESKILL, preview.operation(), preview.quantity())
|
||||
.whenComplete((reservation, reserveFailure) -> {
|
||||
if (reserveFailure != null) { fail(reserveFailure, result); return; }
|
||||
if (reservation.status() != RareInventoryDirectory.UseStatus.RESERVED) {
|
||||
publish(() -> result.accept(new Outcome(
|
||||
reservation.status() == RareInventoryDirectory.UseStatus.NOT_AVAILABLE
|
||||
? Status.NOT_AVAILABLE : Status.STALE, Optional.empty())));
|
||||
return;
|
||||
}
|
||||
characters.reskill(current.record().id(), current.record().revision(), preview.operation(), nativeLimit)
|
||||
.whenComplete((reset, resetFailure) -> complete(player, preview, reset, resetFailure, result));
|
||||
});
|
||||
}
|
||||
|
||||
/** Resolve interrupted resets from authoritative character proof; never replay native cleanup. */
|
||||
public void install() {
|
||||
for (var use : inventory.unresolvedUses()) {
|
||||
if (!use.product().equals(RareProduct.RESKILL.id())) continue;
|
||||
characters.find(use.character()).whenComplete((record, failure) -> {
|
||||
if (failure != null) { report(failure); return; }
|
||||
boolean applied = record.isPresent() && record.orElseThrow().rewardReceipts().contains(use.operation());
|
||||
var work = applied ? inventory.commitUse(use.operation()) : inventory.refundUse(use.operation());
|
||||
work.exceptionally(problem -> { report(problem); return RareInventoryDirectory.UseStatus.RESERVED; });
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private void complete(Player player, Preview preview, CharacterStorage.Reskill reset, Throwable failure,
|
||||
Consumer<Outcome> result) {
|
||||
if (failure != null || reset == null) {
|
||||
if (failure != null) report(failure);
|
||||
refund(preview.operation(), () -> result.accept(new Outcome(Status.FAILED, Optional.empty())));
|
||||
return;
|
||||
}
|
||||
if (reset.status() != CharacterStorage.ReskillStatus.APPLIED
|
||||
&& reset.status() != CharacterStorage.ReskillStatus.DUPLICATE) {
|
||||
var status = switch (reset.status()) {
|
||||
case NOTHING_TO_RESET -> Status.NOTHING_TO_RESET;
|
||||
case STALE -> Status.STALE;
|
||||
case UNAVAILABLE -> Status.NOT_AVAILABLE;
|
||||
case APPLIED, DUPLICATE -> throw new IllegalStateException();
|
||||
};
|
||||
refund(preview.operation(), () -> result.accept(new Outcome(status, reset.record())));
|
||||
return;
|
||||
}
|
||||
publish(() -> {
|
||||
boolean acknowledged = false;
|
||||
try {
|
||||
var current = context(player);
|
||||
acknowledged = current.isPresent()
|
||||
&& current.orElseThrow().active().session().equals(preview.active().session())
|
||||
&& (reset.status() == CharacterStorage.ReskillStatus.DUPLICATE
|
||||
|| sessions.acknowledgeProgress(preview.active(), preview.record().revision(), reset.record().orElseThrow()));
|
||||
} catch (RuntimeException uncertain) { report(uncertain); }
|
||||
if (acknowledged) try { cleanup.accept(preview.record()); } catch (RuntimeException uncertain) { report(uncertain); acknowledged=false; }
|
||||
boolean currentSession = acknowledged;
|
||||
inventory.commitUse(preview.operation()).whenComplete((ignored, commitFailure) -> {
|
||||
if (commitFailure != null) { report(commitFailure); publish(() -> result.accept(new Outcome(Status.FAILED, reset.record()))); }
|
||||
else publish(() -> result.accept(new Outcome(currentSession ? Status.APPLIED : Status.STALE, reset.record())));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
private void refund(UUID operation, Runnable after) {
|
||||
inventory.refundUse(operation).whenComplete((ignored, failure) -> {
|
||||
if (failure != null) report(failure);
|
||||
publish(after);
|
||||
});
|
||||
}
|
||||
|
||||
private Optional<Context> context(Player player) {
|
||||
var active = sessions.active(player.getUniqueId()).filter(sessions::current).orElse(null);
|
||||
var record = active == null ? null : sessions.currentRecord(active).filter(value -> !value.dead()).orElse(null);
|
||||
return record == null ? Optional.empty() : Optional.of(new Context(active, record));
|
||||
}
|
||||
|
||||
private static BigInteger refund(CharacterRecord record) {
|
||||
return record.stats().values().stream().reduce(BigInteger.ZERO, BigInteger::add)
|
||||
.add(BigInteger.valueOf(record.learned().size()))
|
||||
.add(BigInteger.valueOf(record.passives().stream().filter(id -> !id.isEmpty()).distinct().count()));
|
||||
}
|
||||
|
||||
private void fail(Throwable failure, Consumer<Outcome> result) {
|
||||
report(failure); publish(() -> result.accept(new Outcome(Status.FAILED, Optional.empty())));
|
||||
}
|
||||
private void publish(Runnable action) { try { nextTick.accept(action); } catch (RuntimeException failure) { report(failure); } }
|
||||
private void report(Throwable failure) { try { failures.accept(failure); } catch (RuntimeException ignored) { } }
|
||||
}
|
||||
@@ -26,8 +26,8 @@ public final class RareShopMenus implements Listener,AutoCloseable {
|
||||
private record Holder(UUID shop,UUID character,UUID session,UUID catalog)implements InventoryHolder{public Inventory getInventory(){return null;}}
|
||||
private final RareShop service;private final org.bukkit.Server server;private final NamespacedKey productKey;private boolean closed;
|
||||
public RareShopMenus(Plugin plugin,RareShop service){this.service=Objects.requireNonNull(service);server=plugin.getServer();productKey=new NamespacedKey(plugin,"rare_shop_product");}
|
||||
public void open(Player player,UUID shop){service.view(player,shop,view->{if(closed||!player.isOnline())return;if(view.isEmpty()){player.sendMessage("Rare Items shop requires a living active character beside the registered merchant.");return;}var current=view.orElseThrow();var inventory=server.createInventory(new Holder(shop,current.record().id(),current.session(),current.catalog().revision()),27,net.kyori.adventure.text.Component.text("Rare Items"));int slot=10;boolean available=false;for(var product:RareProduct.values()){var offer=current.catalog().offer(product);inventory.setItem(slot++,item(product,offer));if(offer.remaining()>0)available=true;}inventory.setItem(22,schedule(current.catalog(),service.now()));if(!available)inventory.setItem(13,empty());player.openInventory(inventory);});}
|
||||
private ItemStack item(RareProduct product,RareCatalog.Offer offer){var item=new ItemStack(Material.POTION);var meta=item.getItemMeta();meta.displayName(net.kyori.adventure.text.Component.text((offer.remaining()==0?"Sold out — ":"Buy ")+product.displayName()+" — "+offer.price()+" coins"));meta.lore(List.of(net.kyori.adventure.text.Component.text("Stock: "+offer.remaining())));meta.getPersistentDataContainer().set(productKey,PersistentDataType.STRING,product.id());item.setItemMeta(meta);return item;}
|
||||
public void open(Player player,UUID shop){service.view(player,shop,view->{if(closed||!player.isOnline())return;if(view.isEmpty()){player.sendMessage("Rare Items shop requires a living active character beside the registered merchant.");return;}var current=view.orElseThrow();var inventory=server.createInventory(new Holder(shop,current.record().id(),current.session(),current.catalog().revision()),27,net.kyori.adventure.text.Component.text("Rare Items"));int slot=10;boolean available=false;for(var product:RareProduct.values()){var offer=current.catalog().available(product)?current.catalog().offer(product):null;inventory.setItem(slot++,item(product,offer));if(offer!=null&&offer.remaining()>0)available=true;}inventory.setItem(22,schedule(current.catalog(),service.now()));if(!available)inventory.setItem(16,empty());player.openInventory(inventory);});}
|
||||
private ItemStack item(RareProduct product,RareCatalog.Offer offer){var item=new ItemStack(Material.POTION);var meta=item.getItemMeta();if(offer==null){meta.displayName(net.kyori.adventure.text.Component.text("Unavailable — "+product.displayName()));meta.lore(List.of(net.kyori.adventure.text.Component.text("Available after the next rare restock")));}else{meta.displayName(net.kyori.adventure.text.Component.text((offer.remaining()==0?"Sold out — ":"Buy ")+product.displayName()+" — "+offer.price()+" coins"));meta.lore(List.of(net.kyori.adventure.text.Component.text("Stock: "+offer.remaining())));meta.getPersistentDataContainer().set(productKey,PersistentDataType.STRING,product.id());}item.setItemMeta(meta);return item;}
|
||||
private static ItemStack empty(){var item=new ItemStack(Material.BARRIER);var meta=item.getItemMeta();meta.displayName(net.kyori.adventure.text.Component.text("All Rare Items are sold out"));item.setItemMeta(meta);return item;}
|
||||
private static ItemStack schedule(RareCatalog catalog,Instant now){var next=catalog.day().plusDays(1).atStartOfDay(ZoneOffset.UTC).toInstant();long seconds=Math.max(0,Duration.between(now,next).toSeconds()),hours=seconds/3600,minutes=(seconds%3600)/60;var item=new ItemStack(Material.CLOCK);var meta=item.getItemMeta();meta.displayName(net.kyori.adventure.text.Component.text("Restock in: "+hours+"h "+minutes+"m"));item.setItemMeta(meta);return item;}
|
||||
public void refreshOpen(){if(closed)return;for(var player:server.getOnlinePlayers()){var view=player.getOpenInventory();if(view==null)continue;var inventory=view.getTopInventory();if(inventory!=null&&inventory.getHolder() instanceof Holder holder)open(player,holder.shop());}}
|
||||
|
||||
@@ -41,6 +41,9 @@ rare-price-greater-health-potion: 500
|
||||
rare-stock-greater-health-potion-min: 0
|
||||
rare-stock-greater-health-potion-max: 2
|
||||
rare-greater-health-potion-healing-percent: 100
|
||||
rare-price-reskill: 2000
|
||||
rare-stock-reskill-min: 0
|
||||
rare-stock-reskill-max: 1
|
||||
sheet-resource-pack-url: ''
|
||||
sheet-resource-pack-sha1: ''
|
||||
|
||||
|
||||
@@ -42,6 +42,10 @@ class AbilityRegistryNativeTest {
|
||||
() -> assertThrows(NullPointerException.class, () -> new AbilityDefinition("category", "Category", Material.STONE,
|
||||
List.of("Lore"), "Use", Map.of(), BigInteger.ONE, null, AbilityDefinition.Activation.IMMEDIATE,
|
||||
ControlInput.Gesture.USE, Duration.ZERO, Map.of(), AbilityDefinition.TargetPolicy.SELF, ignored -> {})),
|
||||
() -> assertThrows(IllegalArgumentException.class, () -> new AbilityDefinition("ambiguous_cost", "Ambiguous", Material.STONE,
|
||||
List.of("Lore"), "Use", Map.of(), BigInteger.TWO, AbilityDefinition.Category.ATK,
|
||||
AbilityDefinition.Activation.IMMEDIATE, ControlInput.Gesture.USE, Duration.ZERO,
|
||||
Map.of(), AbilityDefinition.TargetPolicy.SELF, ignored -> {})),
|
||||
() -> assertThrows(IllegalArgumentException.class, () -> copy(valid, "low", Map.of(Stat.INT, BigInteger.valueOf(9)), Map.of(), Duration.ZERO)),
|
||||
() -> assertThrows(IllegalArgumentException.class, () -> copy(valid, "negative", valid.requirements(), Map.of("range", BigDecimal.valueOf(-1)), Duration.ZERO)),
|
||||
() -> assertThrows(IllegalArgumentException.class, () -> copy(valid, "infinite", valid.requirements(), Map.of("range", new BigDecimal("1E1000000")), Duration.ZERO)),
|
||||
|
||||
@@ -28,20 +28,46 @@ class RareShopNativeTest {
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Test void registeredMerchantPurchaseInventoryUseAndNativeHealingUseConnectedPath()throws Exception{
|
||||
java.nio.file.Files.writeString(data.resolve("config.yml"),"rare-price-variance-percent: 0\nrare-price-health-potion: 40\nrare-stock-health-potion-min: 1\nrare-stock-health-potion-max: 1\n");
|
||||
java.nio.file.Files.writeString(data.resolve("config.yml"),"rare-price-variance-percent: 0\nrare-price-health-potion: 40\nrare-stock-health-potion-min: 1\nrare-stock-health-potion-max: 1\nrare-price-reskill: 20\nrare-stock-reskill-min: 1\nrare-stock-reskill-max: 1\n");
|
||||
try(var f=new FantasyStickLifecycleNativeTest.Fixture(data)){
|
||||
f.plugin.setEnabled(true);var actor=new FantasyStickLifecycleNativeTest.Actor(data);f.players.put(actor.core.id,actor.player);doReturn(true).when(actor.player).hasPermission("fantasystick.admin");UUID worldId=UUID.randomUUID();when(actor.world.getUID()).thenReturn(worldId);int x=actor.core.location.getBlockX()>>4,z=actor.core.location.getBlockZ()>>4;var chunk=mock(Chunk.class);when(chunk.getWorld()).thenReturn(actor.world);when(chunk.getX()).thenReturn(x);when(chunk.getZ()).thenReturn(z);when(chunk.getEntities()).thenReturn(new org.bukkit.entity.Entity[0]);when(actor.world.getChunkAt(x,z)).thenReturn(chunk);when(actor.world.isChunkLoaded(x,z)).thenReturn(true);when(actor.world.getEntities()).thenReturn(List.of());
|
||||
assertEquals(List.of("list","place","remove","restock"),f.command.tabComplete(actor.player,"fantasystick",new String[]{"rare-shop",""}));assertTrue(f.command.tabComplete(actor.player,"fantasystick",new String[]{"config","rare-"}).contains("rare-price-health-potion"));
|
||||
assertEquals(List.of("list","place","remove","restock"),f.command.tabComplete(actor.player,"fantasystick",new String[]{"rare-shop",""}));assertTrue(f.command.tabComplete(actor.player,"fantasystick",new String[]{"config","rare-"}).containsAll(List.of("rare-price-health-potion","rare-price-reskill","rare-stock-reskill-min","rare-stock-reskill-max")));assertEquals(List.of("20","2000"),f.command.tabComplete(actor.player,"fantasystick",new String[]{"config","rare-price-reskill",""}));
|
||||
var villager=mock(Villager.class);when(villager.getLocation()).thenReturn(actor.core.location);var values=new HashMap<String,String>();var pdc=mock(PersistentDataContainer.class);when(villager.getPersistentDataContainer()).thenReturn(pdc);doAnswer(call->{values.put(((NamespacedKey)call.getArgument(0)).getKey(),call.getArgument(2));return null;}).when(pdc).set(any(NamespacedKey.class),eq(PersistentDataType.STRING),anyString());when(pdc.get(any(NamespacedKey.class),eq(PersistentDataType.STRING))).thenAnswer(call->values.get(((NamespacedKey)call.getArgument(0)).getKey()));doAnswer(call->{((java.util.function.Consumer<Villager>)call.getArgument(2)).accept(villager);return villager;}).when(actor.world).spawn(any(Location.class),eq(Villager.class),any(java.util.function.Consumer.class));
|
||||
f.command.execute(actor.player,"fantasystick",new String[]{"rare-shop","place","Curios"});await(f,()->((RareMerchantDirectory)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"rareMerchants")).all().size()==1);var directory=(RareMerchantDirectory)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"rareMerchants");var shop=directory.all().getFirst();assertEquals("Curios",shop.name());var controller=(RareMerchantController)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"rareMerchantController");assertTrue(controller.tagged(villager));
|
||||
var repository=new YamlCharacterRepository(data);var old=repository.load(actor.core.record.id()).orElseThrow();repository.replace(new CharacterRecord(old.id(),old.name(),old.revision().add(BigInteger.ONE),old.stats(),old.level(),old.experience(),old.unspentPoints(),old.health(),old.learned(),old.loadout(),old.passives(),old.cooldowns(),old.restrictedKills(),false,null,null,BigInteger.valueOf(100),true,old.rewardReceipts(),old.pvpCoinEscrow(),old.gear()),old.revision());f.activate(actor);
|
||||
var repository=new YamlCharacterRepository(data);var old=repository.load(actor.core.record.id()).orElseThrow();var purchasedStats=new java.util.EnumMap<>(old.stats());purchasedStats.put(games.dmg.fantasystick.progression.Stat.DEX,BigInteger.ONE);repository.replace(new CharacterRecord(old.id(),old.name(),old.revision().add(BigInteger.ONE),purchasedStats,old.level(),old.experience(),BigInteger.valueOf(39),old.health(),old.learned(),old.loadout(),old.passives(),old.cooldowns(),old.restrictedKills(),false,null,null,BigInteger.valueOf(100),true,old.rewardReceipts(),old.pvpCoinEscrow(),old.gear()),old.revision());f.activate(actor);
|
||||
int opened=actor.inventories.size(),books=actor.books.size();var main=new PlayerInteractEntityEvent(actor.player,villager,EquipmentSlot.HAND);var offhand=new PlayerInteractEntityEvent(actor.player,villager,EquipmentSlot.OFF_HAND);f.dispatcher.accept(main);f.dispatcher.accept(offhand);assertTrue(main.isCancelled());assertTrue(offhand.isCancelled());await(f,()->actor.inventories.size()==opened+1);assertEquals(books,actor.books.size());var menu=actor.inventories.getLast();var potion=menu.getItem(11);assertEquals(Material.POTION,potion.getType());assertTrue(net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer.plainText().serialize(potion.getItemMeta().displayName()).contains("Health Potion — 40 coins"));assertEquals("Stock: 1",net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer.plainText().serialize(potion.getItemMeta().lore().getFirst()));
|
||||
var menus=(RareShopMenus)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"rareShopMenus");var click=mock(InventoryClickEvent.class);when(click.getInventory()).thenReturn(menu);when(click.getWhoClicked()).thenReturn(actor.player);when(click.getCurrentItem()).thenReturn(potion);menus.click(click);var inventory=(RareInventoryDirectory)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"rareInventory");await(f,()->inventory.quantity(actor.core.record.id(),RareProduct.HEALTH_POTION).equals(BigInteger.ONE));var characters=(CharacterStorage)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"characters");var sessions=(games.dmg.fantasystick.session.EquipmentSessions)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"sessions");await(f,()->sessions.active(actor.core.id).flatMap(sessions::currentRecord).map(value->value.coins().equals(BigInteger.valueOf(60))).orElse(false));var active=sessions.active(actor.core.id).orElseThrow(()->new AssertionError("Purchase removed active session: "+actor.messages));var record=sessions.currentRecord(active).orElseThrow(()->new AssertionError("Purchase left no current record: "+actor.messages));var injured=characters.saveHealth(record.id(),record.revision(),BigDecimal.valueOf(5),BigDecimal.valueOf(100)).join().orElseThrow(()->new AssertionError("Injury save was refused"));assertTrue(sessions.acknowledgeProgress(active,record.revision(),injured));actor.player.setHealth(5);
|
||||
PartyBookNativeTest.open(f,actor);assertTrue(PartyBookNativeTest.text(actor).contains("Health Potion"),PartyBookNativeTest.text(actor));assertTrue(PartyBookNativeTest.text(actor).contains("[Use]"),PartyBookNativeTest.text(actor));var action=PartyBookNativeTest.button(actor,"[Use]");PartyBookNativeTest.click(f,actor,action);await(f,()->inventory.quantity(actor.core.record.id(),RareProduct.HEALTH_POTION).signum()==0&&actor.player.getHealth()>5&&actor.messages.stream().anyMatch(message->message.contains("Used Health Potion")));assertEquals(10d,actor.player.getHealth());assertEquals(0,BigDecimal.TEN.compareTo(characters.find(record.id()).join().orElseThrow().health()));assertTrue(actor.messages.stream().anyMatch(message->message.contains("Used Health Potion")&&message.contains("restored")));
|
||||
f.plugin.setEnabled(false);f.awaitWorkers();f.plugin.setEnabled(true);var reloaded=(RareInventoryDirectory)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"rareInventory");assertEquals(BigInteger.ZERO,reloaded.quantity(actor.core.record.id(),RareProduct.HEALTH_POTION));assertTrue(((RareMerchantDirectory)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"rareMerchants")).find(shop.id()).isPresent());
|
||||
int menusBeforeReskill=actor.inventories.size();menus.open(actor.player,shop.id());await(f,()->actor.inventories.size()>menusBeforeReskill);var reskillMenu=actor.inventories.getLast();var reskill=reskillMenu.getItem(13);assertTrue(net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer.plainText().serialize(reskill.getItemMeta().displayName()).contains("Reskill — 20 coins"));var reskillClick=mock(InventoryClickEvent.class);when(reskillClick.getInventory()).thenReturn(reskillMenu);when(reskillClick.getWhoClicked()).thenReturn(actor.player);when(reskillClick.getCurrentItem()).thenReturn(reskill);menus.click(reskillClick);await(f,()->inventory.quantity(actor.core.record.id(),RareProduct.RESKILL).equals(BigInteger.ONE));await(f,()->sessions.active(actor.core.id).flatMap(sessions::currentRecord).map(value->value.coins().equals(BigInteger.valueOf(40))&&!value.stats().get(games.dmg.fantasystick.progression.Stat.DEX).equals(BigInteger.ZERO)).orElse(false));PartyBookNativeTest.open(f,actor);PartyBookNativeTest.click(f,actor,PartyBookNativeTest.button(actor,"[Use]"));await(f,()->PartyBookNativeTest.text(actor).contains("Confirm Reskill"));PartyBookNativeTest.click(f,actor,PartyBookNativeTest.button(actor,"[Confirm Reskill]"));await(f,()->inventory.quantity(actor.core.record.id(),RareProduct.RESKILL).signum()==0&&sessions.active(actor.core.id).flatMap(sessions::currentRecord).map(value->value.stats().values().stream().allMatch(BigInteger.ZERO::equals)&&value.unspentPoints().equals(BigInteger.valueOf(40))).orElse(false));var resetActive=sessions.active(actor.core.id).orElseThrow();var resetRecord=sessions.currentRecord(resetActive).orElseThrow();var repurchased=characters.purchaseStat(resetRecord.id(),resetRecord.revision(),games.dmg.fantasystick.progression.Stat.DEX,BigDecimal.valueOf(actor.player.getHealth()),new BigDecimal("1024")).join().record().orElseThrow();assertTrue(sessions.acknowledgeProgress(resetActive,resetRecord.revision(),repurchased));assertEquals(BigInteger.ONE,repurchased.stats().get(games.dmg.fantasystick.progression.Stat.DEX));assertEquals(BigInteger.valueOf(39),repurchased.unspentPoints());
|
||||
f.plugin.setEnabled(false);f.awaitWorkers();f.plugin.setEnabled(true);var reloaded=(RareInventoryDirectory)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"rareInventory");assertEquals(BigInteger.ZERO,reloaded.quantity(actor.core.record.id(),RareProduct.HEALTH_POTION));assertEquals(BigInteger.ZERO,reloaded.quantity(actor.core.record.id(),RareProduct.RESKILL));assertEquals(BigInteger.ONE,new YamlCharacterRepository(data).load(actor.core.record.id()).orElseThrow().stats().get(games.dmg.fantasystick.progression.Stat.DEX));assertTrue(((RareMerchantDirectory)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"rareMerchants")).find(shop.id()).isPresent());
|
||||
}
|
||||
}
|
||||
@Test void everyMerchantSharesOneAllZeroCatalogAndShowsAnEmptyShop()throws Exception{java.nio.file.Files.writeString(data.resolve("config.yml"),"rare-stock-lesser-health-potion-min: 0\nrare-stock-lesser-health-potion-max: 0\nrare-stock-health-potion-min: 0\nrare-stock-health-potion-max: 0\nrare-stock-greater-health-potion-min: 0\nrare-stock-greater-health-potion-max: 0\n");try(var f=new FantasyStickLifecycleNativeTest.Fixture(data)){f.plugin.setEnabled(true);var actor=new FantasyStickLifecycleNativeTest.Actor(data);f.players.put(actor.core.id,actor.player);UUID world=UUID.randomUUID();when(actor.world.getUID()).thenReturn(world);f.activate(actor);var directory=(RareMerchantDirectory)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"rareMerchants");var first=directory.place("One",world,actor.core.location.getX(),actor.core.location.getY(),actor.core.location.getZ(),0,0).join();var second=directory.place("Two",world,actor.core.location.getX(),actor.core.location.getY(),actor.core.location.getZ(),0,0).join();var menus=(RareShopMenus)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"rareShopMenus");menus.open(actor.player,first.id());await(f,()->!actor.inventories.isEmpty());var one=actor.inventories.getLast();assertEquals(Material.BARRIER,one.getItem(13).getType());menus.open(actor.player,second.id());await(f,()->actor.inventories.size()>=2);var two=actor.inventories.getLast();assertEquals(one.getItem(10).getItemMeta().displayName(),two.getItem(10).getItemMeta().displayName());assertTrue(net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer.plainText().serialize(one.getItem(10).getItemMeta().displayName()).startsWith("Sold out"));}}
|
||||
@Test void reskillUseRequiresFreshConfirmationThenResetsTheExactActiveCharacter()throws Exception{
|
||||
try(var f=new FantasyStickLifecycleNativeTest.Fixture(data)){
|
||||
f.plugin.setEnabled(true);var actor=new FantasyStickLifecycleNativeTest.Actor(data);f.players.put(actor.core.id,actor.player);
|
||||
var repository=new YamlCharacterRepository(data);var old=repository.load(actor.core.record.id()).orElseThrow();var stats=new java.util.EnumMap<>(old.stats());stats.put(games.dmg.fantasystick.progression.Stat.STR,BigInteger.ONE);stats.put(games.dmg.fantasystick.progression.Stat.CON,BigInteger.valueOf(5));var deadline=java.time.Instant.parse("2026-09-25T00:00:00Z");var invested=new CharacterRecord(old.id(),old.name(),old.revision().add(BigInteger.ONE),stats,old.level(),old.experience(),BigInteger.valueOf(100),new BigDecimal("15"),Set.of("unknown_saved"),List.of("unknown_saved","","","","","",""),List.of("unknown_passive","",""),Map.of("revive",deadline),old.restrictedKills(),false,null,null,old.coins(),old.coinsInitialized(),old.rewardReceipts(),old.pvpCoinEscrow(),old.gear(),old.sheetGeneration());repository.replace(invested,old.revision());
|
||||
f.activate(actor);var inventory=(RareInventoryDirectory)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"rareInventory");inventory.add(invested.id(),RareProduct.RESKILL,UUID.randomUUID()).join();
|
||||
PartyBookNativeTest.open(f,actor);String inventoryText=PartyBookNativeTest.text(actor);assertTrue(inventoryText.contains("Reskill: 1"),inventoryText);PartyBookNativeTest.click(f,actor,PartyBookNativeTest.button(actor,"[Use]"));
|
||||
await(f,()->PartyBookNativeTest.text(actor).contains("Confirm Reskill"));String preview=PartyBookNativeTest.text(actor);assertTrue(preview.contains("Refund: 8 points"),preview);assertTrue(preview.contains("Cooldowns retained"),preview);assertEquals(BigInteger.ONE,inventory.quantity(invested.id(),RareProduct.RESKILL));
|
||||
PartyBookNativeTest.click(f,actor,PartyBookNativeTest.button(actor,"[Confirm Reskill]"));var sessions=(games.dmg.fantasystick.session.EquipmentSessions)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"sessions");await(f,()->sessions.active(actor.core.id).flatMap(sessions::currentRecord).map(record->record.stats().values().stream().allMatch(BigInteger.ZERO::equals)&&record.unspentPoints().equals(BigInteger.valueOf(108))).orElse(false));var reset=sessions.currentRecord(sessions.active(actor.core.id).orElseThrow()).orElseThrow();assertTrue(reset.learned().isEmpty());assertEquals(List.of("","",""),reset.passives());assertEquals(deadline,reset.cooldowns().get("revive"));assertEquals(10d,actor.maximumHealth.getValue());assertEquals(10d,actor.player.getHealth());assertEquals(BigInteger.ZERO,inventory.quantity(invested.id(),RareProduct.RESKILL));
|
||||
}
|
||||
}
|
||||
|
||||
@Test void reskillWithNothingInvestedRefusesWithoutConsumingTheStoredItem()throws Exception{
|
||||
try(var f=new FantasyStickLifecycleNativeTest.Fixture(data)){f.plugin.setEnabled(true);var actor=new FantasyStickLifecycleNativeTest.Actor(data);f.players.put(actor.core.id,actor.player);f.activate(actor);var inventory=(RareInventoryDirectory)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"rareInventory");inventory.add(actor.core.record.id(),RareProduct.RESKILL,UUID.randomUUID()).join();PartyBookNativeTest.open(f,actor);PartyBookNativeTest.click(f,actor,PartyBookNativeTest.button(actor,"[Use]"));await(f,()->actor.messages.stream().anyMatch(message->message.contains("no investments")));assertEquals(BigInteger.ONE,inventory.quantity(actor.core.record.id(),RareProduct.RESKILL));assertFalse(PartyBookNativeTest.text(actor).contains("Confirm Reskill"));}
|
||||
}
|
||||
|
||||
@Test void staleReskillConfirmationCannotConsumeOrOverwriteNewerProgress()throws Exception{
|
||||
try(var f=new FantasyStickLifecycleNativeTest.Fixture(data)){f.plugin.setEnabled(true);var actor=new FantasyStickLifecycleNativeTest.Actor(data);f.players.put(actor.core.id,actor.player);var repository=new YamlCharacterRepository(data);var old=repository.load(actor.core.record.id()).orElseThrow();var stats=new java.util.EnumMap<>(old.stats());stats.put(games.dmg.fantasystick.progression.Stat.STR,BigInteger.ONE);var invested=new CharacterRecord(old.id(),old.name(),old.revision().add(BigInteger.ONE),stats,old.level(),old.experience(),BigInteger.valueOf(39),old.health(),old.learned(),old.loadout(),old.passives(),old.cooldowns(),old.restrictedKills(),false,null,null,old.coins(),old.coinsInitialized(),old.rewardReceipts(),old.pvpCoinEscrow(),old.gear(),old.sheetGeneration());repository.replace(invested,old.revision());f.activate(actor);var inventory=(RareInventoryDirectory)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"rareInventory");inventory.add(invested.id(),RareProduct.RESKILL,UUID.randomUUID()).join();PartyBookNativeTest.open(f,actor);PartyBookNativeTest.click(f,actor,PartyBookNativeTest.button(actor,"[Use]"));await(f,()->PartyBookNativeTest.text(actor).contains("Confirm Reskill"));var confirm=PartyBookNativeTest.button(actor,"[Confirm Reskill]");var characters=(CharacterStorage)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"characters");var sessions=(games.dmg.fantasystick.session.EquipmentSessions)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"sessions");var active=sessions.active(actor.core.id).orElseThrow();var current=sessions.currentRecord(active).orElseThrow();var progressed=characters.awardCombatReward(current.id(),current.revision(),UUID.randomUUID(),BigInteger.ONE,BigInteger.ZERO,games.dmg.fantasystick.progression.ProgressionRules.defaults(),games.dmg.fantasystick.progression.CombatRewardRules.defaults(),null).join().record().orElseThrow();assertTrue(sessions.acknowledgeProgress(active,current.revision(),progressed));PartyBookNativeTest.click(f,actor,confirm);await(f,()->actor.messages.stream().anyMatch(message->message.contains("build or quantity changed")));assertEquals(BigInteger.ONE,inventory.quantity(invested.id(),RareProduct.RESKILL));var retained=sessions.currentRecord(active).orElseThrow();assertEquals(BigInteger.ONE,retained.stats().get(games.dmg.fantasystick.progression.Stat.STR));assertEquals(BigInteger.ONE,retained.experience());}
|
||||
}
|
||||
|
||||
@Test void restartConsumesOnlyReskillsWithAuthoritativeResetProofAndRefundsUnappliedReservations()throws Exception{
|
||||
var factory=new games.dmg.fantasystick.crafting.CharacterFactory();var base=factory.create(games.dmg.fantasystick.progression.ProgressionRules.defaults());var other=factory.create(games.dmg.fantasystick.progression.ProgressionRules.defaults());var stats=new java.util.EnumMap<>(base.stats());stats.put(games.dmg.fantasystick.progression.Stat.STR,BigInteger.ONE);var invested=new CharacterRecord(base.id(),base.name(),base.revision(),stats,base.level(),base.experience(),BigInteger.valueOf(39),base.health(),base.learned(),base.loadout(),base.passives(),base.cooldowns(),base.restrictedKills(),false,null,null,base.coins(),base.coinsInitialized(),base.rewardReceipts(),base.pvpCoinEscrow(),base.gear(),base.sheetGeneration());var repository=new YamlCharacterRepository(data);repository.create(invested);repository.create(other);UUID applied=UUID.randomUUID(),unapplied=UUID.randomUUID();
|
||||
try(var inventory=new RareInventoryDirectory(new YamlRareInventoryRepository(data));var characters=new CharacterStorage(repository,java.time.Clock.systemUTC())){inventory.add(invested.id(),RareProduct.RESKILL,UUID.randomUUID()).join();inventory.add(other.id(),RareProduct.RESKILL,UUID.randomUUID()).join();inventory.reserveUse(invested.id(),RareProduct.RESKILL,applied,BigInteger.ONE).join();inventory.reserveUse(other.id(),RareProduct.RESKILL,unapplied,BigInteger.ONE).join();assertEquals(CharacterStorage.ReskillStatus.APPLIED,characters.reskill(invested.id(),invested.revision(),applied,new BigDecimal("1024")).join().status());}
|
||||
try(var f=new FantasyStickLifecycleNativeTest.Fixture(data)){f.plugin.setEnabled(true);var inventory=(RareInventoryDirectory)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"rareInventory");await(f,()->inventory.unresolvedUses().isEmpty());assertEquals(BigInteger.ZERO,inventory.quantity(invested.id(),RareProduct.RESKILL));assertEquals(BigInteger.ONE,inventory.quantity(other.id(),RareProduct.RESKILL));var saved=new YamlCharacterRepository(data).load(invested.id()).orElseThrow();assertEquals(BigInteger.valueOf(40),saved.unspentPoints());assertTrue(saved.stats().values().stream().allMatch(BigInteger.ZERO::equals));}
|
||||
}
|
||||
|
||||
@Test void everyMerchantSharesOneAllZeroCatalogAndShowsAnEmptyShop()throws Exception{java.nio.file.Files.writeString(data.resolve("config.yml"),"rare-stock-lesser-health-potion-min: 0\nrare-stock-lesser-health-potion-max: 0\nrare-stock-health-potion-min: 0\nrare-stock-health-potion-max: 0\nrare-stock-greater-health-potion-min: 0\nrare-stock-greater-health-potion-max: 0\nrare-stock-reskill-min: 0\nrare-stock-reskill-max: 0\n");try(var f=new FantasyStickLifecycleNativeTest.Fixture(data)){f.plugin.setEnabled(true);var actor=new FantasyStickLifecycleNativeTest.Actor(data);f.players.put(actor.core.id,actor.player);UUID world=UUID.randomUUID();when(actor.world.getUID()).thenReturn(world);f.activate(actor);var directory=(RareMerchantDirectory)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"rareMerchants");var first=directory.place("One",world,actor.core.location.getX(),actor.core.location.getY(),actor.core.location.getZ(),0,0).join();var second=directory.place("Two",world,actor.core.location.getX(),actor.core.location.getY(),actor.core.location.getZ(),0,0).join();var menus=(RareShopMenus)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"rareShopMenus");menus.open(actor.player,first.id());await(f,()->!actor.inventories.isEmpty());var one=actor.inventories.getLast();assertTrue(net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer.plainText().serialize(one.getItem(13).getItemMeta().displayName()).contains("Reskill"));assertEquals(Material.BARRIER,one.getItem(16).getType());menus.open(actor.player,second.id());await(f,()->actor.inventories.size()>=2);var two=actor.inventories.getLast();assertEquals(one.getItem(10).getItemMeta().displayName(),two.getItem(10).getItemMeta().displayName());assertTrue(net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer.plainText().serialize(one.getItem(10).getItemMeta().displayName()).startsWith("Sold out"));}}
|
||||
|
||||
@Test void allPotionSizesPreserveFractionalHealingAndFullHealthStock()throws Exception{try(var f=new FantasyStickLifecycleNativeTest.Fixture(data)){f.plugin.setEnabled(true);var actor=new FantasyStickLifecycleNativeTest.Actor(data);f.players.put(actor.core.id,actor.player);f.activate(actor);var inventory=(RareInventoryDirectory)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"rareInventory");var characters=(CharacterStorage)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"characters");var sessions=(games.dmg.fantasystick.session.EquipmentSessions)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"sessions");inventory.add(actor.core.record.id(),RareProduct.LESSER_HEALTH_POTION,UUID.randomUUID()).join();injure(actor,characters,sessions,new BigDecimal("4"));useFirst(f,actor);awaitEvidence(f,()->actor.player.getHealth()==6.5&&inventory.quantity(actor.core.record.id(),RareProduct.LESSER_HEALTH_POTION).signum()==0,()->"lesser health="+actor.player.getHealth()+" quantity="+inventory.quantity(actor.core.record.id(),RareProduct.LESSER_HEALTH_POTION)+" messages="+actor.messages);inventory.add(actor.core.record.id(),RareProduct.LESSER_HEALTH_POTION,UUID.randomUUID()).join();injure(actor,characters,sessions,BigDecimal.TEN);var potionService=(RarePotionService)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"rarePotions");var refusal=new java.util.concurrent.atomic.AtomicReference<RarePotionService.Outcome>();potionService.use(actor.player,RareProduct.LESSER_HEALTH_POTION,refusal::set);assertEquals(RarePotionService.Status.FULL_HEALTH,refusal.get().status());assertEquals(BigInteger.ONE,inventory.quantity(actor.core.record.id(),RareProduct.LESSER_HEALTH_POTION));var settings=(RareSettings)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"rareSettings");var zero=settings.set("rare-lesser-health-potion-healing-percent","0").toCompletableFuture().join();assertTrue(settings.publish(zero));injure(actor,characters,sessions,BigDecimal.ONE);var noEffect=new java.util.concurrent.atomic.AtomicReference<RarePotionService.Outcome>();potionService.use(actor.player,RareProduct.LESSER_HEALTH_POTION,noEffect::set);assertEquals(RarePotionService.Status.NO_EFFECT,noEffect.get().status());assertEquals(BigInteger.ONE,inventory.quantity(actor.core.record.id(),RareProduct.LESSER_HEALTH_POTION));inventory.add(actor.core.record.id(),RareProduct.GREATER_HEALTH_POTION,UUID.randomUUID()).join();injure(actor,characters,sessions,BigDecimal.ONE);var greater=new java.util.concurrent.atomic.AtomicReference<RarePotionService.Outcome>();potionService.use(actor.player,RareProduct.GREATER_HEALTH_POTION,greater::set);awaitEvidence(f,()->greater.get()!=null&&greater.get().status()==RarePotionService.Status.APPLIED&&actor.player.getHealth()==10&&inventory.quantity(actor.core.record.id(),RareProduct.GREATER_HEALTH_POTION).signum()==0,()->"greater outcome="+greater.get()+" health="+actor.player.getHealth()+" quantities="+inventory.inventory(actor.core.record.id())+" messages="+actor.messages);assertEquals(BigInteger.ONE,inventory.quantity(actor.core.record.id(),RareProduct.LESSER_HEALTH_POTION));}}
|
||||
private static void injure(FantasyStickLifecycleNativeTest.Actor actor,CharacterStorage characters,games.dmg.fantasystick.session.EquipmentSessions sessions,BigDecimal health){var active=sessions.active(actor.core.id).orElseThrow();var record=sessions.currentRecord(active).orElseThrow();var saved=characters.saveHealth(record.id(),record.revision(),health,BigDecimal.valueOf(100)).join().orElseThrow();if(!saved.revision().equals(record.revision()))assertTrue(sessions.acknowledgeProgress(active,record.revision(),saved));actor.player.setHealth(health.doubleValue());}
|
||||
|
||||
@@ -78,6 +78,8 @@ class DistributionTest {
|
||||
"adventure-champion-reward-xp: 150", "adventure-champion-reward-coins: 40")) {
|
||||
assertTrue(defaults.contains(setting), "Missing packaged adventure default: " + setting);
|
||||
}
|
||||
for(String setting:java.util.List.of("rare-price-reskill: 2000","rare-stock-reskill-min: 0","rare-stock-reskill-max: 1"))assertTrue(defaults.contains(setting),"Missing packaged Reskill default: "+setting);
|
||||
assertFalse(defaults.contains("rare-reskill-healing-percent"));
|
||||
assertTrue(defaults.contains("great-sword-base-damage: 7"));
|
||||
assertTrue(defaults.contains("great-sword-recovery-seconds: 0.75"));
|
||||
for (String setting : java.util.List.of("frost-shard-base-damage: 4",
|
||||
|
||||
@@ -350,6 +350,35 @@ class CharacterStorageTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test void reskillAtomicallyRefundsEveryInvestmentClearsBuildAndPreservesIdentityProgressAndCooldowns()throws Exception{
|
||||
var repository=new YamlCharacterRepository(data);
|
||||
var base=new games.dmg.fantasystick.crafting.CharacterFactory().create(games.dmg.fantasystick.progression.ProgressionRules.defaults());
|
||||
var stats=new java.util.EnumMap<>(base.stats());
|
||||
stats.put(games.dmg.fantasystick.progression.Stat.STR,BigInteger.ONE);stats.put(games.dmg.fantasystick.progression.Stat.DEX,BigInteger.TWO);stats.put(games.dmg.fantasystick.progression.Stat.CON,BigInteger.valueOf(9));stats.put(games.dmg.fantasystick.progression.Stat.INT,BigInteger.valueOf(3));stats.put(games.dmg.fantasystick.progression.Stat.WIS,BigInteger.valueOf(5));stats.put(games.dmg.fantasystick.progression.Stat.CHR,BigInteger.valueOf(6));
|
||||
var deadline=java.time.Instant.parse("2026-09-25T00:00:00Z");var receipt=UUID.randomUUID();
|
||||
var invested=new CharacterRecord(base.id(),base.name(),base.revision(),stats,12,BigInteger.valueOf(987),BigInteger.valueOf(100),new java.math.BigDecimal("19"),java.util.Set.of("fireball","unknown_saved"),java.util.List.of("fireball","unknown_saved","","","","",""),java.util.List.of("speed_i","unknown_passive",""),java.util.Map.of("revive",deadline),base.restrictedKills(),false,null,null,BigInteger.valueOf(77),true,java.util.Set.of(receipt),BigInteger.ZERO,base.gear(),BigInteger.valueOf(4));
|
||||
repository.create(invested);var operation=UUID.randomUUID();
|
||||
try(var storage=new CharacterStorage(repository,Clock.systemUTC())){
|
||||
var outcome=storage.reskill(invested.id(),invested.revision(),operation,new java.math.BigDecimal("1024")).join();
|
||||
assertEquals(CharacterStorage.ReskillStatus.APPLIED,outcome.status());var saved=outcome.record().orElseThrow();
|
||||
assertTrue(saved.stats().values().stream().allMatch(BigInteger.ZERO::equals));
|
||||
assertEquals(BigInteger.valueOf(130),saved.unspentPoints());
|
||||
assertTrue(saved.learned().isEmpty());assertEquals(java.util.List.of("","","","","","",""),saved.loadout());assertEquals(java.util.List.of("","",""),saved.passives());
|
||||
assertEquals(new java.math.BigDecimal("10"),saved.health());assertEquals(java.util.Map.of("revive",deadline),saved.cooldowns());
|
||||
assertEquals(invested.id(),saved.id());assertEquals(invested.name(),saved.name());assertEquals(12,saved.level());assertEquals(BigInteger.valueOf(987),saved.experience());assertEquals(BigInteger.valueOf(77),saved.coins());assertEquals(invested.gear(),saved.gear());assertEquals(BigInteger.valueOf(4),saved.sheetGeneration());
|
||||
assertTrue(saved.rewardReceipts().containsAll(java.util.Set.of(receipt,operation)));
|
||||
var duplicate=storage.reskill(invested.id(),invested.revision(),operation,new java.math.BigDecimal("1024")).join();assertEquals(CharacterStorage.ReskillStatus.DUPLICATE,duplicate.status());assertEquals(saved,duplicate.record().orElseThrow());
|
||||
}
|
||||
}
|
||||
|
||||
@Test void reskillPreservesLowerPositiveHealthAndNoOpDoesNotWriteAReceipt()throws Exception{
|
||||
var repository=new YamlCharacterRepository(data);var base=new games.dmg.fantasystick.crafting.CharacterFactory().create(games.dmg.fantasystick.progression.ProgressionRules.defaults());var stats=new java.util.EnumMap<>(base.stats());stats.put(games.dmg.fantasystick.progression.Stat.CON,BigInteger.valueOf(5));var invested=new CharacterRecord(base.id(),base.name(),base.revision(),stats,base.level(),base.experience(),BigInteger.valueOf(35),new java.math.BigDecimal("4.25"),base.learned(),base.loadout(),base.passives(),base.cooldowns(),base.restrictedKills(),false,null,null,base.coins(),base.coinsInitialized(),base.rewardReceipts(),base.pvpCoinEscrow(),base.gear(),base.sheetGeneration());repository.create(invested);try(var storage=new CharacterStorage(repository,Clock.systemUTC())){var applied=storage.reskill(invested.id(),invested.revision(),UUID.randomUUID(),new java.math.BigDecimal("1024")).join().record().orElseThrow();assertEquals(new java.math.BigDecimal("4.25"),applied.health());assertEquals(BigInteger.valueOf(40),applied.unspentPoints());var operation=UUID.randomUUID();var noOp=storage.reskill(applied.id(),applied.revision(),operation,new java.math.BigDecimal("1024")).join();assertEquals(CharacterStorage.ReskillStatus.NOTHING_TO_RESET,noOp.status());assertEquals(applied,noOp.record().orElseThrow());assertFalse(applied.rewardReceipts().contains(operation));assertEquals(applied,repository.load(applied.id()).orElseThrow());}
|
||||
}
|
||||
|
||||
@Test void abilityPersistenceRejectsAmbiguousNonOnePointPurchases()throws Exception{
|
||||
var repository=new YamlCharacterRepository(data);var base=new games.dmg.fantasystick.crafting.CharacterFactory().create(games.dmg.fantasystick.progression.ProgressionRules.defaults());repository.create(base);try(var storage=new CharacterStorage(repository,Clock.systemUTC())){assertThrows(IllegalArgumentException.class,()->storage.unlockAbility(base.id(),base.revision(),"ambiguous",java.util.Map.of(),BigInteger.TWO));assertEquals(base,repository.load(base.id()).orElseThrow());}
|
||||
}
|
||||
|
||||
@Test
|
||||
void abilityUnlearnRefundsExactlyOnePointClearsEverySlotAndPreservesCooldown() throws Exception {
|
||||
var repository = new YamlCharacterRepository(data);
|
||||
|
||||
@@ -10,6 +10,18 @@ import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
class RareSettingsTest {
|
||||
@TempDir Path data;
|
||||
@Test void registersReskillForTheNextSharedCatalogWithoutInventingAHealingSetting()throws Exception{
|
||||
try(var settings=new RareSettings(data,Map.of())){
|
||||
assertTrue(RareSettings.keys().containsAll(java.util.List.of("rare-price-reskill","rare-stock-reskill-min","rare-stock-reskill-max")));
|
||||
assertFalse(RareSettings.keys().contains("rare-reskill-healing-percent"));
|
||||
assertEquals("2000",settings.value("rare-price-reskill"));
|
||||
assertEquals("0",settings.value("rare-stock-reskill-min"));
|
||||
assertEquals("1",settings.value("rare-stock-reskill-max"));
|
||||
assertEquals(java.math.BigInteger.valueOf(2000),settings.rules().basePrices().get(RareProduct.RESKILL));
|
||||
assertFalse(settings.rules().healingPercent().containsKey(RareProduct.RESKILL));
|
||||
}
|
||||
}
|
||||
|
||||
@Test void validatesRangesAndPublishesOnlyAcknowledgedWritesWhilePreservingOtherYaml()throws Exception{
|
||||
java.nio.file.Files.writeString(data.resolve("config.yml"),"unrelated: keep\n");
|
||||
try(var settings=new RareSettings(data,Map.of())){
|
||||
|
||||
@@ -13,7 +13,7 @@ class RareCatalogGeneratorTest {
|
||||
var prices=new EnumMap<RareProduct,BigInteger>(RareProduct.class);
|
||||
var stock=new EnumMap<RareProduct,RareMarketRules.StockRange>(RareProduct.class);
|
||||
var healing=new EnumMap<RareProduct,Integer>(RareProduct.class);
|
||||
for(var product:RareProduct.values()){prices.put(product,BigInteger.valueOf(product.basePrice()));stock.put(product,new RareMarketRules.StockRange(0,product.maximumStock()));healing.put(product,product.defaultHealingPercent());}
|
||||
for(var product:RareProduct.values()){prices.put(product,BigInteger.valueOf(product.basePrice()));stock.put(product,new RareMarketRules.StockRange(0,product.maximumStock()));if(product.heals())healing.put(product,product.defaultHealingPercent());}
|
||||
var rules=new RareMarketRules(prices,10,stock,healing);
|
||||
int[] call={0};
|
||||
var catalog=RareCatalogGenerator.generate(LocalDate.of(2026,9,23),Instant.parse("2026-09-23T12:00:00Z"),RareCatalog.RefreshReason.STARTUP,rules,(minimum,maximum)->call[0]++%2==0?maximum:minimum);
|
||||
@@ -26,7 +26,7 @@ class RareCatalogGeneratorTest {
|
||||
|
||||
@Test void zeroBasePriceStillCostsOneCoinAndEveryProductCanStockZero() {
|
||||
var prices=new EnumMap<RareProduct,BigInteger>(RareProduct.class);var stock=new EnumMap<RareProduct,RareMarketRules.StockRange>(RareProduct.class);var healing=new EnumMap<RareProduct,Integer>(RareProduct.class);
|
||||
for(var product:RareProduct.values()){prices.put(product,BigInteger.ZERO);stock.put(product,new RareMarketRules.StockRange(0,0));healing.put(product,product.defaultHealingPercent());}
|
||||
for(var product:RareProduct.values()){prices.put(product,BigInteger.ZERO);stock.put(product,new RareMarketRules.StockRange(0,0));if(product.heals())healing.put(product,product.defaultHealingPercent());}
|
||||
var catalog=RareCatalogGenerator.generate(LocalDate.of(2026,9,23),Instant.EPOCH,RareCatalog.RefreshReason.ADMINISTRATIVE,new RareMarketRules(prices,100,stock,healing),(minimum,maximum)->minimum);
|
||||
assertTrue(catalog.products().values().stream().allMatch(offer->offer.price().equals(BigInteger.ONE)&&offer.remaining()==0));
|
||||
}
|
||||
|
||||
@@ -13,6 +13,10 @@ import org.junit.jupiter.api.io.TempDir;
|
||||
class RareInventoryDirectoryTest {
|
||||
@TempDir Path data;
|
||||
|
||||
@Test void loadsVersionOnePotionProofBeforeWritingTheExtendedConsumableSchema()throws Exception{
|
||||
UUID character=UUID.randomUUID(),operation=UUID.randomUUID();java.nio.file.Files.writeString(data.resolve("rare-inventory.yml"),"schema-version: 1\ncharacters: []\npurchase-receipts: []\nuses:\n- operation: '"+operation+"'\n character: '"+character+"'\n product: lesser-health-potion\n expected-quantity: '1'\n health-before: '4.5'\n maximum: '10'\n percent: '25'\n phase: RESERVED\n");try(var inventory=new RareInventoryDirectory(new YamlRareInventoryRepository(data))){assertEquals(operation,inventory.unresolvedUses().getFirst().operation());assertEquals(RareInventoryDirectory.UseStatus.COMMITTED,inventory.commitUse(operation).join());}assertTrue(java.nio.file.Files.readString(data.resolve("rare-inventory.yml")).contains("schema-version: 2"));
|
||||
}
|
||||
|
||||
@Test void purchaseReceiptAddsExactlyOneTypedItemAcrossRetryAndRestart() throws Exception {
|
||||
UUID character=UUID.randomUUID(),operation=UUID.randomUUID();
|
||||
try(var inventory=new RareInventoryDirectory(new YamlRareInventoryRepository(data))){
|
||||
@@ -39,6 +43,25 @@ class RareInventoryDirectoryTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test void nonHealingUseReservationRetainsTypedRecoveryProofAcrossRestart()throws Exception{
|
||||
UUID character=UUID.randomUUID(),purchase=UUID.randomUUID(),use=UUID.randomUUID();
|
||||
try(var inventory=new RareInventoryDirectory(new YamlRareInventoryRepository(data))){
|
||||
inventory.add(character,RareProduct.RESKILL,purchase).join();inventory.add(character,RareProduct.RESKILL,UUID.randomUUID()).join();inventory.add(character,RareProduct.HEALTH_POTION,UUID.randomUUID()).join();
|
||||
var reservation=inventory.reserveUse(character,RareProduct.RESKILL,use,BigInteger.TWO).join();
|
||||
assertEquals(RareInventoryDirectory.UseStatus.RESERVED,reservation.status());
|
||||
assertNull(reservation.use().healthBefore());assertNull(reservation.use().maximum());assertEquals(0,reservation.use().percent());
|
||||
}
|
||||
try(var inventory=new RareInventoryDirectory(new YamlRareInventoryRepository(data))){
|
||||
var proof=inventory.unresolvedUses().getFirst();assertEquals(use,proof.operation());assertEquals(RareProduct.RESKILL.id(),proof.product());
|
||||
assertEquals(RareInventoryDirectory.UseStatus.COMMITTED,inventory.commitUse(use).join());
|
||||
assertEquals(BigInteger.ONE,inventory.quantity(character,RareProduct.RESKILL));assertEquals(BigInteger.ONE,inventory.quantity(character,RareProduct.HEALTH_POTION));
|
||||
}
|
||||
}
|
||||
|
||||
@Test void concurrentReskillReservationsCannotSpendOneItemTwice()throws Exception{
|
||||
UUID character=UUID.randomUUID();try(var inventory=new RareInventoryDirectory(new YamlRareInventoryRepository(data))){inventory.add(character,RareProduct.RESKILL,UUID.randomUUID()).join();var first=inventory.reserveUse(character,RareProduct.RESKILL,UUID.randomUUID(),BigInteger.ONE);var second=inventory.reserveUse(character,RareProduct.RESKILL,UUID.randomUUID(),BigInteger.ONE);assertEquals(java.util.Set.of(RareInventoryDirectory.UseStatus.RESERVED,RareInventoryDirectory.UseStatus.NOT_AVAILABLE),java.util.Set.of(first.join().status(),second.join().status()));assertEquals(BigInteger.ZERO,inventory.quantity(character,RareProduct.RESKILL));}
|
||||
}
|
||||
|
||||
@Test void committedUseCannotReplayOrRecreateConsumedStock() throws Exception {
|
||||
UUID character=UUID.randomUUID(),purchase=UUID.randomUUID(),use=UUID.randomUUID();
|
||||
try(var inventory=new RareInventoryDirectory(new YamlRareInventoryRepository(data))){
|
||||
|
||||
@@ -6,7 +6,9 @@ import games.dmg.fantasystick.persistence.*;
|
||||
import java.math.BigInteger;
|
||||
import java.nio.file.Path;
|
||||
import java.time.*;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
@@ -21,12 +23,22 @@ class RareMarketTest {
|
||||
try(var inventory=new RareInventoryDirectory(new YamlRareInventoryRepository(data))){assertEquals(BigInteger.ONE,inventory.quantity(character.id(),RareProduct.HEALTH_POTION));}finally{settings.close();}
|
||||
}
|
||||
|
||||
@Test void buyingReskillStoresItWithoutResettingTheCharacter()throws Exception{
|
||||
var clock=Clock.fixed(Instant.parse("2026-09-24T12:00:00Z"),ZoneOffset.UTC);var settings=new RareSettings(data,Map.of("rare-price-variance-percent","0","rare-price-reskill","2000","rare-stock-reskill-min","1","rare-stock-reskill-max","1"));var repository=new YamlCharacterRepository(data);var base=new games.dmg.fantasystick.crafting.CharacterFactory().create(games.dmg.fantasystick.progression.ProgressionRules.defaults());var stats=new java.util.EnumMap<>(base.stats());stats.put(games.dmg.fantasystick.progression.Stat.STR,BigInteger.ONE);var character=new CharacterRecord(base.id(),base.name(),base.revision(),stats,base.level(),base.experience(),BigInteger.valueOf(39),base.health(),Set.of("unknown_saved"),List.of("unknown_saved","","","","","",""),base.passives(),Map.of("revive",Instant.parse("2026-09-25T00:00:00Z")),base.restrictedKills(),false,null,null,BigInteger.valueOf(3000),true,Set.of(),BigInteger.ZERO,CharacterGear.none());
|
||||
try(var characters=new CharacterStorage(repository,clock);var inventory=new RareInventoryDirectory(new YamlRareInventoryRepository(data));var market=new RareMarket(new YamlRareCatalogRepository(data),new RarePurchaseOperationStore(data),characters,inventory,settings::rules,clock,(minimum,maximum)->minimum)){characters.create(character).join();var catalog=market.current().toCompletableFuture().join();var bought=market.purchase(character.id(),character.revision(),catalog.revision(),RareProduct.RESKILL).toCompletableFuture().join();assertEquals(RareMarket.PurchaseStatus.APPLIED,bought.status());var saved=bought.record().orElseThrow();assertEquals(stats,saved.stats());assertEquals(character.learned(),saved.learned());assertEquals(character.cooldowns(),saved.cooldowns());assertEquals(BigInteger.valueOf(1000),saved.coins());assertEquals(BigInteger.ONE,inventory.quantity(character.id(),RareProduct.RESKILL));}finally{settings.close();}
|
||||
}
|
||||
|
||||
@Test void restartFinishesDebitInventoryAndStockAfterSettlementFailureWithoutDuplication()throws Exception{var clock=Clock.fixed(Instant.parse("2026-09-23T12:00:00Z"),ZoneOffset.UTC);var settings=new RareSettings(data,Map.of("rare-price-variance-percent","0","rare-price-health-potion","40","rare-stock-health-potion-min","1","rare-stock-health-potion-max","1"));var charactersRepository=new YamlCharacterRepository(data);var character=withCoins(new games.dmg.fantasystick.crafting.CharacterFactory().create(games.dmg.fantasystick.progression.ProgressionRules.defaults()));var durable=new YamlRareCatalogRepository(data);class Failing implements RareCatalogRepository{int saves;public java.util.Optional<RareCatalog> load()throws java.io.IOException{return durable.load();}public void save(RareCatalog catalog)throws java.io.IOException{if(++saves==3)throw new java.io.IOException("injected settlement failure");durable.save(catalog);}}try(var characters=new CharacterStorage(charactersRepository,clock);var inventory=new RareInventoryDirectory(new YamlRareInventoryRepository(data))){characters.create(character).join();try(var market=new RareMarket(new Failing(),new RarePurchaseOperationStore(data),characters,inventory,settings::rules,clock,(minimum,maximum)->minimum)){var catalog=market.current().toCompletableFuture().join();assertThrows(java.util.concurrent.CompletionException.class,()->market.purchase(character.id(),character.revision(),catalog.revision(),RareProduct.HEALTH_POTION).toCompletableFuture().join());}}try(var characters=new CharacterStorage(charactersRepository,clock);var inventory=new RareInventoryDirectory(new YamlRareInventoryRepository(data));var market=new RareMarket(durable,new RarePurchaseOperationStore(data),characters,inventory,settings::rules,clock,(minimum,maximum)->maximum)){var catalog=market.current().toCompletableFuture().join();assertEquals(BigInteger.valueOf(60),characters.find(character.id()).join().orElseThrow().coins());assertEquals(BigInteger.ONE,inventory.quantity(character.id(),RareProduct.HEALTH_POTION));assertEquals(0,catalog.offer(RareProduct.HEALTH_POTION).remaining());assertTrue(catalog.transactions().isEmpty());}finally{settings.close();}}
|
||||
|
||||
@Test void competingBuyersCannotOversellTheLastSharedUnit()throws Exception{var clock=Clock.fixed(Instant.parse("2026-09-23T12:00:00Z"),ZoneOffset.UTC);var settings=new RareSettings(data,Map.of("rare-price-variance-percent","0","rare-price-health-potion","40","rare-stock-health-potion-min","1","rare-stock-health-potion-max","1"));var repository=new YamlCharacterRepository(data);var factory=new games.dmg.fantasystick.crafting.CharacterFactory();var a=withCoins(factory.create(games.dmg.fantasystick.progression.ProgressionRules.defaults()));var b=withCoins(factory.create(games.dmg.fantasystick.progression.ProgressionRules.defaults()));try(var characters=new CharacterStorage(repository,clock);var inventory=new RareInventoryDirectory(new YamlRareInventoryRepository(data));var market=new RareMarket(new YamlRareCatalogRepository(data),new RarePurchaseOperationStore(data),characters,inventory,settings::rules,clock,(minimum,maximum)->minimum)){characters.create(a).join();characters.create(b).join();var catalog=market.current().toCompletableFuture().join();var first=market.purchase(a.id(),a.revision(),catalog.revision(),RareProduct.HEALTH_POTION).toCompletableFuture();var second=market.purchase(b.id(),b.revision(),catalog.revision(),RareProduct.HEALTH_POTION).toCompletableFuture();assertEquals(java.util.Set.of(RareMarket.PurchaseStatus.APPLIED,RareMarket.PurchaseStatus.SOLD_OUT),java.util.Set.of(first.join().status(),second.join().status()));assertEquals(0,market.current().toCompletableFuture().join().offer(RareProduct.HEALTH_POTION).remaining());assertEquals(BigInteger.ONE,inventory.quantity(a.id(),RareProduct.HEALTH_POTION).add(inventory.quantity(b.id(),RareProduct.HEALTH_POTION)));}finally{settings.close();}}
|
||||
|
||||
private static CharacterRecord withCoins(CharacterRecord old){return new CharacterRecord(old.id(),old.name(),old.revision(),old.stats(),old.level(),old.experience(),old.unspentPoints(),old.health(),old.learned(),old.loadout(),old.passives(),old.cooldowns(),old.restrictedKills(),false,null,null,BigInteger.valueOf(100),true,java.util.Set.of(),BigInteger.ZERO,CharacterGear.none());}
|
||||
|
||||
@Test void newlyDeliveredReskillWaitsForTheNextRefreshInsteadOfRerollingTheCurrentCatalog()throws Exception{
|
||||
var now=Instant.parse("2026-09-24T12:00:00Z");var clock=Clock.fixed(now,ZoneOffset.UTC);var offers=new java.util.EnumMap<RareProduct,RareCatalog.Offer>(RareProduct.class);for(var product:List.of(RareProduct.LESSER_HEALTH_POTION,RareProduct.HEALTH_POTION,RareProduct.GREATER_HEALTH_POTION))offers.put(product,new RareCatalog.Offer(BigInteger.ONE,1));var revision=java.util.UUID.randomUUID();var legacy=new RareCatalog(LocalDate.of(2026,9,24),revision,now,RareCatalog.RefreshReason.STARTUP,offers);new YamlRareCatalogRepository(data).save(legacy);var settings=new RareSettings(data,Map.of("rare-stock-reskill-min","1","rare-stock-reskill-max","1"));var repository=new YamlCharacterRepository(data);var character=withCoins(new games.dmg.fantasystick.crafting.CharacterFactory().create(games.dmg.fantasystick.progression.ProgressionRules.defaults()));
|
||||
try(var characters=new CharacterStorage(repository,clock);var inventory=new RareInventoryDirectory(new YamlRareInventoryRepository(data));var market=new RareMarket(new YamlRareCatalogRepository(data),new RarePurchaseOperationStore(data),characters,inventory,settings::rules,clock,(minimum,maximum)->minimum)){characters.create(character).join();var current=market.current().toCompletableFuture().join();assertEquals(revision,current.revision());assertFalse(current.available(RareProduct.RESKILL));assertEquals(RareMarket.PurchaseStatus.UNAVAILABLE,market.purchase(character.id(),character.revision(),revision,RareProduct.RESKILL).toCompletableFuture().join().status());var refreshed=market.restock().toCompletableFuture().join();assertTrue(refreshed.available(RareProduct.RESKILL));assertEquals(1,refreshed.offer(RareProduct.RESKILL).remaining());}finally{settings.close();}
|
||||
}
|
||||
|
||||
@Test void staleGenerationAndZeroStockRefuseWithoutCoinsOrInventoryMutation() throws Exception {
|
||||
var clock=Clock.fixed(Instant.parse("2026-09-23T12:00:00Z"),ZoneOffset.UTC);var settings=new RareSettings(data,Map.of("rare-stock-lesser-health-potion-min","0","rare-stock-lesser-health-potion-max","0"));var repository=new YamlCharacterRepository(data);var base=new games.dmg.fantasystick.crafting.CharacterFactory().create(games.dmg.fantasystick.progression.ProgressionRules.defaults());var character=new CharacterRecord(base.id(),base.name(),base.revision(),base.stats(),base.level(),base.experience(),base.unspentPoints(),base.health(),base.learned(),base.loadout(),base.passives(),base.cooldowns(),base.restrictedKills(),false,null,null,BigInteger.valueOf(100),true,java.util.Set.of(),BigInteger.ZERO,CharacterGear.none());
|
||||
try(var characters=new CharacterStorage(repository,clock);var inventory=new RareInventoryDirectory(new YamlRareInventoryRepository(data));var market=new RareMarket(new YamlRareCatalogRepository(data),new RarePurchaseOperationStore(data),characters,inventory,settings::rules,clock,(minimum,maximum)->minimum)){
|
||||
|
||||
Reference in new issue
Block a user