redislib.py 6.7 KB

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