Files

88 lines
3.9 KiB
Python

#!/usr/bin/env python3
"""LOCAL rolling full-row captures and an atomic addon data file. No SQL writes."""
import datetime
import gzip
import hashlib
import json
import os
import tempfile
import time
from pathlib import Path
import spawn_export
def atomic(path, data):
path=Path(path);path.parent.mkdir(parents=True,exist_ok=True)
fd,name=tempfile.mkstemp(prefix='.'+path.name+'.',dir=path.parent)
try:
with os.fdopen(fd,'wb') as out:out.write(data)
os.replace(name,path)
finally:
if os.path.exists(name):os.unlink(name)
def lua(value):
if value is None:return 'nil'
if isinstance(value,bool):return 'true' if value else 'false'
if isinstance(value,int):return str(value)
if isinstance(value,str):
# Lua 5.1 decimal escapes, including control bytes; database names are data.
out=''
for byte in value.encode('utf-8'):
if byte in (34,92) or byte<32 or byte==127:out+='\\%03d'%byte
else:out+=bytes([byte]).decode('latin1')
return '"'+out+'"'
if isinstance(value,list):return '{'+','.join(lua(x) for x in value)+'}'
if isinstance(value,dict):return '{'+','.join('['+lua(str(k))+']='+lua(v) for k,v in value.items())+'}'
raise ValueError('Unsupported addon capture value')
def catalog(reader=spawn_export.query):
result={}
for table,template in [('creature','creature_template'),('gameobject','gameobject_template')]:
rows={}
for line in reader('SELECT entry,HEX(name) FROM '+template+' ORDER BY entry;').splitlines():
ident,name=line.split('\t');
if not ident.isdigit():raise ValueError('Invalid template ID')
rows[ident]=bytes.fromhex(name).decode('utf-8')
result[table]=rows
return result
def capture(root, addon, session, character, names, snapshot=None):
root=Path(root);root.mkdir(parents=True,exist_ok=True)
data=spawn_export.snapshot() if snapshot is None else snapshot
spawn_export.validate(data)
stamp=datetime.datetime.fromisoformat(data['captured_utc']).timestamp()
if stamp<=0:raise ValueError('Invalid capture timestamp')
raw=json.dumps(data,separators=(',',':')).encode()
target=root/('capture-%020d.json.gz'%int(stamp*1000000))
with target.open('xb') as f:f.write(gzip.compress(raw,compresslevel=3,mtime=0))
payload={'format':1,'localOnly':True,'session':session,'character':character,
'captured':int(stamp),'capture_id':target.name,'catalog':names,'columns':{},'rows':{}}
for table in spawn_export.TABLES:
payload['columns'][table]=data['tables'][table]['columns']
payload['rows'][table]={guid:[v if v is not None else 'NULL' for v in values]
for guid,values in data['tables'][table]['rows'].items()}
atomic(Path(addon)/'Capture.lua',('OctoEditorCapture = '+lua(payload)+';\n').encode('latin1'))
atomic(root/'status.json',json.dumps({'healthy':True,'captured':int(stamp),'file':target.name,
'sha256':hashlib.sha256(raw).hexdigest()}).encode())
return data
def newest(root, table, guid, before, containing=True):
"""Newest completed capture at/before the operation; never invent a row."""
for path in sorted(Path(root).glob('capture-*.json.gz'),reverse=True):
data=json.loads(gzip.decompress(path.read_bytes()));spawn_export.validate(data)
stamp=datetime.datetime.fromisoformat(data['captured_utc']).timestamp()
if stamp>before:continue
if not containing or guid in data['tables'][table]['rows']:return data
raise ValueError('No pre-operation full-row snapshot; refusing undo')
def watch(root, addon, session, character, names, stop, interval=15):
while not stop.wait(interval):
try:capture(root,addon,session,character,names)
except Exception as exc:
atomic(Path(root)/'status.json',json.dumps({'healthy':False,'error':type(exc).__name__}).encode())