cache.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  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 context name.
  63. .. code: python
  64. {
  65. "context name": [
  66. ("foo key": "foo value", <expire>),
  67. ("bar key": "bar value", <expire>),
  68. # ...
  69. ],
  70. # ...
  71. }
  72. """
  73. def report(self):
  74. c_ctx = 0
  75. c_kv = 0
  76. lines = []
  77. for ctx_name, kv_list in self.cached_items.items():
  78. c_ctx += 1
  79. if not kv_list:
  80. lines.append(f"[{ctx_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"[{ctx_name:20s}] {valid_until} {key:12}" f" --> ({type(value).__name__}) {value} ")
  86. lines.append(f"Number of contexts: {c_ctx}")
  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, ctx: str | None = 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. The ``ctx`` argument specifies the context of the ``key``. A key is
  101. only unique in its context.
  102. The concrete implementations of this abstraction determine how the
  103. context is mapped in the connected database. In SQL databases, for
  104. example, the context is a DB table or in a Key/Value DB it could be
  105. a prefix for the key.
  106. If the context is not specified (the default is ``None``) then a
  107. default context should be used, e.g. a default table for SQL databases
  108. or a default prefix in a Key/Value DB.
  109. """
  110. @abc.abstractmethod
  111. def get(self, key: str, default=None, ctx: str | None = None) -> typing.Any:
  112. """Return *value* of *key*. If key is unset, ``None`` is returned."""
  113. @abc.abstractmethod
  114. def maintenance(self, force: bool = False, truncate: bool = False) -> bool:
  115. """Performs maintenance on the cache.
  116. ``force``:
  117. Maintenance should be carried out even if the maintenance interval has
  118. not yet been reached.
  119. ``truncate``:
  120. Truncate the entire cache, which is necessary, for example, if the
  121. password has changed.
  122. """
  123. @abc.abstractmethod
  124. def state(self) -> ExpireCacheStats:
  125. """Returns a :py:obj:`ExpireCacheStats`, which provides information
  126. about the status of the cache."""
  127. @staticmethod
  128. def build_cache(cfg: ExpireCacheCfg) -> ExpireCache:
  129. """Factory to build a caching instance.
  130. .. note::
  131. Currently, only the SQLite adapter is available, but other database
  132. types could be implemented in the future, e.g. a Valkey (Redis)
  133. adapter.
  134. """
  135. return ExpireCacheSQLite(cfg)
  136. @staticmethod
  137. def normalize_name(name: str) -> str:
  138. """Returns a normalized name that can be used as a file name or as a SQL
  139. table name (is used, for example, to normalize the context name)."""
  140. _valid = "-_." + string.ascii_letters + string.digits
  141. return "".join([c for c in name if c in _valid])
  142. def serialize(self, value: typing.Any) -> bytes:
  143. dump: bytes = pickle.dumps(value)
  144. return dump
  145. def deserialize(self, value: bytes) -> typing.Any:
  146. obj = pickle.loads(value)
  147. return obj
  148. def secret_hash(self, name: str | bytes) -> str:
  149. """Creates a hash of the argument ``name``. The hash value is formed
  150. from the ``name`` combined with the :py:obj:`password
  151. <ExpireCacheCfg.password>`. Can be used, for example, to make the
  152. ``key`` stored in the DB unreadable for third parties."""
  153. if isinstance(name, str):
  154. name = bytes(name, encoding='utf-8')
  155. m = hmac.new(name + self.cfg.password, digestmod='sha256')
  156. return m.hexdigest()
  157. class ExpireCacheSQLite(sqlitedb.SQLiteAppl, ExpireCache):
  158. """Cache that manages key/value pairs in a SQLite DB. The DB model in the
  159. SQLite DB is implemented in abstract class :py:obj:`SQLiteAppl
  160. <searx.sqlitedb.SQLiteAppl>`.
  161. The following configurations are required / supported:
  162. - :py:obj:`ExpireCacheCfg.db_url`
  163. - :py:obj:`ExpireCacheCfg.MAXHOLD_TIME`
  164. - :py:obj:`ExpireCacheCfg.MAINTENANCE_PERIOD`
  165. - :py:obj:`ExpireCacheCfg.MAINTENANCE_MODE`
  166. """
  167. DB_SCHEMA = 1
  168. # The key/value tables will be created on demand by self.create_table
  169. DDL_CREATE_TABLES = {}
  170. CACHE_TABLE_PREFIX = "CACHE-TABLE-"
  171. def __init__(self, cfg: ExpireCacheCfg):
  172. """An instance of the SQLite expire cache is build up from a
  173. :py:obj:`config <ExpireCacheCfg>`."""
  174. self.cfg = cfg
  175. if cfg.db_url == ":memory:":
  176. log.critical("don't use SQLite DB in :memory: in production!!")
  177. super().__init__(cfg.db_url)
  178. def init(self, conn: sqlite3.Connection) -> bool:
  179. ret_val = super().init(conn)
  180. if not ret_val:
  181. return False
  182. new = hashlib.sha256(self.cfg.password).hexdigest()
  183. old = self.properties(self.hash_token)
  184. if old != new:
  185. if old is not None:
  186. log.warning("[%s] hash token changed: truncate all cache tables", self.cfg.name)
  187. self.maintenance(force=True, truncate=True)
  188. self.properties.set(self.hash_token, new)
  189. return True
  190. def maintenance(self, force: bool = False, truncate: bool = False) -> bool:
  191. if not force and int(time.time()) < self.next_maintenance_time:
  192. # log.debug("no maintenance required yet, next maintenance interval is in the future")
  193. return False
  194. # Prevent parallel DB maintenance cycles from other DB connections
  195. # (e.g. in multi thread or process environments).
  196. self.properties.set("LAST_MAINTENANCE", "") # hint: this (also) sets the m_time of the property!
  197. if truncate:
  198. self.truncate_tables(self.table_names)
  199. return True
  200. # drop items by expire time stamp ..
  201. expire = int(time.time())
  202. with self.connect() as conn:
  203. for table in self.table_names:
  204. res = conn.execute(f"DELETE FROM {table} WHERE expire < ?", (expire,))
  205. log.debug("deleted %s keys from table %s (expire date reached)", res.rowcount, table)
  206. # Vacuuming the WALs
  207. # https://www.theunterminatedstring.com/sqlite-vacuuming/
  208. conn.execute("PRAGMA wal_checkpoint(TRUNCATE)")
  209. conn.close()
  210. return True
  211. def create_table(self, table: str) -> bool:
  212. """Create DB ``table`` if it has not yet been created, no recreates are
  213. initiated if the table already exists.
  214. """
  215. if table in self.table_names:
  216. # log.debug("key/value table %s exists in DB (no need to recreate)", table)
  217. return False
  218. log.info("key/value table '%s' NOT exists in DB -> create DB table ..", table)
  219. sql_table = "\n".join(
  220. [
  221. f"CREATE TABLE IF NOT EXISTS {table} (",
  222. " key TEXT,",
  223. " value BLOB,",
  224. f" expire INTEGER DEFAULT (strftime('%s', 'now') + {self.cfg.MAXHOLD_TIME}),",
  225. "PRIMARY KEY (key))",
  226. ]
  227. )
  228. sql_index = f"CREATE INDEX IF NOT EXISTS index_expire_{table} ON {table}(expire);"
  229. with self.connect() as conn:
  230. conn.execute(sql_table)
  231. conn.execute(sql_index)
  232. conn.close()
  233. self.properties.set(f"{self.CACHE_TABLE_PREFIX}-{table}", table)
  234. return True
  235. @property
  236. def table_names(self) -> list[str]:
  237. """List of key/value tables already created in the DB."""
  238. sql = f"SELECT value FROM properties WHERE name LIKE '{self.CACHE_TABLE_PREFIX}%%'"
  239. rows = self.DB.execute(sql).fetchall() or []
  240. return [r[0] for r in rows]
  241. def truncate_tables(self, table_names: list[str]):
  242. log.debug("truncate table: %s", ",".join(table_names))
  243. with self.connect() as conn:
  244. for table in table_names:
  245. conn.execute(f"DELETE FROM {table}")
  246. conn.close()
  247. return True
  248. @property
  249. def next_maintenance_time(self) -> int:
  250. """Returns (unix epoch) time of the next maintenance."""
  251. return self.cfg.MAINTENANCE_PERIOD + self.properties.m_time("LAST_MAINTENANCE", int(time.time()))
  252. # implement ABC methods of ExpireCache
  253. def set(self, key: str, value: typing.Any, expire: int | None, ctx: str | None = None) -> bool:
  254. """Set key/value in DB table given by argument ``ctx``. If expire is
  255. unset the default is taken from :py:obj:`ExpireCacheCfg.MAXHOLD_TIME`.
  256. If ``ctx`` argument is ``None`` (the default), a table name is
  257. generated from the :py:obj:`ExpireCacheCfg.name`. If DB table does not
  258. exists, it will be created (on demand) by :py:obj:`self.create_table
  259. <ExpireCacheSQLite.create_table>`.
  260. """
  261. table = ctx
  262. self.maintenance()
  263. value = self.serialize(value=value)
  264. if len(value) > self.cfg.MAX_VALUE_LEN:
  265. log.warning("ExpireCache.set(): %s.key='%s' - value too big to cache (len: %s) ", table, value, len(value))
  266. return False
  267. if not expire:
  268. expire = self.cfg.MAXHOLD_TIME
  269. expire = int(time.time()) + expire
  270. table_name = table
  271. if not table_name:
  272. table_name = self.normalize_name(self.cfg.name)
  273. self.create_table(table_name)
  274. sql = (
  275. f"INSERT INTO {table_name} (key, value, expire) VALUES (?, ?, ?)"
  276. f" ON CONFLICT DO "
  277. f"UPDATE SET value=?, expire=?"
  278. )
  279. if table:
  280. with self.DB:
  281. self.DB.execute(sql, (key, value, expire, value, expire))
  282. else:
  283. with self.connect() as conn:
  284. conn.execute(sql, (key, value, expire, value, expire))
  285. conn.close()
  286. return True
  287. def get(self, key: str, default=None, ctx: str | None = None) -> typing.Any:
  288. """Get value of ``key`` from table given by argument ``ctx``. If
  289. ``ctx`` argument is ``None`` (the default), a table name is generated
  290. from the :py:obj:`ExpireCacheCfg.name`. If ``key`` not exists (in
  291. table), the ``default`` value is returned.
  292. """
  293. table = ctx
  294. self.maintenance()
  295. if not table:
  296. table = self.normalize_name(self.cfg.name)
  297. if table not in self.table_names:
  298. return default
  299. sql = f"SELECT value FROM {table} WHERE key = ?"
  300. row = self.DB.execute(sql, (key,)).fetchone()
  301. if row is None:
  302. return default
  303. return self.deserialize(row[0])
  304. def state(self) -> ExpireCacheStats:
  305. cached_items = {}
  306. for table in self.table_names:
  307. cached_items[table] = []
  308. for row in self.DB.execute(f"SELECT key, value, expire FROM {table}"):
  309. cached_items[table].append((row[0], self.deserialize(row[1]), row[2]))
  310. return ExpireCacheStats(cached_items=cached_items)