177 lines
8.2 KiB
Python
177 lines
8.2 KiB
Python
"""Plan shared tw_char.item_transmogs dependencies for an Octo character import."""
|
|
|
|
from collections import defaultdict
|
|
|
|
|
|
def item_id(value):
|
|
if isinstance(value, str) and value.isascii() and value.isdigit():
|
|
value = int(value)
|
|
if type(value) is not int or not 0 < value <= 0xffffffff:
|
|
raise ValueError('Expected a positive uint32 item or display ID')
|
|
return value
|
|
|
|
|
|
def referenced_bases(instances):
|
|
bases = defaultdict(set)
|
|
for item in instances:
|
|
serial = item.get('transmogrifyId', 0)
|
|
if serial not in (0, '0'):
|
|
bases[item_id(serial)].add(item_id(item['itemEntry']))
|
|
return bases
|
|
|
|
|
|
def registry_index(rows):
|
|
indexed = {}
|
|
for row in rows:
|
|
ident, base, display = (item_id(row[k]) for k in ('ID', 'ItemID', 'DisplayID'))
|
|
# Some older local rows explicitly recorded zero for an unknown source.
|
|
src = row['SourceID']
|
|
src = 0 if src in (0, '0') else item_id(src)
|
|
if src > 0x7fffffff:
|
|
raise ValueError('SourceID exceeds the signed registry column')
|
|
value = dict(ID=ident, ItemID=base, DisplayID=display, SourceID=src)
|
|
if ident in indexed and indexed[ident] != value:
|
|
raise ValueError(f'Conflicting registry rows for serial {ident}')
|
|
indexed[ident] = value
|
|
return indexed
|
|
|
|
|
|
def plan(instances, source_rows=(), target_rows=None, templates=None, cached_records=(),
|
|
target_instances=()):
|
|
"""Only an original registry tuple supplies SourceID. A cache observation can
|
|
verify or contradict its display. Target snapshots must cover all requested IDs.
|
|
"""
|
|
references = referenced_bases(instances)
|
|
carriers = referenced_bases(target_instances)
|
|
source = registry_index(source_rows)
|
|
local = registry_index(target_rows or ())
|
|
catalogue = {}
|
|
for template in templates or ():
|
|
entry, display = item_id(template['entry']), int(template['display_id'])
|
|
if entry in catalogue and catalogue[entry] != display:
|
|
raise ValueError(f'Conflicting local template displays for entry {entry}')
|
|
catalogue[entry] = display
|
|
observations = {}
|
|
for row in cached_records:
|
|
serial = item_id(row['entry'])
|
|
if serial in references:
|
|
display = item_id(row['display_id'])
|
|
if serial in observations and observations[serial] != display:
|
|
raise ValueError(f'Conflicting cached displays for serial {serial}')
|
|
observations[serial] = display
|
|
|
|
records, inserts = [], []
|
|
for serial, bases in sorted(references.items()):
|
|
original = source.get(serial)
|
|
current = local.get(serial)
|
|
observed = observations.get(serial)
|
|
record = dict(ID=serial, referenced_bases=sorted(bases))
|
|
if observed is not None:
|
|
record['cached_display_id'] = observed
|
|
if len(bases | carriers.get(serial, set())) != 1:
|
|
status = 'conflicting-instance-bases'
|
|
elif original and original['ItemID'] not in bases:
|
|
status = 'source-registry-base-conflict'
|
|
elif templates is None or target_rows is None:
|
|
status = 'target-snapshot-required'
|
|
elif serial in catalogue:
|
|
status = 'serial-collides-with-real-item'
|
|
elif not bases.issubset(catalogue):
|
|
status = 'missing-base-template'
|
|
elif current and current['ItemID'] not in bases:
|
|
status = 'local-registry-base-conflict'
|
|
elif not original:
|
|
if not current:
|
|
status = 'source-registry-required'
|
|
elif observed is None:
|
|
if current['SourceID'] == current['ItemID'] and current['DisplayID'] == catalogue[current['ItemID']]:
|
|
status = 'local-base-look-source-unverified'
|
|
else:
|
|
status = 'local-present-source-unverified'
|
|
elif current['DisplayID'] != observed:
|
|
status = 'local-display-conflicts-with-cache'
|
|
else:
|
|
status = 'local-display-matches-cache-source-unverified'
|
|
elif observed is not None and original['DisplayID'] != observed:
|
|
status = 'source-display-conflicts-with-cache'
|
|
elif not original['SourceID']:
|
|
status = 'source-item-id-unknown'
|
|
elif current and current != original:
|
|
status = 'local-registry-tuple-conflict'
|
|
elif original['SourceID'] not in catalogue:
|
|
status = 'missing-source-item-template'
|
|
elif catalogue[original['SourceID']] != original['DisplayID']:
|
|
status = 'local-source-display-differs'
|
|
elif current:
|
|
status = 'matching-registry-row'
|
|
else:
|
|
status = 'ready-to-insert'
|
|
inserts.append(original)
|
|
record['status'] = status
|
|
records.append(record)
|
|
return dict(records=records, insert_rows=inserts)
|
|
|
|
|
|
def from_export(data, snapshot=None):
|
|
if snapshot is None:
|
|
snapshot = {}
|
|
if not isinstance(snapshot, dict) or (snapshot and snapshot.get('kind') != 'octo-import-transmog-snapshot-v1'):
|
|
raise ValueError('Unrecognised transmog evidence snapshot')
|
|
cache = snapshot.get('cache')
|
|
if cache is not None and cache.get('kind') != 'installed-classic-item-cache-prefix':
|
|
raise ValueError('Expected item_template_snapshot cache records')
|
|
return plan(data.get('item_instance', []),
|
|
source_rows=[*data.get('item_transmogs', []), *snapshot.get('source_registry', [])],
|
|
target_rows=snapshot.get('target_registry') if 'target_instances' in snapshot else None,
|
|
templates=snapshot.get('templates'),
|
|
target_instances=snapshot.get('target_instances', []),
|
|
cached_records=cache['records'] if cache is not None else [])
|
|
|
|
|
|
def recovery_plan(data, evidence, query):
|
|
"""Read the exact global dependencies through the recovery importer's query function."""
|
|
needs = referenced_bases(data.get('item_instance', []))
|
|
if not needs:
|
|
return dict(records=[], insert_rows=[])
|
|
evidence = evidence or {}
|
|
source = registry_index([*data.get('item_transmogs', []), *evidence.get('source_registry', [])])
|
|
ids = set(needs)
|
|
for serial, bases in needs.items():
|
|
ids.update(bases)
|
|
if serial in source:
|
|
ids.add(source[serial]['SourceID'])
|
|
snapshot = dict(evidence, target_registry=[], templates=[], target_instances=[])
|
|
for values, sql, columns, dest in [
|
|
(needs, 'SELECT ID,ItemID,DisplayID,SourceID FROM tw_char.item_transmogs WHERE ID',
|
|
('ID', 'ItemID', 'DisplayID', 'SourceID'), 'target_registry'),
|
|
(needs, 'SELECT DISTINCT transmogrifyId,itemEntry FROM tw_char.item_instance WHERE transmogrifyId',
|
|
('transmogrifyId', 'itemEntry'), 'target_instances'),
|
|
(ids - {0}, 'SELECT entry,display_id FROM tw_world.item_template WHERE entry',
|
|
('entry', 'display_id'), 'templates'),
|
|
]:
|
|
values = sorted(values)
|
|
for pos in range(0, len(values), 1000):
|
|
chunk = ','.join(map(str, values[pos:pos + 1000]))
|
|
for row in query(f'{sql} IN ({chunk})'):
|
|
snapshot[dest].append(dict(zip(columns, map(int, row), strict=True)))
|
|
snapshot.setdefault('kind', 'octo-import-transmog-snapshot-v1')
|
|
return from_export(data, snapshot)
|
|
|
|
|
|
def insert_statement(row):
|
|
"""Serials are shared. Recheck the observations at write time and never overwrite an occupant."""
|
|
checked = registry_index([row])
|
|
serial, row = next(iter(checked.items()))
|
|
base, display, src = row['ItemID'], row['DisplayID'], row['SourceID']
|
|
if not src or serial in (base, src):
|
|
raise ValueError('Invalid source registry tuple')
|
|
return (
|
|
'INSERT INTO tw_char.item_transmogs (ID,ItemID,DisplayID,SourceID) '
|
|
f'SELECT {serial},{base},{display},{src} FROM DUAL '
|
|
f'WHERE EXISTS (SELECT 1 FROM tw_world.item_template WHERE entry={base}) '
|
|
f'AND EXISTS (SELECT 1 FROM tw_world.item_template WHERE entry={src} AND display_id={display}) '
|
|
f'AND NOT EXISTS (SELECT 1 FROM tw_world.item_template WHERE entry={serial}) '
|
|
f'AND NOT EXISTS (SELECT 1 FROM tw_char.item_instance WHERE transmogrifyId={serial} AND itemEntry<>{base}) '
|
|
'ON DUPLICATE KEY UPDATE ID=ID;'
|
|
)
|