From 987e52931f59957d61ae232a3840902384153fba Mon Sep 17 00:00:00 2001 From: strsv Date: Sat, 7 Nov 2026 00:47:30 +0300 Subject: [PATCH] feat: cache HLTB search responses Store search results in hltb_cache (schema v8) with a 7-day TTL, cache misses too, prune rows older than 90 days, and add --cache-ttl, --no-cache and --clear-cache. --- docs/data-sources.md | 4 +- docs/schema.md | 16 +++++- tests/test_hltb.py | 59 +++++++++++++++++++ tools/db.py | 16 +++++- tools/fetch_hltb.py | 132 ++++++++++++++++++++++++++++++++++++++----- tools/schema.sql | 7 +++ 6 files changed, 216 insertions(+), 18 deletions(-) diff --git a/docs/data-sources.md b/docs/data-sources.md index 69a8193..a19c19b 100644 --- a/docs/data-sources.md +++ b/docs/data-sources.md @@ -128,7 +128,9 @@ GET https://store.steampowered.com/api/appdetails римские цифры, издания (`GOTY`, `HD`, `Classic`, `RHCP`), годы; при промахе пробуются варианты запроса с годом. HLTB не даёт официального API, поэтому интеграция может сломаться при изменениях сайта; без пакета остаётся оценка -по жанрам/тегам. +по жанрам/тегам. Ответы поиска кэшируются в `hltb_cache` на 7 дней (TTL +настраивается через `--cache-ttl`), чтобы повторные прогоны не создавали +лишних запросов. ## Обложки diff --git a/docs/schema.md b/docs/schema.md index 93c4f58..c056570 100644 --- a/docs/schema.md +++ b/docs/schema.md @@ -19,6 +19,7 @@ games ──< game_genres moods справочник профилей настроений (JSON внутри) reco_feedback оценки рекомендаций по настроениям +hltb_cache кэш ответов поиска HowLongToBeat по запросу schema_meta служебные ключи (версия схемы, дата импорта, SteamID, путь) game_fts FTS5-индекс: название, описание, теги v_library вью: игра + часы + установка + статус @@ -217,6 +218,19 @@ python tools/personal.py attr 1086940 play_with friend в разных настроениях. `dislike`/`ignore`/`played` исключают игру из этой подборки, `like` добавляет бонус играм с общими тегами. +### `hltb_cache` + +| Поле | Смысл | +|---|---| +| `query` | поисковый запрос к HowLongToBeat (нормализованный или с годом) | +| `fetched_at` | ISO-время получения ответа | +| `results` | JSON-массив найденных игр с полями `game_name`, `release_world`, `game_id`, `main_story`, `main_extra`, `completionist` | + +Кэш использует `tools/fetch_hltb.py`, чтобы повторные запуски и «повторить промахи» +не дёргали HLTB заново. Записи старше TTL (по умолчанию 7 дней) игнорируются, +старше 90 дней — удаляются при запуске; пустой массив — это тоже кэшированный +промах. Очистка: `--clear-cache`. + ### `schema_meta` | Поле | Смысл | @@ -225,7 +239,7 @@ python tools/personal.py attr 1086940 play_with friend | `value` | значение | `schema_version` управляет миграциями (`db.SCHEMA_VERSION` и `db.MIGRATIONS`). -Текущая версия — **4**. Миграции применяются при `db.init`; база с версией новее +Текущая версия — **8**. Миграции применяются при `db.init`; база с версией новее приложения отклоняется, чтобы старый код не повредил новые данные. ## Представление `v_library` diff --git a/tests/test_hltb.py b/tests/test_hltb.py index 4724841..9dbb62a 100644 --- a/tests/test_hltb.py +++ b/tests/test_hltb.py @@ -2,12 +2,15 @@ import os import sys +import tempfile import unittest +from datetime import datetime, timedelta, timezone from types import SimpleNamespace ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, os.path.join(ROOT, "tools")) +import db import fetch_hltb @@ -50,5 +53,61 @@ class HltbTests(unittest.TestCase): self.assertIsNone(fetch_hltb.positive(None)) +class HltbCacheTests(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.con = db.connect(os.path.join(self.tmp.name, "test.db")) + db.init(self.con) + self.addCleanup(self.con.close) + + def test_entry_roundtrip(self): + entry = SimpleNamespace( + game_name="Hades", release_world=2020, game_id=1, + main_story=20.5, main_extra=30.0, completionist=50.0, + extra_field="ignored") + data = fetch_hltb.entry_to_dict(entry) + self.assertNotIn("extra_field", data) + restored = fetch_hltb.entry_from_dict(data) + self.assertEqual(restored.game_name, "Hades") + self.assertEqual(restored.main_story, 20.5) + self.assertEqual(restored.game_id, 1) + + def test_cache_roundtrip(self): + entries = [{"game_name": "Hades", "release_world": 2020, "game_id": 1, + "main_story": 20.5, "main_extra": 30.0, "completionist": 50.0}] + fetch_hltb.cache_put(self.con, "hades", entries) + self.assertEqual(fetch_hltb.cache_get(self.con, "hades", 7), entries) + + def test_cache_miss_returns_none(self): + self.assertIsNone(fetch_hltb.cache_get(self.con, "unknown", 7)) + + def test_cache_expires(self): + old = (datetime.now(timezone.utc) - timedelta(days=10)).isoformat(timespec="seconds") + self.con.execute( + "INSERT INTO hltb_cache (query, fetched_at, results) VALUES (?, ?, ?)", + ("hades", old, "[]")) + self.con.commit() + self.assertIsNone(fetch_hltb.cache_get(self.con, "hades", 7)) + self.assertEqual(fetch_hltb.cache_get(self.con, "hades", 0), None) + + def test_cache_clear(self): + fetch_hltb.cache_put(self.con, "a", []) + fetch_hltb.cache_put(self.con, "b", []) + self.assertEqual(fetch_hltb.cache_clear(self.con), 2) + self.assertEqual(self.con.execute("SELECT COUNT(*) FROM hltb_cache").fetchone()[0], 0) + + def test_cache_prune_removes_old_rows(self): + old = (datetime.now(timezone.utc) - timedelta(days=120)).isoformat(timespec="seconds") + self.con.execute( + "INSERT INTO hltb_cache (query, fetched_at, results) VALUES (?, ?, ?)", + ("old", old, "[]")) + self.con.commit() + fetch_hltb.cache_put(self.con, "new", []) + self.assertEqual(fetch_hltb.cache_prune(self.con), 1) + rows = {r[0] for r in self.con.execute("SELECT query FROM hltb_cache")} + self.assertEqual(rows, {"new"}) + + if __name__ == "__main__": unittest.main() diff --git a/tools/db.py b/tools/db.py index 0d185ad..c940365 100644 --- a/tools/db.py +++ b/tools/db.py @@ -8,7 +8,7 @@ from datetime import datetime, timezone BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DEFAULT_DB = os.path.join(BASE_DIR, "steam.db") SCHEMA_PATH = os.path.join(BASE_DIR, "tools", "schema.sql") -SCHEMA_VERSION = 7 +SCHEMA_VERSION = 8 MOOD_PRESETS = { "adventure-rpg-party": { @@ -568,6 +568,19 @@ def _migration_7(con): _ensure_column(con, "games", "hltb_match", "INTEGER") +def _migration_8(con): + """Cache HowLongToBeat search responses by query.""" + con.execute(""" + CREATE TABLE IF NOT EXISTS hltb_cache ( + query TEXT PRIMARY KEY, + fetched_at TEXT NOT NULL, + results TEXT NOT NULL + ) + """) + con.execute("CREATE INDEX IF NOT EXISTS idx_hltb_cache_fetched " + "ON hltb_cache(fetched_at)") + + MIGRATIONS = { 1: _migration_1, 2: _migration_2, @@ -576,6 +589,7 @@ MIGRATIONS = { 5: _migration_5, 6: _migration_6, 7: _migration_7, + 8: _migration_8, } diff --git a/tools/fetch_hltb.py b/tools/fetch_hltb.py index 94304a0..9a15ece 100644 --- a/tools/fetch_hltb.py +++ b/tools/fetch_hltb.py @@ -13,11 +13,13 @@ games.hltb_* and the main story time becomes games.estimated_hours. import argparse import difflib +import json import os import re import sys import time -from datetime import datetime, timezone +from datetime import datetime, timedelta, timezone +from types import SimpleNamespace for stream in (sys.stdout, sys.stderr): try: @@ -94,6 +96,71 @@ def positive(value): return value if value > 0 else None +CACHE_TTL_DAYS = 7.0 +CACHE_RETENTION_DAYS = 90 +CACHE_FIELDS = ("game_name", "release_world", "game_id", + "main_story", "main_extra", "completionist") + + +def entry_to_dict(entry): + """Keep only the fields needed for matching and storage.""" + return {field: getattr(entry, field, None) for field in CACHE_FIELDS} + + +def entry_from_dict(data): + return SimpleNamespace(**{field: data.get(field) for field in CACHE_FIELDS}) + + +def cache_get(con, query, ttl_days): + """Return cached search entries, or None when missing or stale.""" + if ttl_days <= 0: + return None + row = con.execute("SELECT fetched_at, results FROM hltb_cache WHERE query = ?", + (query,)).fetchone() + if not row: + return None + try: + fetched = datetime.fromisoformat(row["fetched_at"]) + except (TypeError, ValueError): + return None + if fetched.tzinfo is None: + fetched = fetched.replace(tzinfo=timezone.utc) + age = (datetime.now(timezone.utc) - fetched).total_seconds() + if age > ttl_days * 86400: + return None + try: + data = json.loads(row["results"]) + except (TypeError, ValueError): + return None + if not isinstance(data, list): + return None + return data + + +def cache_put(con, query, entries): + now = datetime.now(timezone.utc).isoformat(timespec="seconds") + con.execute( + """INSERT INTO hltb_cache (query, fetched_at, results) VALUES (?, ?, ?) + ON CONFLICT(query) DO UPDATE SET fetched_at = excluded.fetched_at, + results = excluded.results""", + (query, now, json.dumps(entries, ensure_ascii=False))) + con.commit() + + +def cache_clear(con): + deleted = con.execute("DELETE FROM hltb_cache").rowcount + con.commit() + return deleted + + +def cache_prune(con, days=CACHE_RETENTION_DAYS): + cutoff = (datetime.now(timezone.utc) - timedelta(days=days)).isoformat(timespec="seconds") + deleted = con.execute("DELETE FROM hltb_cache WHERE fetched_at < ?", + (cutoff,)).rowcount + con.commit() + return deleted + + def main(): ap = argparse.ArgumentParser(description="Enrich games with HowLongToBeat times") ap.add_argument("--db", default=db.DEFAULT_DB) @@ -104,15 +171,33 @@ def main(): help="retry games that were checked without a match") ap.add_argument("--delay", type=float, default=0.5) ap.add_argument("--dry-run", action="store_true") + ap.add_argument("--cache-ttl", type=float, default=CACHE_TTL_DAYS, + help="days to reuse cached HLTB searches (0 disables)") + ap.add_argument("--no-cache", action="store_true", + help="do not read or write the HLTB query cache") + ap.add_argument("--clear-cache", action="store_true", + help="delete cached HLTB searches and exit") args = ap.parse_args() + con = db.connect(args.db) + db.init(con) + if args.clear_cache: + print(f"Cleared {cache_clear(con)} cached searches.") + con.close() + return 0 + + cache_enabled = not args.no_cache + if cache_enabled and not args.dry_run: + pruned = cache_prune(con) + if pruned: + print(f"Pruned {pruned} stale cached searches.") + if HowLongToBeat is None: print("howlongtobeatpy is not installed; run: pip install -r requirements-hltb.txt", file=sys.stderr) + con.close() return 1 - con = db.connect(args.db) - db.init(con) where = ["LOWER(type) = 'game'"] if not args.refresh: if args.retry_missed: @@ -127,26 +212,39 @@ def main(): print(f"To fetch: {len(rows)}") searcher = HowLongToBeat() - matched = missing = errors = 0 + matched = missing = errors = cached_hits = 0 for index, row in enumerate(rows, 1): release = str(row["release_date"] or "") year = int(release[:4]) if len(release) >= 4 and release[:4].isdigit() else None entry = None last_error = None + network_used = False for query in search_variants(row["name"], year): - try: - entries = searcher.search(query) - except Exception as exc: - last_error = exc - break + entries = None + if cache_enabled: + cached = cache_get(con, query, args.cache_ttl) + if cached is not None: + entries = [entry_from_dict(item) for item in cached] + cached_hits += 1 + if entries is None: + try: + raw = searcher.search(query) + except Exception as exc: + last_error = exc + break + network_used = True + entries = raw + if cache_enabled and not args.dry_run: + cache_put(con, query, [entry_to_dict(item) for item in raw]) + time.sleep(args.delay) entry = find_match(entries, row["name"], year) if entry: break - time.sleep(args.delay) if last_error is not None: errors += 1 print(f" {row['name']}: {last_error}") - time.sleep(args.delay) + if network_used: + time.sleep(args.delay) continue if not entry: missing += 1 @@ -157,7 +255,8 @@ def main(): hltb_match = CASE WHEN hltb_id IS NOT NULL THEN 1 ELSE 0 END WHERE appid = ?""", (now, row["appid"])) con.commit() - time.sleep(args.delay) + if network_used: + time.sleep(args.delay) if len(rows) <= 20: print(f" {row['name']}: не найдено") if index % 10 == 0 or index == len(rows) or len(rows) <= 20: @@ -177,7 +276,8 @@ def main(): hltb_match = CASE WHEN hltb_id IS NOT NULL THEN 1 ELSE 0 END WHERE appid = ?""", (now, row["appid"])) con.commit() - time.sleep(args.delay) + if network_used: + time.sleep(args.delay) if len(rows) <= 20: print(f" {row['name']}: нет времени") if len(rows) <= 20: @@ -197,9 +297,11 @@ def main(): print(f" {row['name']}: {best} ч") if index % 10 == 0 or index == len(rows) or len(rows) <= 20: print(f" {index}/{len(rows)} matched={matched} missing={missing} errors={errors}") - time.sleep(args.delay) + if network_used: + time.sleep(args.delay) - print(f"Done. matched={matched} missing={missing} errors={errors}") + print(f"Done. matched={matched} missing={missing} errors={errors} " + f"cached={cached_hits}") if args.dry_run: print("dry run: database was not changed") con.close() diff --git a/tools/schema.sql b/tools/schema.sql index b5713b0..bb4a903 100644 --- a/tools/schema.sql +++ b/tools/schema.sql @@ -113,6 +113,13 @@ CREATE TABLE IF NOT EXISTS moods ( updated_at TEXT ); +CREATE TABLE IF NOT EXISTS hltb_cache ( + query TEXT PRIMARY KEY, + fetched_at TEXT NOT NULL, + results TEXT NOT NULL +); +CREATE INDEX IF NOT EXISTS idx_hltb_cache_fetched ON hltb_cache(fetched_at); + CREATE VIRTUAL TABLE IF NOT EXISTS game_fts USING fts5( appid UNINDEXED, name,