This commit is contained in:
1 parent
fa87b44cc8
commit
c960dbcf7b
24 files changed
+318
-33
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());}}
|
||||
|
||||
Reference in new issue
Block a user