Keep thirst in the owned shared player profile

This commit is contained in:
unimatrixgit 2026-12-06 14:40:52 +01:00
commit 0aa09e3853
6 changed files with 225 additions and 5 deletions

View file

@ -170,6 +170,7 @@ public final class DuneCore extends JavaPlugin implements Listener, CommandExecu
Bukkit.getScheduler().runTaskTimer(this, this::spawnSandworms, 200L, 200L);
Bukkit.getScheduler().runTaskTimer(this, this::spawnSpiceRaiders, 200L, 200L);
getLogger().info("DuneCore enabled. Gameplay, faction travel, Arrakis threats, and spice raiders ready.");
HydrationProfiles.start(this);
}
@Override public void onDisable() {
OrdosCold.close(this);
@ -182,6 +183,7 @@ public final class DuneCore extends JavaPlugin implements Listener, CommandExecu
catch (Exception ex) { getLogger().severe("Shared shutdown save failed for " + p.getName() + ": " + ex.getMessage()); }
sharedDatabase.close();
} else if (data != null && dataFile != null) savePlayers();
HydrationProfiles.close();
}
private void savePlayers() {
if (sharedDatabase != null) {

View file

@ -0,0 +1,100 @@
package com.example.dunerealms;
import java.lang.reflect.Field;
import java.sql.*;
import java.util.*;
import org.bukkit.*;
import org.bukkit.boss.*;
import org.bukkit.entity.Player;
import org.bukkit.event.*;
import org.bukkit.event.player.*;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.PotionMeta;
import org.bukkit.persistence.PersistentDataType;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.potion.PotionType;
/** Hydration belongs to the existing lock-owned network profile, never local player data. */
public final class HydrationProfiles implements Listener {
private static final Map<UUID,Double> values=new HashMap<>();
private static final Set<String> PLANETS=Set.of("arrakis","caladan","kaitain","giedi_prime","sigma_draconis_iv");
private final JavaPlugin plugin;
private final SharedDatabase database;
private final Map<UUID,BossBar> bars=new HashMap<>();
private static HydrationProfiles active;
private HydrationProfiles(JavaPlugin plugin,SharedDatabase database){this.plugin=plugin;this.database=database;}
public static void initialize(SharedDatabase database)throws SQLException{
try(Connection c=database.connect()){
boolean exists;
try(PreparedStatement p=c.prepareStatement("SELECT * FROM dune_players WHERE 1=0");ResultSet r=p.executeQuery()){
exists=false;ResultSetMetaData m=r.getMetaData();for(int i=1;i<=m.getColumnCount();i++)if(m.getColumnName(i).equalsIgnoreCase("hydration"))exists=true;
}
if(!exists)try(Statement s=c.createStatement()){s.executeUpdate("ALTER TABLE dune_players ADD COLUMN hydration DOUBLE PRECISION NOT NULL DEFAULT 100");}
catch(SQLException e){if(!"42S21".equals(e.getSQLState())&&!"42701".equals(e.getSQLState()))throw e;}
try(Statement s=c.createStatement();ResultSet r=s.executeQuery("SELECT hydration FROM dune_players WHERE 1=0")){r.getMetaData();}
}
}
public static void load(Player player,ResultSet row)throws SQLException{
double amount=row.getDouble("hydration");
if(row.wasNull()||!Double.isFinite(amount)||amount<0||amount>100)throw new SQLException("Invalid shared hydration profile");
values.put(player.getUniqueId(),amount);
}
/** Called within the original single atomic profile UPDATE on its owning connection. */
public static void bind(PreparedStatement query,Player player)throws SQLException{
Double value=values.get(player.getUniqueId());
if(value==null||!Double.isFinite(value)||value<0||value>100)throw new SQLException("Hydration profile was not loaded");
query.setDouble(9,value);
if(query.getConnection().getMetaData().getDatabaseProductName().equalsIgnoreCase("PostgreSQL"))query.setObject(10,player.getUniqueId());
else query.setString(10,player.getUniqueId().toString());
}
public static void forget(Player player){values.remove(player.getUniqueId());if(active!=null)active.hide(player.getUniqueId());}
public static void start(JavaPlugin plugin){
try{
Object db=plugin.getClass().getMethod("sharedDatabase").invoke(plugin);
if(!(db instanceof SharedDatabase shared))return;
if(active!=null)throw new IllegalStateException("Hydration already started");
active=new HydrationProfiles(plugin,shared);
Bukkit.getPluginManager().registerEvents(active,plugin);
Bukkit.getScheduler().runTaskTimer(plugin,active::tick,20L,20L);
plugin.getLogger().info("Shared thirst active; Arrakis 2/min, other planets 1/min; Lobby and Builder exempt");
}catch(ReflectiveOperationException e){throw new IllegalStateException("Shared hydration API unavailable",e);}
}
public static void close(){if(active!=null){active.bars.values().forEach(BossBar::removeAll);active.bars.clear();active=null;}values.clear();}
static String realm(String name){for(String p:PLANETS)if(name.equals(p)||name.equals(p+"_nether")||name.equals(p+"_the_end"))return p;return "";}
static double decay(String realm){return realm.equals("arrakis")?2.0/60:1.0/60;}
private boolean eligible(Player player){
if(!player.isOnline()||player.isDead()||!Set.of(GameMode.SURVIVAL,GameMode.ADVENTURE).contains(player.getGameMode())||realm(player.getWorld().getName()).isEmpty()||!database.isLoaded(player.getUniqueId())||!values.containsKey(player.getUniqueId()))return false;
try{
Field field=SharedDatabase.class.getDeclaredField("builderLeases");field.setAccessible(true);
return field.get(database) instanceof Map<?,?> leases&&!leases.containsKey(player.getUniqueId());
}catch(NoSuchFieldException e){return true;}catch(ReflectiveOperationException e){return false;}
}
private void hide(UUID id){BossBar old=bars.remove(id);if(old!=null)old.removeAll();}
private void tick(){
for(Player player:Bukkit.getOnlinePlayers()){
UUID id=player.getUniqueId();if(!eligible(player)){hide(id);continue;}
double value=Math.max(0,values.get(id)-decay(realm(player.getWorld().getName())));values.put(id,value);
BossBar bar=bars.computeIfAbsent(id,key->{BossBar b=Bukkit.createBossBar("Thirst",BarColor.BLUE,BarStyle.SEGMENTED_10);b.addPlayer(player);return b;});
bar.setProgress(value/100);bar.setTitle("Hydration "+(int)Math.ceil(value)+" / 100");bar.setColor(value<20?BarColor.RED:BarColor.BLUE);
}
}
private int restoration(ItemStack item){
var jarvis=Bukkit.getPluginManager().getPlugin("JarvisTranslator");
if(jarvis!=null&&jarvis.isEnabled())try{return Math.max(0,Math.min(100,(Integer)jarvis.getClass().getMethod("hydrationRestoration",ItemStack.class).invoke(jarvis,item)));}
catch(ReflectiveOperationException e){plugin.getLogger().warning("Drink hydration API unavailable");return 0;}
return 0;
}
static boolean plainWater(ItemStack item){
if(item==null||item.getType()!=Material.POTION||!(item.getItemMeta() instanceof PotionMeta meta)||meta.getBasePotionType()!=PotionType.WATER||meta.hasCustomEffects())return false;
return !meta.getPersistentDataContainer().has(new NamespacedKey("executableitems","ei-id"),PersistentDataType.STRING)
&&!meta.getPersistentDataContainer().has(new NamespacedKey("dunerealms","item"),PersistentDataType.STRING);
}
@EventHandler(priority=EventPriority.MONITOR,ignoreCancelled=true) public void consume(PlayerItemConsumeEvent event){
Player player=event.getPlayer();if(!eligible(player))return;
ItemStack item=event.getItem();int amount=plainWater(item)?35:restoration(item);
if(amount<=0)return;
Bukkit.getScheduler().runTask(plugin,()->{if(!event.isCancelled()&&eligible(player))values.computeIfPresent(player.getUniqueId(),(id,v)->Math.min(100,v+amount));});
}
@EventHandler public void quit(PlayerQuitEvent event){hide(event.getPlayer().getUniqueId());}
}

View file

@ -49,6 +49,7 @@ public final class SharedDatabase implements AutoCloseable {
s.executeUpdate("CREATE TABLE IF NOT EXISTS dune_bounties (target UUID PRIMARY KEY, world TEXT NOT NULL, reward INTEGER NOT NULL, claimed BOOLEAN NOT NULL DEFAULT FALSE, hunter UUID)");
c.commit();
}
HydrationProfiles.initialize(this);
}
public Connection connect() throws SQLException {
@ -90,12 +91,13 @@ public final class SharedDatabase implements AutoCloseable {
Integer level, total, slot;
Float progress;
try (PreparedStatement q = c.prepareStatement(
"SELECT faction,inventory,experience_level,experience_progress,total_experience,held_slot,session_open FROM dune_players WHERE uuid=?")) {
"SELECT faction,inventory,experience_level,experience_progress,total_experience,held_slot,session_open,hydration FROM dune_players WHERE uuid=?")) {
q.setObject(1, id);
try (ResultSet r = q.executeQuery()) {
if (!r.next()) throw new SQLException("Missing network profile");
if (r.getBoolean("session_open"))
throw new SQLException("Unclean previous session; administrator recovery required");
HydrationProfiles.load(p,r);
faction = r.getString("faction");
String blob = r.getString("inventory");
if (blob != null && !blob.isBlank()) inventory = decode(blob);
@ -225,6 +227,7 @@ public final class SharedDatabase implements AutoCloseable {
writePlayer(p, factions, true);
} finally {
forgetBuilderProfile(p);
HydrationProfiles.forget(p);
Connection c = sessions.remove(p.getUniqueId());
if (c != null) c.close();
}
@ -236,7 +239,7 @@ public final class SharedDatabase implements AutoCloseable {
// Never reconnect here: a replacement connection would not own the session lock.
String inventory = encode(p.getInventory().getContents());
try (PreparedStatement q = c.prepareStatement(
"UPDATE dune_players SET faction=?,inventory=?,experience_level=?,experience_progress=?,total_experience=?,held_slot=?,session_open=?,inventory_view=?::jsonb,inventory_updated_at=CURRENT_TIMESTAMP WHERE uuid=?")) {
"UPDATE dune_players SET faction=?,inventory=?,experience_level=?,experience_progress=?,total_experience=?,held_slot=?,session_open=?,inventory_view=?::jsonb,inventory_updated_at=CURRENT_TIMESTAMP,hydration=? WHERE uuid=?")) {
q.setString(1, factions.getOrDefault(p.getUniqueId(), ""));
q.setString(2, inventory);
q.setInt(3, p.getLevel());
@ -246,6 +249,7 @@ public final class SharedDatabase implements AutoCloseable {
q.setBoolean(7, !release);
q.setString(8, InventoryWebSnapshot.capture(p));
q.setObject(9, p.getUniqueId());
HydrationProfiles.bind(q,p);
if (q.executeUpdate() != 1) throw new SQLException("Network profile disappeared during save");
} catch (SQLException ex) {
try {

View file

@ -31,10 +31,23 @@ class SharedDatabaseTest {
@BeforeEach void prepare() throws Exception {
Connection schema = mock(Connection.class);
when(schema.createStatement()).thenReturn(mock(Statement.class));
PreparedStatement hydrationSchema=mock(PreparedStatement.class);
ResultSet hydrationColumns=mock(ResultSet.class);
ResultSetMetaData hydrationMeta=mock(ResultSetMetaData.class);
when(schema.prepareStatement(anyString())).thenReturn(hydrationSchema);
when(hydrationSchema.executeQuery()).thenReturn(hydrationColumns);
when(hydrationColumns.getMetaData()).thenReturn(hydrationMeta);
when(hydrationMeta.getColumnCount()).thenReturn(1);
when(hydrationMeta.getColumnName(1)).thenReturn("hydration");
when(schema.createStatement().executeQuery(anyString())).thenReturn(hydrationColumns);
owner = mock(Connection.class);
DatabaseMetaData ownerMeta=mock(DatabaseMetaData.class);
when(ownerMeta.getDatabaseProductName()).thenReturn("PostgreSQL");
when(owner.getMetaData()).thenReturn(ownerMeta);
lock = mock(PreparedStatement.class);
row = mock(PreparedStatement.class);
update = mock(PreparedStatement.class);
when(update.getConnection()).thenReturn(owner);
lockResult = mock(ResultSet.class);
profile = mock(ResultSet.class);
when(owner.prepareStatement(anyString())).thenAnswer(call -> {
@ -49,10 +62,11 @@ class SharedDatabaseTest {
when(row.executeQuery()).thenReturn(profile);
when(profile.next()).thenReturn(true);
when(profile.getString("faction")).thenReturn("fremen");
when(profile.getDouble("hydration")).thenReturn(100.0);
when(update.executeUpdate()).thenReturn(1);
driver = mock(Driver.class);
when(driver.acceptsURL("jdbc:dune-test:profiles")).thenReturn(true);
when(driver.connect(eq("jdbc:dune-test:profiles"), any())).thenReturn(schema, owner);
when(driver.connect(eq("jdbc:dune-test:profiles"), any())).thenReturn(schema, schema, owner);
DriverManager.registerDriver(driver);
JavaPlugin plugin = mock(JavaPlugin.class);
YamlConfiguration config = new YamlConfiguration();
@ -76,9 +90,27 @@ class SharedDatabaseTest {
@AfterEach void cleanup() throws Exception {
db.close();
HydrationProfiles.close();
DriverManager.deregisterDriver(driver);
}
@Test void hydrationIsLoadedAndSavedInsideTheOriginalOwnedAtomicCheckpoint() throws Exception {
when(profile.getDouble("hydration")).thenReturn(37.25);
db.loadPlayer(player,factions);
db.savePlayer(player,factions);
verify(update).setDouble(9,37.25);
verify(update).setObject(10,id);
verify(owner).prepareStatement(contains("hydration=? WHERE uuid=?"));
verify(driver,times(3)).connect(eq("jdbc:dune-test:profiles"),any());
}
@Test void invalidHydrationRefusesProfileBeforeOpeningOrApplyingInventory() throws Exception {
when(profile.getDouble("hydration")).thenReturn(Double.NaN);
assertThrows(SQLException.class,()->db.loadPlayer(player,factions));
verify(owner,never()).prepareStatement("UPDATE dune_players SET session_open=TRUE WHERE uuid=?");
verify(inventory,never()).setContents(any());
}
@Test void builderCheckpointRejectsCreativeWritesAndRestoresCommittedInventory() throws Exception {
db.loadPlayer(player, factions);
when(owner.getAutoCommit()).thenReturn(true);
@ -160,13 +192,13 @@ class SharedDatabaseTest {
verify(update).setBoolean(7, false);
verify(owner).close();
assertFalse(db.isLoaded(id));
verify(driver, times(2)).connect(anyString(), any()); // Schema + one owned connection only.
verify(driver, times(3)).connect(anyString(), any()); // Schema + hydration schema + one owned connection only.
}
@Test void duplicateLoadOnSameBackendCannotOverwriteSession() throws Exception {
db.loadPlayer(player, factions);
assertThrows(SQLException.class, () -> db.loadPlayer(player, factions));
verify(driver, times(2)).connect(anyString(), any());
verify(driver, times(3)).connect(anyString(), any());
verify(owner, never()).close();
}

54
tools/HydrationMerge.java Normal file
View file

@ -0,0 +1,54 @@
import java.nio.file.*;
import java.util.*;
import java.util.zip.*;
import org.objectweb.asm.*;
import org.objectweb.asm.tree.*;
/** Adds profile hydration to the retained native SQL paths without replacing their ownership logic. */
public class HydrationMerge {
static final String P="com/example/dunerealms/",H=P+"HydrationProfiles",DB=P+"SharedDatabase";
static MethodInsnNode call(String name,String descriptor){return new MethodInsnNode(Opcodes.INVOKESTATIC,H,name,descriptor,false);}
static ClassNode read(byte[] b){ClassNode c=new ClassNode();new ClassReader(b).accept(c,0);return c;}
static byte[] write(ClassNode c){ClassWriter w=new ClassWriter(ClassWriter.COMPUTE_MAXS);c.accept(w);return w.toByteArray();}
static void need(boolean condition,String message){if(!condition)throw new IllegalStateException(message);}
public static void main(String[] args)throws Exception{
Path out=Path.of(args[1]);Files.createDirectories(out);
try(ZipFile zip=new ZipFile(args[0])){
ClassNode db=read(zip.getInputStream(zip.getEntry(DB+".class")).readAllBytes());
int ctors=0,loads=0,writes=0,loadCalls=0,binds=0,releases=0;
for(MethodNode m:db.methods){
if(m.name.equals("<init>"))for(AbstractInsnNode n:m.instructions.toArray())if(n.getOpcode()==Opcodes.RETURN){InsnList x=new InsnList();x.add(new VarInsnNode(Opcodes.ALOAD,0));x.add(call("initialize","(L"+DB+";)V"));m.instructions.insertBefore(n,x);ctors++;}
if(m.name.equals("loadPlayer")){
for(AbstractInsnNode n:m.instructions.toArray()){
if(n instanceof LdcInsnNode l&&l.cst instanceof String s&&s.startsWith("SELECT faction,inventory")&&s.contains("session_open FROM dune_players")){l.cst=s.replace("session_open FROM","session_open,hydration FROM");loads++;}
if(n instanceof MethodInsnNode i&&i.owner.equals("java/sql/ResultSet")&&i.name.equals("getString")&&n.getPrevious() instanceof LdcInsnNode l&&"faction".equals(l.cst)&&l.getPrevious() instanceof VarInsnNode v&&v.getOpcode()==Opcodes.ALOAD){InsnList x=new InsnList();x.add(new VarInsnNode(Opcodes.ALOAD,1));x.add(new VarInsnNode(Opcodes.ALOAD,v.var));x.add(call("load","(Lorg/bukkit/entity/Player;Ljava/sql/ResultSet;)V"));m.instructions.insertBefore(v,x);loadCalls++;}
}
}
if(m.name.equals("writePlayer"))for(AbstractInsnNode n:m.instructions.toArray()){
if(n instanceof InvokeDynamicInsnNode indy)for(int a=0;a<indy.bsmArgs.length;a++)if(indy.bsmArgs[a] instanceof String s&&s.startsWith("UPDATE dune_players SET faction=")){
need(s.chars().filter(c->c=='?').count()==8&&s.chars().filter(c->c==1).count()==1&&s.endsWith(" WHERE uuid=?")&&!s.contains("hydration"),"Unexpected dynamic profile UPDATE");
indy.bsmArgs[a]=s.replace(" WHERE uuid=?",",hydration=? WHERE uuid=?");writes++;
}
if(n instanceof LdcInsnNode l&&l.cst instanceof String s&&s.startsWith("UPDATE dune_players SET faction=")){
need(s.chars().filter(c->c=='?').count()==9&&!s.contains("hydration"),"Unexpected native profile UPDATE");
need(s.endsWith(" WHERE uuid=?"),"Unexpected native profile WHERE");l.cst=s.replace(" WHERE uuid=?",",hydration=? WHERE uuid=?");writes++;
}
if(n instanceof MethodInsnNode i&&i.owner.equals("java/sql/PreparedStatement")&&i.name.equals("executeUpdate")&&i.desc.equals("()I")&&n.getPrevious() instanceof VarInsnNode v&&v.getOpcode()==Opcodes.ALOAD){InsnList x=new InsnList();x.add(new VarInsnNode(Opcodes.ALOAD,v.var));x.add(new VarInsnNode(Opcodes.ALOAD,1));x.add(call("bind","(Ljava/sql/PreparedStatement;Lorg/bukkit/entity/Player;)V"));m.instructions.insertBefore(v,x);binds++;}
}
if(m.name.equals("releasePlayer"))for(AbstractInsnNode n:m.instructions.toArray())if(n.getOpcode()==Opcodes.RETURN||n.getOpcode()==Opcodes.ATHROW){InsnList x=new InsnList();x.add(new VarInsnNode(Opcodes.ALOAD,1));x.add(call("forget","(Lorg/bukkit/entity/Player;)V"));m.instructions.insertBefore(n,x);releases++;}
}
need(ctors>0&&loads==1&&loadCalls==1&&(writes==1||writes==2)&&binds==1&&releases>0,"Native SQL anchor mismatch: "+List.of(ctors,loads,loadCalls,writes,binds,releases));
Files.write(out.resolve("SharedDatabase.class"),write(db));
ClassNode core=read(zip.getInputStream(zip.getEntry(P+"DuneCore.class")).readAllBytes());
boolean getter=core.methods.stream().anyMatch(m->m.name.equals("sharedDatabase")&&m.desc.equals("()L"+DB+";")&&(m.access&Opcodes.ACC_PUBLIC)!=0);
if(!getter){need(core.fields.stream().anyMatch(f->f.name.equals("sharedDatabase")&&f.desc.equals("L"+DB+";")),"Shared profile field missing");MethodNode m=new MethodNode(Opcodes.ACC_PUBLIC,"sharedDatabase","()L"+DB+";",null,null);m.instructions.add(new VarInsnNode(Opcodes.ALOAD,0));m.instructions.add(new FieldInsnNode(Opcodes.GETFIELD,core.name,"sharedDatabase","L"+DB+";"));m.instructions.add(new InsnNode(Opcodes.ARETURN));core.methods.add(m);}
int enable=0,disable=0;
for(MethodNode m:core.methods)for(AbstractInsnNode n:m.instructions.toArray())if(n.getOpcode()==Opcodes.RETURN){
if(m.name.equals("onEnable")){InsnList x=new InsnList();x.add(new VarInsnNode(Opcodes.ALOAD,0));x.add(call("start","(Lorg/bukkit/plugin/java/JavaPlugin;)V"));m.instructions.insertBefore(n,x);enable++;}
if(m.name.equals("onDisable")){m.instructions.insertBefore(n,call("close","()V"));disable++;}
}
need(enable>0&&disable>0,"Core lifecycle missing");Files.write(out.resolve("DuneCore.class"),write(core));
System.out.println("Preserved retained SQL/session logic; added hydration hooks "+List.of(ctors,loads,loadCalls,writes,binds,releases,enable,disable));
}
}
}

28
tools/plugin_hydration.py Normal file
View file

@ -0,0 +1,28 @@
"""Deterministic narrow retained Core overlay; baseline, donor and helper must be source-pinned by caller."""
import argparse,hashlib,os,pathlib,subprocess,tempfile,zipfile
p=argparse.ArgumentParser();p.add_argument('baseline');p.add_argument('baseline_sha');p.add_argument('donor_class');p.add_argument('donor_sha');p.add_argument('output');p.add_argument('asm_classpath');a=p.parse_args()
sha=lambda b:hashlib.sha256(b).hexdigest()
base=pathlib.Path(a.baseline);donor=pathlib.Path(a.donor_class);target=pathlib.Path(a.output)
assert sha(base.read_bytes())==a.baseline_sha,'Retained baseline hash mismatch'
assert sha(donor.read_bytes())==a.donor_sha,'Donor class hash mismatch'
assert base.resolve()!=target.resolve(),'Never overwrite baseline'
java=pathlib.Path(os.environ['JAVA_HOME'])/'bin'/('java.exe'if os.name=='nt'else'java')
helper=pathlib.Path(__file__).with_name('HydrationMerge.java')
with tempfile.TemporaryDirectory()as tmp:
subprocess.run([str(java),'--class-path',a.asm_classpath,str(helper),str(base),tmp],check=True)
prefix='com/example/dunerealms/'
changes={prefix+n:(pathlib.Path(tmp)/n).read_bytes()for n in ['DuneCore.class','SharedDatabase.class']}
addition=prefix+'HydrationProfiles.class'
with zipfile.ZipFile(base)as old:
assert addition not in old.namelist(),'Hydration already installed'
assert len(old.namelist())==len(set(old.namelist())),'Duplicate baseline archive entry'
with zipfile.ZipFile(target,'w',compression=zipfile.ZIP_DEFLATED,compresslevel=9)as new:
for info in old.infolist():
if info.is_dir():continue
new.writestr(info,changes.get(info.filename,old.read(info)))
z=zipfile.ZipInfo(addition,(2026,1,1,0,0,0));z.compress_type=zipfile.ZIP_DEFLATED;new.writestr(z,donor.read_bytes())
with zipfile.ZipFile(target)as new,zipfile.ZipFile(base)as old:
previous={i.filename for i in old.infolist()if not i.is_dir()};now=set(new.namelist())
assert now-previous=={addition}and previous-now==set()
actual={n for n in previous if old.read(n)!=new.read(n)};assert actual==set(changes)
print('OUTPUT_SHA256',sha(target.read_bytes()),'CHANGED',','.join(sorted(changes)),'ADDED',addition)