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.
This commit is contained in:
1 parent
e82d0e0f0a
commit
987e52931f
6 files changed
+216
-18
No files matched your search
+117
-15
@@ -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()
|
||||
|
||||
Reference in new issue
Block a user