redislib.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """A collection of convenient functions and redis/lua scripts.
  3. This code was partial inspired by the `Bullet-Proofing Lua Scripts in RedisPy`_
  4. article.
  5. .. _Bullet-Proofing Lua Scripts in RedisPy:
  6. https://redis.com/blog/bullet-proofing-lua-scripts-in-redispy/
  7. """
  8. import hmac
  9. from searx import get_setting
  10. LUA_SCRIPT_STORAGE = {}
  11. """A global dictionary to cache client's ``Script`` objects, used by
  12. :py:obj:`lua_script_storage`"""
  13. def lua_script_storage(client, script):
  14. """Returns a redis :py:obj:`Script
  15. <redis.commands.core.CoreCommands.register_script>` instance.
  16. Due to performance reason the ``Script`` object is instantiated only once
  17. for a client (``client.register_script(..)``) and is cached in
  18. :py:obj:`LUA_SCRIPT_STORAGE`.
  19. """
  20. # redis connection can be closed, lets use the id() of the redis connector
  21. # as key in the script-storage:
  22. client_id = id(client)
  23. if LUA_SCRIPT_STORAGE.get(client_id) is None:
  24. LUA_SCRIPT_STORAGE[client_id] = {}
  25. if LUA_SCRIPT_STORAGE[client_id].get(script) is None:
  26. LUA_SCRIPT_STORAGE[client_id][script] = client.register_script(script)
  27. return LUA_SCRIPT_STORAGE[client_id][script]
  28. PURGE_BY_PREFIX = """
  29. local prefix = tostring(ARGV[1])
  30. for i, name in ipairs(redis.call('KEYS', prefix .. '*')) do
  31. redis.call('EXPIRE', name, 0)
  32. end
  33. """
  34. def purge_by_prefix(client, prefix: str = "SearXNG_"):
  35. """Purge all keys with ``prefix`` from database.
  36. Queries all keys in the database by the given prefix and set expire time to
  37. zero. The default prefix will drop all keys which has been set by SearXNG
  38. (drops SearXNG schema entirely from database).
  39. The implementation is the lua script from string :py:obj:`PURGE_BY_PREFIX`.
  40. The lua script uses EXPIRE_ instead of DEL_: if there are a lot keys to
  41. delete and/or their values are big, `DEL` could take more time and blocks
  42. the command loop while `EXPIRE` turns back immediate.
  43. :param prefix: prefix of the key to delete (default: ``SearXNG_``)
  44. :type name: str
  45. .. _EXPIRE: https://redis.io/commands/expire/
  46. .. _DEL: https://redis.io/commands/del/
  47. """
  48. script = lua_script_storage(client, PURGE_BY_PREFIX)
  49. script(args=[prefix])
  50. def secret_hash(name: str):
  51. """Creates a hash of the ``name``.
  52. Combines argument ``name`` with the ``secret_key`` from :ref:`settings
  53. server`. This function can be used to get a more anonymized name of a Redis
  54. KEY.
  55. :param name: the name to create a secret hash for
  56. :type name: str
  57. """
  58. m = hmac.new(bytes(name, encoding='utf-8'), digestmod='sha256')
  59. m.update(bytes(get_setting('server.secret_key'), encoding='utf-8'))
  60. return m.hexdigest()
  61. INCR_COUNTER = """
  62. local limit = tonumber(ARGV[1])
  63. local expire = tonumber(ARGV[2])
  64. local c_name = KEYS[1]
  65. local c = redis.call('GET', c_name)
  66. if not c then
  67. c = redis.call('INCR', c_name)
  68. if expire > 0 then
  69. redis.call('EXPIRE', c_name, expire)
  70. end
  71. else
  72. c = tonumber(c)
  73. if limit == 0 or c < limit then
  74. c = redis.call('INCR', c_name)
  75. end
  76. end
  77. return c
  78. """
  79. def incr_counter(client, name: str, limit: int = 0, expire: int = 0):
  80. """Increment a counter and return the new value.
  81. If counter with redis key ``SearXNG_counter_<name>`` does not exists it is
  82. created with initial value 1 returned. The replacement ``<name>`` is a
  83. *secret hash* of the value from argument ``name`` (see
  84. :py:func:`secret_hash`).
  85. The implementation of the redis counter is the lua script from string
  86. :py:obj:`INCR_COUNTER`.
  87. :param name: name of the counter
  88. :type name: str
  89. :param expire: live-time of the counter in seconds (default ``None`` means
  90. infinite).
  91. :type expire: int / see EXPIRE_
  92. :param limit: limit where the counter stops to increment (default ``None``)
  93. :type limit: int / limit is 2^64 see INCR_
  94. :return: value of the incremented counter
  95. :type return: int
  96. .. _EXPIRE: https://redis.io/commands/expire/
  97. .. _INCR: https://redis.io/commands/incr/
  98. A simple demo of a counter with expire time and limit::
  99. >>> for i in range(6):
  100. ... i, incr_counter(client, "foo", 3, 5) # max 3, duration 5 sec
  101. ... time.sleep(1) # from the third call on max has been reached
  102. ...
  103. (0, 1)
  104. (1, 2)
  105. (2, 3)
  106. (3, 3)
  107. (4, 3)
  108. (5, 1)
  109. """
  110. script = lua_script_storage(client, INCR_COUNTER)
  111. name = "SearXNG_counter_" + secret_hash(name)
  112. c = script(args=[limit, expire], keys=[name])
  113. return c
  114. def drop_counter(client, name):
  115. """Drop counter with redis key ``SearXNG_counter_<name>``
  116. The replacement ``<name>`` is a *secret hash* of the value from argument
  117. ``name`` (see :py:func:`incr_counter` and :py:func:`incr_sliding_window`).
  118. """
  119. name = "SearXNG_counter_" + secret_hash(name)
  120. client.delete(name)
  121. INCR_SLIDING_WINDOW = """
  122. local expire = tonumber(ARGV[1])
  123. local name = KEYS[1]
  124. local current_time = redis.call('TIME')
  125. redis.call('ZREMRANGEBYSCORE', name, 0, current_time[1] - expire)
  126. redis.call('ZADD', name, current_time[1], current_time[1] .. current_time[2])
  127. local result = redis.call('ZCOUNT', name, 0, current_time[1] + 1)
  128. redis.call('EXPIRE', name, expire)
  129. return result
  130. """
  131. def incr_sliding_window(client, name: str, duration: int):
  132. """Increment a sliding-window counter and return the new value.
  133. If counter with redis key ``SearXNG_counter_<name>`` does not exists it is
  134. created with initial value 1 returned. The replacement ``<name>`` is a
  135. *secret hash* of the value from argument ``name`` (see
  136. :py:func:`secret_hash`).
  137. :param name: name of the counter
  138. :type name: str
  139. :param duration: live-time of the sliding window in seconds
  140. :typeduration: int
  141. :return: value of the incremented counter
  142. :type return: int
  143. The implementation of the redis counter is the lua script from string
  144. :py:obj:`INCR_SLIDING_WINDOW`. The lua script uses `sorted sets in Redis`_
  145. to implement a sliding window for the redis key ``SearXNG_counter_<name>``
  146. (ZADD_). The current TIME_ is used to score the items in the sorted set and
  147. the time window is moved by removing items with a score lower current time
  148. minus *duration* time (ZREMRANGEBYSCORE_).
  149. The EXPIRE_ time (the duration of the sliding window) is refreshed on each
  150. call (increment) and if there is no call in this duration, the sorted
  151. set expires from the redis DB.
  152. The return value is the amount of items in the sorted set (ZCOUNT_), what
  153. means the number of calls in the sliding window.
  154. .. _Sorted sets in Redis:
  155. https://redis.com/ebook/part-1-getting-started/chapter-1-getting-to-know-redis/1-2-what-redis-data-structures-look-like/1-2-5-sorted-sets-in-redis/
  156. .. _TIME: https://redis.io/commands/time/
  157. .. _ZADD: https://redis.io/commands/zadd/
  158. .. _EXPIRE: https://redis.io/commands/expire/
  159. .. _ZREMRANGEBYSCORE: https://redis.io/commands/zremrangebyscore/
  160. .. _ZCOUNT: https://redis.io/commands/zcount/
  161. A simple demo of the sliding window::
  162. >>> for i in range(5):
  163. ... incr_sliding_window(client, "foo", 3) # duration 3 sec
  164. ... time.sleep(1) # from the third call (second) on the window is moved
  165. ...
  166. 1
  167. 2
  168. 3
  169. 3
  170. 3
  171. >>> time.sleep(3) # wait until expire
  172. >>> incr_sliding_window(client, "foo", 3)
  173. 1
  174. """
  175. script = lua_script_storage(client, INCR_SLIDING_WINDOW)
  176. name = "SearXNG_counter_" + secret_hash(name)
  177. c = script(args=[duration], keys=[name])
  178. return c