cache.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. """Implementation of caching solutions.
  2. - :py:obj:`searx.cache.ExpireCache` and its :py:obj:`searx.cache.ExpireCacheCfg`
  3. ----
  4. """
  5. from __future__ import annotations
  6. __all__ = ["ExpireCacheCfg", "ExpireCacheStats", "ExpireCache", "ExpireCacheSQLite"]
  7. import abc
  8. import dataclasses
  9. import datetime
  10. import hashlib
  11. import hmac
  12. import os
  13. import pickle
  14. import sqlite3
  15. import string
  16. import tempfile
  17. import time
  18. import typing
  19. import msgspec
  20. from searx import sqlitedb
  21. from searx import logger
  22. from searx import get_setting
  23. log = logger.getChild("cache")
  24. class ExpireCacheCfg(msgspec.Struct): # pylint: disable=too-few-public-methods
  25. """Configuration of a :py:obj:`ExpireCache` cache."""
  26. name: str
  27. """Name of the cache."""
  28. db_url: str = ""
  29. """URL of the SQLite DB, the path to the database file. If unset a default
  30. DB will be created in `/tmp/sxng_cache_{self.name}.db`"""
  31. MAX_VALUE_LEN: int = 1024 * 10
  32. """Max lenght of a *serialized* value."""
  33. MAXHOLD_TIME: int = 60 * 60 * 24 * 7 # 7 days
  34. """Hold time (default in sec.), after which a value is removed from the cache."""
  35. MAINTENANCE_PERIOD: int = 60 * 60 # 2h
  36. """Maintenance period in seconds / when :py:obj:`MAINTENANCE_MODE` is set to
  37. ``auto``."""
  38. MAINTENANCE_MODE: typing.Literal["auto", "off"] = "auto"
  39. """Type of maintenance mode
  40. ``auto``:
  41. Maintenance is carried out automatically as part of the maintenance
  42. intervals (:py:obj:`MAINTENANCE_PERIOD`); no external process is required.
  43. ``off``:
  44. Maintenance is switched off and must be carried out by an external process
  45. if required.
  46. """
  47. password: bytes = get_setting("server.secret_key").encode() # type: ignore
  48. """Password used by :py:obj:`ExpireCache.secret_hash`.
  49. The default password is taken from :ref:`secret_key <server.secret_key>`.
  50. When the password is changed, the hashed keys in the cache can no longer be
  51. used, which is why all values in the cache are deleted when the password is
  52. changed.
  53. """
  54. def __post_init__(self):
  55. # if db_url is unset, use a default DB in /tmp/sxng_cache_{name}.db
  56. if not self.db_url:
  57. self.db_url = tempfile.gettempdir() + os.sep + f"sxng_cache_{ExpireCache.normalize_name(self.name)}.db"
  58. @dataclasses.dataclass
  59. class ExpireCacheStats:
  60. """Dataclass wich provides information on the status of the cache."""
  61. cached_items: dict[str, list[tuple[str, typing.Any, int]]]
  62. """Values in the cache mapped by table name.
  63. .. code: python
  64. {
  65. "table name": [
  66. ("foo key": "foo value", <expire>),
  67. ("bar key": "bar value", <expire>),
  68. # ...
  69. ],
  70. # ...
  71. }
  72. """
  73. def report(self):
  74. c_tables = 0
  75. c_kv = 0
  76. lines = []
  77. for table_name, kv_list in self.cached_items.items():
  78. c_tables += 1
  79. if not kv_list:
  80. lines.append(f"[{table_name:20s}] empty")
  81. continue
  82. for key, value, expire in kv_list:
  83. valid_until = datetime.datetime.fromtimestamp(expire).strftime("%Y-%m-%d %H:%M:%S")
  84. c_kv += 1
  85. lines.append(f"[{table_name:20s}] {valid_until} {key:12}" f" --> ({type(value).__name__}) {value} ")
  86. lines.append(f"number of tables: {c_tables}")
  87. lines.append(f"number of key/value pairs: {c_kv}")
  88. return "\n".join(lines)
  89. class ExpireCache(abc.ABC):
  90. """Abstract base class for the implementation of a key/value cache
  91. with expire date."""
  92. cfg: ExpireCacheCfg
  93. hash_token = "hash_token"
  94. @abc.abstractmethod
  95. def set(self, key: str, value: typing.Any, expire: int | None) -> bool:
  96. """Set *key* to *value*. To set a timeout on key use argument
  97. ``expire`` (in sec.). If expire is unset the default is taken from
  98. :py:obj:`ExpireCacheCfg.MAXHOLD_TIME`. After the timeout has expired,
  99. the key will automatically be deleted.
  100. """
  101. @abc.abstractmethod
  102. def get(self, key: str, default=None) -> typing.Any:
  103. """Return *value* of *key*. If key is unset, ``None`` is returned."""
  104. @abc.abstractmethod
  105. def maintenance(self, force: bool = False, truncate: bool = False) -> bool:
  106. """Performs maintenance on the cache.
  107. ``force``:
  108. Maintenance should be carried out even if the maintenance interval has
  109. not yet been reached.
  110. ``truncate``:
  111. Truncate the entire cache, which is necessary, for example, if the
  112. password has changed.
  113. """
  114. @abc.abstractmethod
  115. def state(self) -> ExpireCacheStats:
  116. """Returns a :py:obj:`ExpireCacheStats`, which provides information
  117. about the status of the cache."""
  118. @staticmethod
  119. def build_cache(cfg: ExpireCacheCfg) -> ExpireCache:
  120. """Factory to build a caching instance.
  121. .. note::
  122. Currently, only the SQLite adapter is available, but other database
  123. types could be implemented in the future, e.g. a Valkey (Redis)
  124. adapter.
  125. """
  126. return ExpireCacheSQLite(cfg)
  127. @staticmethod
  128. def normalize_name(name: str) -> str:
  129. """Returns a normalized name that can be used as a file name or as a SQL
  130. table name."""
  131. _valid = "-_." + string.ascii_letters + string.digits
  132. return "".join([c for c in name if c in _valid])
  133. def serialize(self, value: typing.Any) -> bytes:
  134. dump: bytes = pickle.dumps(value)
  135. return dump
  136. def deserialize(self, value: bytes) -> typing.Any:
  137. obj = pickle.loads(value)
  138. return obj
  139. def secret_hash(self, name: str | bytes) -> str:
  140. """Creates a hash of the argument ``name``. The hash value is formed
  141. from the ``name`` combined with the :py:obj:`password
  142. <ExpireCacheCfg.password>`. Can be used, for example, to make the
  143. ``key`` stored in the DB unreadable for third parties."""
  144. if isinstance(name, str):
  145. name = bytes(name, encoding='utf-8')
  146. m = hmac.new(name + self.cfg.password, digestmod='sha256')
  147. return m.hexdigest()
  148. class ExpireCacheSQLite(sqlitedb.SQLiteAppl, ExpireCache):
  149. """Cache that manages key/value pairs in a SQLite DB. The DB model in the
  150. SQLite DB is implemented in abstract class :py:obj:`SQLiteAppl
  151. <searx.sqlitedb.SQLiteAppl>`.
  152. The following configurations are required / supported:
  153. - :py:obj:`ExpireCacheCfg.db_url`
  154. - :py:obj:`ExpireCacheCfg.MAXHOLD_TIME`
  155. - :py:obj:`ExpireCacheCfg.MAINTENANCE_PERIOD`
  156. - :py:obj:`ExpireCacheCfg.MAINTENANCE_MODE`
  157. """
  158. DB_SCHEMA = 1
  159. # The key/value tables will be created on demand by self.create_table
  160. DDL_CREATE_TABLES = {}
  161. CACHE_TABLE_PREFIX = "CACHE-TABLE-"
  162. def __init__(self, cfg: ExpireCacheCfg):
  163. """An instance of the SQLite expire cache is build up from a
  164. :py:obj:`config <ExpireCacheCfg>`."""
  165. self.cfg = cfg
  166. if cfg.db_url == ":memory:":
  167. log.critical("don't use SQLite DB in :memory: in production!!")
  168. super().__init__(cfg.db_url)
  169. def init(self, conn: sqlite3.Connection) -> bool:
  170. ret_val = super().init(conn)
  171. if not ret_val:
  172. return False
  173. new = hashlib.sha256(self.cfg.password).hexdigest()
  174. old = self.properties(self.hash_token)
  175. if old != new:
  176. if old is not None:
  177. log.warning("[%s] hash token changed: truncate all cache tables", self.cfg.name)
  178. self.maintenance(force=True, truncate=True)
  179. self.properties.set(self.hash_token, new)
  180. return True
  181. def maintenance(self, force: bool = False, truncate: bool = False) -> bool:
  182. if not force and int(time.time()) < self.next_maintenance_time:
  183. # log.debug("no maintenance required yet, next maintenance interval is in the future")
  184. return False
  185. # Prevent parallel DB maintenance cycles from other DB connections
  186. # (e.g. in multi thread or process environments).
  187. self.properties.set("LAST_MAINTENANCE", "") # hint: this (also) sets the m_time of the property!
  188. if truncate:
  189. self.truncate_tables(self.table_names)
  190. return True
  191. # drop items by expire time stamp ..
  192. expire = int(time.time())
  193. with self.connect() as conn:
  194. for table in self.table_names:
  195. res = conn.execute(f"DELETE FROM {table} WHERE expire < ?", (expire,))
  196. log.debug("deleted %s keys from table %s (expire date reached)", res.rowcount, table)
  197. # Vacuuming the WALs
  198. # https://www.theunterminatedstring.com/sqlite-vacuuming/
  199. conn.execute("PRAGMA wal_checkpoint(TRUNCATE)")
  200. conn.close()
  201. return True
  202. def create_table(self, table: str) -> bool:
  203. """Create DB ``table`` if it has not yet been created, no recreates are
  204. initiated if the table already exists.
  205. """
  206. if table in self.table_names:
  207. # log.debug("key/value table %s exists in DB (no need to recreate)", table)
  208. return False
  209. log.info("key/value table '%s' NOT exists in DB -> create DB table ..", table)
  210. sql_table = "\n".join(
  211. [
  212. f"CREATE TABLE IF NOT EXISTS {table} (",
  213. " key TEXT,",
  214. " value BLOB,",
  215. f" expire INTEGER DEFAULT (strftime('%s', 'now') + {self.cfg.MAXHOLD_TIME}),",
  216. "PRIMARY KEY (key))",
  217. ]
  218. )
  219. sql_index = f"CREATE INDEX IF NOT EXISTS index_expire_{table} ON {table}(expire);"
  220. with self.connect() as conn:
  221. conn.execute(sql_table)
  222. conn.execute(sql_index)
  223. conn.close()
  224. self.properties.set(f"{self.CACHE_TABLE_PREFIX}-{table}", table)
  225. return True
  226. @property
  227. def table_names(self) -> list[str]:
  228. """List of key/value tables already created in the DB."""
  229. sql = f"SELECT value FROM properties WHERE name LIKE '{self.CACHE_TABLE_PREFIX}%%'"
  230. rows = self.DB.execute(sql).fetchall() or []
  231. return [r[0] for r in rows]
  232. def truncate_tables(self, table_names: list[str]):
  233. log.debug("truncate table: %s", ",".join(table_names))
  234. with self.connect() as conn:
  235. for table in table_names:
  236. conn.execute(f"DELETE FROM {table}")
  237. conn.close()
  238. return True
  239. @property
  240. def next_maintenance_time(self) -> int:
  241. """Returns (unix epoch) time of the next maintenance."""
  242. return self.cfg.MAINTENANCE_PERIOD + self.properties.m_time("LAST_MAINTENANCE", int(time.time()))
  243. # implement ABC methods of ExpireCache
  244. def set(self, key: str, value: typing.Any, expire: int | None, table: str | None = None) -> bool:
  245. """Set key/value in ``table``. If expire is unset the default is taken
  246. from :py:obj:`ExpireCacheCfg.MAXHOLD_TIME`. If ``table`` argument is
  247. ``None`` (the default), a table name is generated from the
  248. :py:obj:`ExpireCacheCfg.name`. If DB ``table`` does not exists, it will be
  249. created (on demand) by :py:obj:`self.create_table
  250. <ExpireCacheSQLite.create_table>`.
  251. """
  252. self.maintenance()
  253. value = self.serialize(value=value)
  254. if len(value) > self.cfg.MAX_VALUE_LEN:
  255. log.warning("ExpireCache.set(): %s.key='%s' - value too big to cache (len: %s) ", table, value, len(value))
  256. return False
  257. if not expire:
  258. expire = self.cfg.MAXHOLD_TIME
  259. expire = int(time.time()) + expire
  260. table_name = table
  261. if not table_name:
  262. table_name = self.normalize_name(self.cfg.name)
  263. self.create_table(table_name)
  264. sql = (
  265. f"INSERT INTO {table_name} (key, value, expire) VALUES (?, ?, ?)"
  266. f" ON CONFLICT DO "
  267. f"UPDATE SET value=?, expire=?"
  268. )
  269. if table:
  270. with self.DB:
  271. self.DB.execute(sql, (key, value, expire, value, expire))
  272. else:
  273. with self.connect() as conn:
  274. conn.execute(sql, (key, value, expire, value, expire))
  275. conn.close()
  276. return True
  277. def get(self, key: str, default=None, table: str | None = None) -> typing.Any:
  278. """Get value of ``key`` from ``table``. If ``table`` argument is
  279. ``None`` (the default), a table name is generated from the
  280. :py:obj:`ExpireCacheCfg.name`. If ``key`` not exists (in table), the
  281. ``default`` value is returned.
  282. """
  283. self.maintenance()
  284. if not table:
  285. table = self.normalize_name(self.cfg.name)
  286. if table not in self.table_names:
  287. return default
  288. sql = f"SELECT value FROM {table} WHERE key = ?"
  289. row = self.DB.execute(sql, (key,)).fetchone()
  290. if row is None:
  291. return default
  292. return self.deserialize(row[0])
  293. def state(self) -> ExpireCacheStats:
  294. cached_items = {}
  295. for table in self.table_names:
  296. cached_items[table] = []
  297. for row in self.DB.execute(f"SELECT key, value, expire FROM {table}"):
  298. cached_items[table].append((row[0], self.deserialize(row[1]), row[2]))
  299. return ExpireCacheStats(cached_items=cached_items)