From 97d5c32c3329af746e6cbef02a47e04282f0841b Mon Sep 17 00:00:00 2001 From: sol-aeternum Date: Thu, 3 Dec 2026 13:54:16 +1030 Subject: [PATCH 1/2] feat: add native Steam and GOG ID index --- README.md | 30 +++++++++ src/update_db.py | 114 +++++++++++++++++++++++++++++++++ tests/unit/test_update_db.py | 121 +++++++++++++++++++++++++++++++++++ 3 files changed, 265 insertions(+) diff --git a/README.md b/README.md index 4cc97b4e491e..7e235d516a99 100644 --- a/README.md +++ b/README.md @@ -45,6 +45,8 @@ The generated JSON files are published to the `gh-pages` branch and served at |-------------------|-------------------------------------------------------|------------------------------------------------------------------------------| | Buckets | Game name search index, split by first two characters | `https://app.lizardbyte.dev/GameDB/buckets/.json` | | Localized buckets | Optional regional game title search index | `https://app.lizardbyte.dev/GameDB/buckets/localized//.json` | +| Store ID index | Native Steam/GOG IDs to candidate game IDs | `https://app.lizardbyte.dev/GameDB/store-index/v1//.json` | +| Store index info | Version, shard algorithm and coverage counts | `https://app.lizardbyte.dev/GameDB/store-index/v1/manifest.json` | | Characters | Individual character details and all characters | `https://app.lizardbyte.dev/GameDB/characters/.json` | | Collections | Individual collection details and all collections | `https://app.lizardbyte.dev/GameDB/collections/.json` | | Franchises | Individual franchise details and all franchises | `https://app.lizardbyte.dev/GameDB/franchises/.json` | @@ -79,6 +81,34 @@ region's bucket and the original bucket, then deduplicate results by game ID. The existing game `name`, bucket URLs, and original bucket contents remain available without selecting a region. +### Optional native store ID index + +The reverse index uses the same IGDB external game links already returned for game records. It does not +search storefronts or infer IDs by title. + +- Read `store-index/v1/manifest.json` first. Version 1 reports `schema_version: 1`, + `shards_per_store: 256`, and `shard_algorithm: "uid-sha256-first-byte-hex"`. Each entry in `stores` + identifies its `external_game_source_id` and `uid_count` (number of distinct indexed native IDs). + Use the index only when the schema and shard algorithm are supported, `partial` is false + (test-mode builds are partial), and the desired store has a nonzero `uid_count`. +- Store names are `steam` (IGDB external game source 1, unsigned 32-bit app ID) and `gog` (source 5, + unsigned 64-bit product ID). IDs are positive decimal strings without leading zeroes. +- Each store has 256 two-digit lowercase hexadecimal shards (`00` through `ff`). Hash the + canonical decimal ID string (ASCII) with SHA-256 and format the first digest byte as two lowercase + hexadecimal digits. Steam app ID 400 (Portal) belongs to shard `26`. This avoids the even-shard + skew that a plain modulo rule would cause for Steam app IDs that are multiples of 10. +- Each shard maps native ID strings to **arrays** of game IDs, for example `{"400":[71]}`. A duplicate + store link can refer to more than one game record; ambiguity is preserved rather than overwritten. +- All shards, including empty objects, are published. A missing key is not evidence of identity + absence in the storefront; IGDB external link coverage is incomplete. A missing manifest/shard + or temporarily unavailable service should trigger the caller's normal fallback, not a permanent + negative cache. +- Recheck the native ID in every selected `games/.json` row and handle conflicting candidates + explicitly. The index is a candidate locator, not a permission to merge metadata blindly. + +Epic is not indexed here because Epic offer IDs cannot be assumed to be the same as a library +client's Legendary artifact or catalog item IDs. + ## Development Code contributors can use the [Developer Setup](docs/developerSetup.md) guide. diff --git a/src/update_db.py b/src/update_db.py index bcdfee8edb5a..9fe6ee0d52d4 100644 --- a/src/update_db.py +++ b/src/update_db.py @@ -1,6 +1,7 @@ # standard imports import argparse from datetime import timedelta +import hashlib import pathlib import json import os @@ -391,6 +392,117 @@ def _build_localized_buckets(full_dict: dict) -> dict: return buckets +# IGDB external_game_source IDs (not display names). Epic is deliberately +# excluded: its offer IDs are not the artifact/catalog-item IDs used by some +# desktop library clients. +STORE_INDEX_SOURCES = {1: ('steam', 2**32 - 1), 5: ('gog', 2**64 - 1)} +STORE_INDEX_SHARDS = 256 +STORE_INDEX_ALGORITHM = 'uid-sha256-first-byte-hex' + + +def _store_id_shard(uid: str) -> str: + """ + Select a shard using the first byte of the SHA-256 digest. + + Parameters + ---------- + uid : str + Validated canonical decimal native store ID, encoded as ASCII. + + Returns + ------- + str + Two-digit lowercase hexadecimal shard name. + """ + return f'{hashlib.sha256(uid.encode("ascii")).digest()[0]:02x}' + + +def _build_store_id_index(full_dict: dict) -> dict: + """ + Reverse native store IDs from already fetched IGDB game records. + + Keep every matching game ID, deduplicate repeated external links, and + validate native numeric IDs before indexing. No new network calls. + + Parameters + ---------- + full_dict : dict + Combined IGDB data keyed by endpoint name. + + Returns + ------- + dict + Store name to shard name to native ID and sorted candidate game IDs. + """ + indexes = {store: {} for store, _ in STORE_INDEX_SOURCES.values()} + for game_id, game_data in full_dict['games'].items(): + if type(game_id) is not int or not 0 < game_id < 2**64: + continue + if (not isinstance(game_data, dict) or type(game_data.get('id')) is not int + or game_data['id'] != game_id): + continue + links = game_data.get('external_games') + if not isinstance(links, list): + continue + + for link in links: + if not isinstance(link, dict): + continue + source = link.get('external_game_source') + source_id = source.get('id') if isinstance(source, dict) else None + if type(source_id) is not int or source_id not in STORE_INDEX_SOURCES: + continue + store, maximum = STORE_INDEX_SOURCES[source_id] + uid = link.get('uid') + if not isinstance(uid, str) or not re.fullmatch(r'[1-9][0-9]{0,19}', uid): + continue + numeric_id = int(uid) + if numeric_id > maximum: + continue + shard = _store_id_shard(uid) + indexes[store].setdefault(shard, {}).setdefault(uid, set()).add(game_id) + + return { + store: { + shard: {uid: sorted(ids) for uid, ids in sorted(entries.items(), key=lambda entry: int(entry[0]))} + for shard, entries in sorted(shards.items()) + } + for store, shards in indexes.items() + } + + +def _write_store_id_index(full_dict: dict): + """ + Publish all fixed shards, including empty ones, and a schema manifest. + + Parameters + ---------- + full_dict : dict + Combined IGDB data keyed by endpoint name. + """ + indexes = _build_store_id_index(full_dict) + index_dir = os.path.join(args.out_dir, 'store-index', 'v1') + for store, shards in indexes.items(): + for i in range(STORE_INDEX_SHARDS): + shard = f'{i:02x}' + write_json_files(file_path=os.path.join(index_dir, store, shard), data=shards.get(shard, {})) + + manifest = { + 'schema_version': 1, + 'shards_per_store': STORE_INDEX_SHARDS, + 'shard_algorithm': STORE_INDEX_ALGORITHM, + 'partial': args.test_mode, + 'stores': { + store: { + 'external_game_source_id': source_id, + 'uid_count': sum(len(entries) for entries in indexes[store].values()), + } + for source_id, (store, _) in STORE_INDEX_SOURCES.items() + }, + } + write_json_files(file_path=os.path.join(index_dir, 'manifest'), data=manifest) + + def _resolve_video_groups(all_videos: list, cache_file: str, group_size: int) -> list: """ Resolve the list of video groups, using and updating the cache file. @@ -656,6 +768,8 @@ def get_data(): file_path = os.path.join(args.out_dir, 'buckets', 'localized', region, bucket) write_json_files(file_path=file_path, data=bucket_data) + _write_store_id_index(full_dict) + all_videos.sort() all_video_groups = _resolve_video_groups( all_videos=all_videos, diff --git a/tests/unit/test_update_db.py b/tests/unit/test_update_db.py index 2fdd8d8d4cee..e7b75ddd26f4 100644 --- a/tests/unit/test_update_db.py +++ b/tests/unit/test_update_db.py @@ -347,11 +347,129 @@ def test_build_localized_buckets_skips_incomplete_or_unsafe_entries(): assert udb._build_localized_buckets(full_dict) == {'jp': {'@': {1: {'name': '!!!'}}}} +@pytest.mark.parametrize(('uid', 'shard'), [ + ('1', '6b'), + ('10', '4a'), + ('20', 'f5'), + ('30', '62'), + ('40', 'd5'), + ('50', '1a'), + ('60', '39'), + ('70', 'ff'), + ('80', '48'), + ('90', '69'), + ('100', 'ad'), + ('400', '26'), + ('5560', '26'), + ('1207664643', '78'), + ('4294967295', 'f8'), + ('18446744073709551615', '2c'), +]) +def test_store_id_shard_known_sha256_vectors(uid, shard): + assert udb._store_id_shard(uid) == shard + + +def test_store_id_index_keeps_duplicates_and_ignores_untrusted_ids(): + def link(source_id, uid): + return {'external_game_source': {'id': source_id}, 'uid': uid} + + full_dict = {'games': { + 71: {'id': 71, 'external_games': [ + link(1, '400'), link(1, '400'), link(1, '656'), link(5, '1207664643'), + link(1, '0'), link(1, '0400'), link(1, '400'), link(1, '../400'), + link(1, '4294967295'), link(5, '18446744073709551615'), + link(1, '4294967296'), link(5, '18446744073709551616'), link(26, '400'), + link(True, '400'), link('1', '400'), link(1, 400), link(1, '-1'), + link(1, '400 '), {'external_game_source': 1, 'uid': '400'}, None, {}, + ]}, + 7: {'id': 7, 'external_games': [link(1, '400'), link(5, '1207664643')]}, + 99: {'id': 99, 'external_games': None}, + 0: {'id': 0, 'external_games': [link(1, '400')]}, + 1: {'id': True, 'external_games': [link(1, '400')]}, + 100: {'id': 101, 'external_games': [link(1, '400')]}, + '71': {'id': 71, 'external_games': [link(1, '400')]}, + 102: None, + 103: {'id': 103, 'external_games': {'id': 1}}, + }} + index = udb._build_store_id_index(full_dict) + assert index == { + 'steam': { + '26': {'400': [7, 71]}, + 'd6': {'656': [71]}, + 'f8': {'4294967295': [71]}, + }, + 'gog': { + '78': {'1207664643': [7, 71]}, + '2c': {'18446744073709551615': [71]}, + }, + } + + +@pytest.mark.parametrize('test_mode', [False, True]) +def test_write_store_id_index_includes_manifest_empty_shards_and_collisions(tmp_path, monkeypatch, test_mode): + monkeypatch.setattr(udb, 'args', _make_args(tmp_path, test_mode=test_mode)) + full_dict = {'games': { + 71: {'id': 71, 'external_games': [ + {'external_game_source': {'id': 1}, 'uid': '400'}, + {'external_game_source': {'id': 1}, 'uid': '5560'}, + ]}, + 7: {'id': 7, 'external_games': [{'external_game_source': {'id': 1}, 'uid': '400'}]}, + 99: {'id': 99, 'name': 'No native link'}, + }} + udb._write_store_id_index(full_dict) + root = tmp_path / 'out' / 'store-index' / 'v1' + manifest = json.loads((root / 'manifest.json').read_text()) + assert manifest == { + 'schema_version': 1, + 'shards_per_store': 256, + 'shard_algorithm': 'uid-sha256-first-byte-hex', + 'partial': test_mode, + 'stores': { + 'steam': {'external_game_source_id': 1, 'uid_count': 2}, + 'gog': {'external_game_source_id': 5, 'uid_count': 0}, + }, + } + assert len(list((root / 'steam').glob('*.json'))) == 256 + assert len(list((root / 'gog').glob('*.json'))) == 256 + # Two games claim UID 400, and UID 5560 shares its SHA-256 first byte. + assert json.loads((root / 'steam' / '26.json').read_text()) == {'400': [7, 71], '5560': [71]} + assert json.loads((root / 'steam' / '00.json').read_text()) == {} + assert json.loads((root / 'gog' / '26.json').read_text()) == {} + + +def test_store_id_index_is_deterministic_and_replaces_stale_shards(tmp_path, monkeypatch): + monkeypatch.setattr(udb, 'args', _make_args(tmp_path)) + links = [ + {'external_game_source': {'id': 1}, 'uid': '5560'}, + {'external_game_source': {'id': 1}, 'uid': '400'}, + {'external_game_source': {'id': 1}, 'uid': '400'}, + ] + games = {71: {'id': 71, 'external_games': links}, 7: {'id': 7, 'external_games': links[:1]}} + udb._write_store_id_index({'games': games}) + root = tmp_path / 'out' / 'store-index' / 'v1' + shard = root / 'steam' / '26.json' + initial = {file.relative_to(root): file.read_bytes() for file in root.rglob('*.json')} + assert json.loads(initial[shard.relative_to(root)]) == {'400': [71], '5560': [7, 71]} + + reversed_games = { + game_id: {**game, 'external_games': list(reversed(game['external_games']))} + for game_id, game in reversed(games.items()) + } + udb._write_store_id_index({'games': reversed_games}) + assert initial == {file.relative_to(root): file.read_bytes() for file in root.rglob('*.json')} + + udb._write_store_id_index({'games': {}}) + assert json.loads(shard.read_text()) == {} + manifest = json.loads((root / 'manifest.json').read_text()) + assert manifest['stores']['steam']['uid_count'] == 0 + + def test_get_data_writes_localized_buckets_without_changing_legacy_files(tmp_path, monkeypatch): monkeypatch.setattr(udb, 'args', _make_args(tmp_path)) game = { 'id': 1, 'name': 'The Legend', + 'external_games': [{'external_game_source': {'id': 1}, 'uid': '400'}], 'cover': {'url': '//images.igdb.com/igdb/image/upload/t_thumb/original.jpg'}, 'game_localizations': [{ 'name': 'ゼルダの伝説', @@ -366,6 +484,7 @@ def test_get_data_writes_localized_buckets_without_changing_legacy_files(tmp_pat patch('src.update_db._resolve_video_groups', return_value=[]): udb.get_data() + assert fetch.call_count == 1 fields = fetch.call_args.kwargs['request_dict']['games']['fields'] assert 'game_localizations.cover.url' in fields assert 'game_localizations.name' in fields @@ -376,10 +495,12 @@ def test_get_data_writes_localized_buckets_without_changing_legacy_files(tmp_pat assert json.loads((output / 'buckets' / 'localized' / 'jp' / 'ゼル.json').read_text()) == { '1': {'name': 'ゼルダの伝説'}, } + assert json.loads((output / 'store-index' / 'v1' / 'steam' / '26.json').read_text()) == {'400': [1]} written_game = json.loads((output / 'games' / '1.json').read_text()) assert written_game['name'] == 'The Legend' assert written_game['cover'] == game['cover'] assert written_game['game_localizations'] == game['game_localizations'] + assert written_game['external_games'] == game['external_games'] def test_resolve_video_groups_no_cache(tmp_path): From 93724fbbfd9dbd64107f2404d489f9b654b0e4e5 Mon Sep 17 00:00:00 2001 From: sol-aeternum <98868588+sol-aeternum@users.noreply.github.com> Date: Thu, 3 Dec 2026 14:11:46 +1030 Subject: [PATCH 2/2] refactor: simplify native store ID index validation Separate game record and external link validation from index construction. Keep the decimal UID expression ASCII-only when using the digit shorthand, and cover mixed ASCII/non-ASCII input. --- src/update_db.py | 82 ++++++++++++++++++++++++++---------- tests/unit/test_update_db.py | 1 + 2 files changed, 61 insertions(+), 22 deletions(-) diff --git a/src/update_db.py b/src/update_db.py index 9fe6ee0d52d4..d4b58fd1b49b 100644 --- a/src/update_db.py +++ b/src/update_db.py @@ -417,6 +417,62 @@ def _store_id_shard(uid: str) -> str: return f'{hashlib.sha256(uid.encode("ascii")).digest()[0]:02x}' +def _game_external_links(game_id: object, game_data: object) -> list: + """ + Return external links for a game with a consistent positive integer ID. + + Parameters + ---------- + game_id : object + Game ID used as the key in the games dictionary. + game_data : object + Corresponding game record. + + Returns + ------- + list + External links, or an empty list for an invalid record. + """ + if type(game_id) is not int or not 0 < game_id < 2**64: + return [] + if (not isinstance(game_data, dict) or type(game_data.get('id')) is not int + or game_data['id'] != game_id): + return [] + links = game_data.get('external_games') + return links if isinstance(links, list) else [] + + +def _native_store_identity(link: object) -> tuple[str, str] | None: + """ + Validate an external link's source and canonical numeric UID. + + Parameters + ---------- + link : object + An IGDB external game link. + + Returns + ------- + tuple[str, str] or None + Store name and native UID for a supported valid link, otherwise None. + """ + if not isinstance(link, dict): + return None + source = link.get('external_game_source') + source_id = source.get('id') if isinstance(source, dict) else None + if type(source_id) is not int or source_id not in STORE_INDEX_SOURCES: + return None + store, maximum = STORE_INDEX_SOURCES[source_id] + uid = link.get('uid') + # ASCII is required because Python's Unicode \d also matches non-ASCII + # decimal digits, which must not enter the canonical UID or shard hash. + if not isinstance(uid, str) or not re.fullmatch(r'[1-9]\d{0,19}', uid, flags=re.ASCII): + return None + if int(uid) > maximum: + return None + return store, uid + + def _build_store_id_index(full_dict: dict) -> dict: """ Reverse native store IDs from already fetched IGDB game records. @@ -436,29 +492,11 @@ def _build_store_id_index(full_dict: dict) -> dict: """ indexes = {store: {} for store, _ in STORE_INDEX_SOURCES.values()} for game_id, game_data in full_dict['games'].items(): - if type(game_id) is not int or not 0 < game_id < 2**64: - continue - if (not isinstance(game_data, dict) or type(game_data.get('id')) is not int - or game_data['id'] != game_id): - continue - links = game_data.get('external_games') - if not isinstance(links, list): - continue - - for link in links: - if not isinstance(link, dict): - continue - source = link.get('external_game_source') - source_id = source.get('id') if isinstance(source, dict) else None - if type(source_id) is not int or source_id not in STORE_INDEX_SOURCES: - continue - store, maximum = STORE_INDEX_SOURCES[source_id] - uid = link.get('uid') - if not isinstance(uid, str) or not re.fullmatch(r'[1-9][0-9]{0,19}', uid): - continue - numeric_id = int(uid) - if numeric_id > maximum: + for link in _game_external_links(game_id, game_data): + identity = _native_store_identity(link) + if identity is None: continue + store, uid = identity shard = _store_id_shard(uid) indexes[store].setdefault(shard, {}).setdefault(uid, set()).add(game_id) diff --git a/tests/unit/test_update_db.py b/tests/unit/test_update_db.py index e7b75ddd26f4..0fd7a561065c 100644 --- a/tests/unit/test_update_db.py +++ b/tests/unit/test_update_db.py @@ -377,6 +377,7 @@ def link(source_id, uid): 71: {'id': 71, 'external_games': [ link(1, '400'), link(1, '400'), link(1, '656'), link(5, '1207664643'), link(1, '0'), link(1, '0400'), link(1, '400'), link(1, '../400'), + link(1, '400'), link(5, '4٠٠'), # Unicode digits after an ASCII first digit are invalid too. link(1, '4294967295'), link(5, '18446744073709551615'), link(1, '4294967296'), link(5, '18446744073709551616'), link(26, '400'), link(True, '400'), link('1', '400'), link(1, 400), link(1, '-1'),