diff --git a/network/ARRAKIS-CREATURES.md b/network/ARRAKIS-CREATURES.md new file mode 100644 index 00000000..6cc6d4ac --- /dev/null +++ b/network/ARRAKIS-CREATURES.md @@ -0,0 +1,19 @@ +# Approved Arrakis creature and recipe scope + +Implementation remains pending until deployed and verified. Keep terrain separate +and preserve the live 1.0.12-arrakeen1 terrain build when recovering its source. + +- Rabbits become Jerboas on Arrakis only; preserve custom worms, raiders and NPCs. +- Hide: Common MK I. Raw meat: Uncommon MK III. Water vial: Rare MK VI, 20% drop. +- Cooked meat: Rare MK VI; fire death and furnace/smoker/campfire use the same item. +- Jerboa stew: Very Rare MK IX. Use Jerboa meat and contaminated spice instead + of the mushroom in the rabbit stew recipe; retain the remaining ingredients. +- Refined spice breeds Jerboas. Use custom flesh, hide and creature artwork. +- Spice blooms can produce tiny worms represented by retextured wolves. +- Jerboa stew tames them with 100% success and breeds them like native wolves. + Offspring automatically belong to their owner and follow the native growth cycle. +- Pets are permanently immune to suffocation, independently of water buffs. +- Water vial: +25% attack damage and max health, and regeneration, for 90 seconds. + Reapplication refreshes the duration rather than stacking modifiers. +- Pet death: spice and one bone, both guaranteed. Bone bears the pet's name, + Legendary MK XIV; memorial item, no extra combat power. diff --git a/network/central-game-storage.py b/network/central-game-storage.py new file mode 100644 index 00000000..98fb3dce --- /dev/null +++ b/network/central-game-storage.py @@ -0,0 +1,37 @@ +"""Switch only the five planet Core DB sections, preserving every plugin JAR.""" +import pathlib,subprocess,yaml,json,re,urllib.parse,os,pwd +ROOT=pathlib.Path('/opt/dunerealms/servers') +NAMES=['arrakis','caladan','giedi_prime','kaitain','sigma_draconis_iv'] +def run(*args):return subprocess.run(args,check=True,text=True,capture_output=True).stdout.strip() +def main(): + for name in NAMES: + state=subprocess.run(['systemctl','is-active','dune-'+name+'.service'],capture_output=True,text=True).stdout.strip() + if state not in ('inactive','failed'):raise RuntimeError('Stop all planet writers first: '+name) + staging=pathlib.Path('/root/dune-db-reconcile');central=yaml.safe_load((staging/'central-core.yml').read_text())['database'] + uri=urllib.parse.urlparse(re.sub('^jdbc:','',central['jdbc-url'])) + assert uri.hostname=='127.0.0.1' and uri.port==13308 and uri.path=='/dunegameplay' + target={k:central[k] for k in ['jdbc-url','username','password']};target['jdbc-url']=target['jdbc-url'].replace(':13308/',':13307/') + patches=[] + for name in NAMES: + path=ROOT/name/'plugins/DuneCore/config.yml';assert path.is_file() and not path.is_symlink() + original=path.read_text();config=yaml.safe_load(original);assert ':13307/dunegameplay' in config['database']['jdbc-url'] + ess=yaml.safe_load((ROOT/name/'plugins/DuneEss/config.yml').read_text()) + if not ess.get('database',{}).get('use-core-database',True):raise ValueError('DuneEss must use Core storage: '+name) + changed=original + for k,v in target.items(): + pattern=r'(?m)^( '+re.escape(k)+r':)\s*[^\n]*$' + changed,n=re.subn(pattern,lambda m:m[1]+' '+json.dumps(v),changed);assert n==1,(name,k) + parsed=yaml.safe_load(changed);expected=json.loads(json.dumps(config));expected['database'].update(target);assert parsed==expected + patches.append((name,path,original,changed)) + # Keep one exact recovery copy privately; never restore it automatically. + uid=pwd.getpwnam('dune') + for name,path,original,changed in patches: + recovery=staging/(name+'-core-before.yml') + if recovery.exists():raise ValueError('This migration was already staged; inspect before retrying') + recovery.write_text(original);recovery.chmod(0o600) + tmp=path.with_name('config.yml.central-stage');tmp.write_text(changed);os.chown(tmp,uid.pw_uid,uid.pw_gid);tmp.chmod(path.stat().st_mode&0o777);tmp.replace(path) + drop=pathlib.Path('/etc/systemd/system/dune-db-tunnel.service.d/central.conf');drop.parent.mkdir(exist_ok=True) + drop.write_text('[Service]\nExecStart=\nExecStart=/usr/bin/ssh -NT -i /root/.ssh/dune-db-tunnel -o BatchMode=yes -o ExitOnForwardFailure=yes -o ServerAliveInterval=20 -o ServerAliveCountMax=3 -o StrictHostKeyChecking=yes -o UserKnownHostsFile=/root/.ssh/dune-central-known-hosts -L 127.0.0.1:13307:127.0.0.1:3306 dev@91.107.196.242\n') + run('systemctl','daemon-reload');run('systemctl','restart','dune-db-tunnel.service') + print(json.dumps({'configured':NAMES,'database':'central','pluginJars':'unchanged'})) +if __name__=='__main__':main() diff --git a/network/game-db-reconcile.py b/network/game-db-reconcile.py new file mode 100644 index 00000000..fe41031b --- /dev/null +++ b/network/game-db-reconcile.py @@ -0,0 +1,85 @@ +"""Reconcile the retired game DB into the central DB without merging item stacks. + +Run on the central host as DBA only after all six game writers are stopped. +Private source/central snapshots remain the recovery evidence, outside Git. +Central Exchange stock, operations, deliveries and every money table are untouched. +""" +import argparse,datetime,gzip,hashlib,json,pathlib,re,subprocess + +def digest(value): + return hashlib.sha256(json.dumps(value,separators=(',',':'),sort_keys=True).encode()).hexdigest() + +def index(table): + positions=[table['columns'].index(c) for c in table['pk']] + if not positions: raise ValueError('Missing primary key') + rows={tuple(r[i] for i in positions):r for r in table['rows']} + if len(rows)!=len(table['rows']):raise ValueError('Duplicate primary key') + return rows + +def plan(source,central): + if source['host']!='Debian-bookworm-latest-amd64-base' or central['host']!='ubuntu-4gb-fsn1-1':raise ValueError('Unexpected database identities') + additions={};schedule=None;conflicts=[] + for name,a in source['tables'].items(): + b=central['tables'].get(name) + if not b:raise ValueError('Missing central table: '+name) + if a['columns']!=b['columns']: + if name=='dune_office_kit_definitions' and not a['rows'] and not b['rows']:continue + raise ValueError('Schema conflict: '+name) + old,new=index(a),index(b) + only=[r for k,r in old.items() if k not in new] + different=[(k,r,new[k]) for k,r in old.items() if k in new and r!=new[k]] + if name=='dune_players': + slot=a['columns'].index('session_open') + if any(r[slot]!='0' for r in a['rows']+b['rows']):raise ValueError('A player session is still open') + additions[name]=only + # The central copy includes committed Exchange withdrawals. Never + # overwrite it with a newer timestamp from the disconnected branch. + conflicts=[{'playerHash':digest(k),'centralInventoryHash':digest(q),'retiredInventoryHash':digest(r),'retained':'central'} for k,r,q in different] + elif name in ('dune_bounties','dune_quest_events'): + if different:raise ValueError('Conflicting history: '+name) + additions[name]=only + elif name=='dune_quest_definitions': + if only or old.keys()!=new.keys():raise ValueError('Different quest definitions') + i=a['columns'].index('next_run_at') + schedule=[] + for k,r,q in different: + if r[:i]+r[i+1:]!=q[:i]+q[i+1:]:raise ValueError('Quest definition changed') + if int(r[i])>int(q[i]):schedule.append((k,r[i])) + elif name=='dune_exchange_listings': + # The retired copy can still contain an item already withdrawn from + # central stock. Every omission must have a matching central receipt. + ops=central['tables']['dune_exchange_inventory_ops'];records=[dict(zip(ops['columns'],r)) for r in ops['rows']] + for r in only: + listing=dict(zip(a['columns'],r)) + if not any(o['listing_id']==listing['id'] and o['actor_uuid']==listing['seller'] and o['kind']=='cancel' for o in records):raise ValueError('Unreconciled retired listing') + if different:raise ValueError('Exchange stock quantities differ') + elif only or different or old.keys()!=new.keys():raise ValueError('Unreconciled table: '+name) + return {'version':1,'sourceHash':digest(source),'centralHash':digest(central),'additions':additions,'schedule':schedule or [],'inventoryVariants':conflicts,'preserveCentralExchange':True} + +def literal(value): + if value is None:return 'NULL' + return "CONVERT(X'"+str(value).encode().hex()+"' USING utf8mb4)" + +def sql_for(p,source): + sql=['START TRANSACTION;'] + for name,rows in p['additions'].items(): + if not re.fullmatch('dune_[a-z_]+',name):raise ValueError('Invalid table') + columns=source['tables'][name]['columns'] + for row in rows:sql.append('INSERT INTO `'+name+'`('+','.join('`'+c+'`' for c in columns)+') VALUES('+','.join(literal(v) for v in row)+');') + for key,value in p['schedule']: + sql.append('UPDATE dune_quest_definitions SET next_run_at='+literal(value)+' WHERE quest_key='+literal(key[0])+' AND next_run_at<'+literal(value)+';') + sql.append('COMMIT;');return '\n'.join(sql) + +def main(): + ap=argparse.ArgumentParser();ap.add_argument('source');ap.add_argument('central');ap.add_argument('--apply-plan');args=ap.parse_args() + source=json.loads(gzip.decompress(pathlib.Path(args.source).read_bytes()));central=json.loads(gzip.decompress(pathlib.Path(args.central).read_bytes()));p=plan(source,central);fingerprint=digest(p) + if args.apply_plan: + if args.apply_plan!=fingerprint:raise ValueError('Plan changed') + # Caller must collect central snapshot immediately before this invocation. + age=datetime.datetime.now(datetime.timezone.utc)-datetime.datetime.fromisoformat(central['created']) + if age.total_seconds()>120:raise ValueError('Central snapshot is stale') + subprocess.run(['mysql','--batch','dunegameplay'],input=sql_for(p,source),text=True,check=True,capture_output=True) + receipt=pathlib.Path(args.central).with_name('reconciliation-receipt.json');receipt.write_text(json.dumps({'planHash':fingerprint,'completed':datetime.datetime.now(datetime.timezone.utc).isoformat(),**p},indent=2));receipt.chmod(0o600) + print(json.dumps({'planHash':fingerprint,'applied':bool(args.apply_plan),'insertCounts':{k:len(v) for k,v in p['additions'].items()},'inventoryVariantsRetained':len(p['inventoryVariants']),'exchange':'central-unchanged'})) + +if __name__=='__main__':main() diff --git a/network/test_game_db_reconcile.py b/network/test_game_db_reconcile.py new file mode 100644 index 00000000..ed0d8370 --- /dev/null +++ b/network/test_game_db_reconcile.py @@ -0,0 +1,21 @@ +import importlib.util,pathlib,unittest,copy +spec=importlib.util.spec_from_file_location('reconcile',pathlib.Path(__file__).with_name('game-db-reconcile.py'));m=importlib.util.module_from_spec(spec);spec.loader.exec_module(m) +def table(columns,rows):return {'columns':columns,'pk':[columns[0]],'rows':rows} +class ReconcileTest(unittest.TestCase): + def setUp(self): + self.a={'host':'Debian-bookworm-latest-amd64-base','tables':{'dune_players':table(['uuid','inventory','session_open'],[['u','retired','0']]),'dune_exchange_listings':table(['id','seller','payload'],[['1','u','shovel']])}} + self.b={'host':'ubuntu-4gb-fsn1-1','tables':{'dune_players':table(['uuid','inventory','session_open'],[['u','central-with-withdrawn-item','0']]),'dune_exchange_listings':table(['id','seller','payload'],[]),'dune_exchange_inventory_ops':table(['id','listing_id','actor_uuid','kind'],[['op','1','u','cancel']])}} + def test_committed_withdrawal_is_never_resurrected(self): + p=m.plan(self.a,self.b);self.assertEqual(p['additions']['dune_players'],[]);self.assertEqual(p['inventoryVariants'][0]['retained'],'central');self.assertNotIn('dune_exchange_listings',m.sql_for(p,self.a)) + def test_unexplained_stock_difference_denied(self): + self.b['tables']['dune_exchange_inventory_ops']['rows']=[] + with self.assertRaises(ValueError):m.plan(self.a,self.b) + def test_active_writer_denied(self): + self.a['tables']['dune_players']['rows'][0][2]='1' + with self.assertRaises(ValueError):m.plan(self.a,self.b) + def test_money_conflict_denied(self): + self.a['tables']['dune_economy_balances']=table(['uuid','amount'],[['u','9']]);self.b['tables']['dune_economy_balances']=table(['uuid','amount'],[['u','10']]) + with self.assertRaises(ValueError):m.plan(self.a,self.b) + def test_recovery_data_is_not_logged(self): + self.assertNotIn('central-with-withdrawn-item',str(m.plan(self.a,self.b))) +if __name__=='__main__':unittest.main()