forked from unimatrix/web
87 lines
5.8 KiB
Python
87 lines
5.8 KiB
Python
"""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']:
|
|
# Legacy tables use general_ci while the new server defaults to 0900.
|
|
# Quest identifiers are exact ASCII keys; compare bytes, not collations.
|
|
sql.append('UPDATE dune_quest_definitions SET next_run_at='+literal(value)+' WHERE BINARY quest_key=BINARY '+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()
|

Staff