redis.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  1. package cache
  2. import (
  3. "context"
  4. "errors"
  5. "strings"
  6. "time"
  7. "github.com/langgenius/dify-plugin-daemon/internal/utils/parser"
  8. "github.com/redis/go-redis/v9"
  9. )
  10. var (
  11. client *redis.Client
  12. ctx = context.Background()
  13. ErrDBNotInit = errors.New("redis client not init")
  14. ErrNotFound = errors.New("key not found")
  15. )
  16. func InitRedisClient(addr, password string) error {
  17. client = redis.NewClient(&redis.Options{
  18. Addr: addr,
  19. Password: password,
  20. })
  21. if _, err := client.Ping(ctx).Result(); err != nil {
  22. return err
  23. }
  24. return nil
  25. }
  26. // Close the redis client
  27. func Close() error {
  28. if client == nil {
  29. return ErrDBNotInit
  30. }
  31. return client.Close()
  32. }
  33. func getCmdable(context ...redis.Cmdable) redis.Cmdable {
  34. if len(context) > 0 {
  35. return context[0]
  36. }
  37. return client
  38. }
  39. func serialKey(keys ...string) string {
  40. return strings.Join(append(
  41. []string{"plugin_daemon"},
  42. keys...,
  43. ), ":")
  44. }
  45. // Store the key-value pair
  46. func Store(key string, value any, time time.Duration, context ...redis.Cmdable) error {
  47. if client == nil {
  48. return ErrDBNotInit
  49. }
  50. if _, ok := value.(string); !ok {
  51. value = parser.MarshalJson(value)
  52. }
  53. return getCmdable(context...).Set(ctx, serialKey(key), value, time).Err()
  54. }
  55. // Get the value with key
  56. func Get[T any](key string, context ...redis.Cmdable) (*T, error) {
  57. if client == nil {
  58. return nil, ErrDBNotInit
  59. }
  60. val, err := getCmdable(context...).Get(ctx, serialKey(key)).Result()
  61. if err != nil {
  62. if err == redis.Nil {
  63. return nil, ErrNotFound
  64. }
  65. return nil, err
  66. }
  67. if val == "" {
  68. return nil, ErrNotFound
  69. }
  70. result, err := parser.UnmarshalJson[T](val)
  71. return &result, err
  72. }
  73. // GetString get the string with key
  74. func GetString(key string, context ...redis.Cmdable) (string, error) {
  75. if client == nil {
  76. return "", ErrDBNotInit
  77. }
  78. v, err := getCmdable(context...).Get(ctx, serialKey(key)).Result()
  79. if err != nil {
  80. if err == redis.Nil {
  81. return "", ErrNotFound
  82. }
  83. }
  84. return v, err
  85. }
  86. // Del the key
  87. func Del(key string, context ...redis.Cmdable) error {
  88. if client == nil {
  89. return ErrDBNotInit
  90. }
  91. _, err := getCmdable(context...).Del(ctx, serialKey(key)).Result()
  92. if err != nil {
  93. if err == redis.Nil {
  94. return ErrNotFound
  95. }
  96. return err
  97. }
  98. return nil
  99. }
  100. // Exist check the key exist or not
  101. func Exist(key string, context ...redis.Cmdable) (int64, error) {
  102. if client == nil {
  103. return 0, ErrDBNotInit
  104. }
  105. return getCmdable(context...).Exists(ctx, serialKey(key)).Result()
  106. }
  107. // Increase the key
  108. func Increase(key string, context ...redis.Cmdable) (int64, error) {
  109. if client == nil {
  110. return 0, ErrDBNotInit
  111. }
  112. num, err := getCmdable(context...).Incr(ctx, serialKey(key)).Result()
  113. if err != nil {
  114. if err == redis.Nil {
  115. return 0, ErrNotFound
  116. }
  117. return 0, err
  118. }
  119. return num, nil
  120. }
  121. // Decrease the key
  122. func Decrease(key string, context ...redis.Cmdable) (int64, error) {
  123. if client == nil {
  124. return 0, ErrDBNotInit
  125. }
  126. return getCmdable(context...).Decr(ctx, serialKey(key)).Result()
  127. }
  128. // SetExpire set the expire time for the key
  129. func SetExpire(key string, time time.Duration, context ...redis.Cmdable) error {
  130. if client == nil {
  131. return ErrDBNotInit
  132. }
  133. return getCmdable(context...).Expire(ctx, serialKey(key), time).Err()
  134. }
  135. // SetMapField set the map field with key
  136. func SetMapField(key string, v map[string]any, context ...redis.Cmdable) error {
  137. if client == nil {
  138. return ErrDBNotInit
  139. }
  140. return getCmdable(context...).HMSet(ctx, serialKey(key), v).Err()
  141. }
  142. // SetMapOneField set the map field with key
  143. func SetMapOneField(key string, field string, value any, context ...redis.Cmdable) error {
  144. if client == nil {
  145. return ErrDBNotInit
  146. }
  147. if _, ok := value.(string); !ok {
  148. value = parser.MarshalJson(value)
  149. }
  150. return getCmdable(context...).HSet(ctx, serialKey(key), field, value).Err()
  151. }
  152. // GetMapField get the map field with key
  153. func GetMapField[T any](key string, field string, context ...redis.Cmdable) (*T, error) {
  154. if client == nil {
  155. return nil, ErrDBNotInit
  156. }
  157. val, err := getCmdable(context...).HGet(ctx, serialKey(key), field).Result()
  158. if err != nil {
  159. if err == redis.Nil {
  160. return nil, ErrNotFound
  161. }
  162. return nil, err
  163. }
  164. result, err := parser.UnmarshalJson[T](val)
  165. return &result, err
  166. }
  167. // DelMapField delete the map field with key
  168. func DelMapField(key string, field string, context ...redis.Cmdable) error {
  169. if client == nil {
  170. return ErrDBNotInit
  171. }
  172. return getCmdable(context...).HDel(ctx, serialKey(key), field).Err()
  173. }
  174. // GetMap get the map with key
  175. func GetMap[V any](key string, context ...redis.Cmdable) (map[string]V, error) {
  176. if client == nil {
  177. return nil, ErrDBNotInit
  178. }
  179. val, err := getCmdable(context...).HGetAll(ctx, serialKey(key)).Result()
  180. if err != nil {
  181. if err == redis.Nil {
  182. return nil, ErrNotFound
  183. }
  184. return nil, err
  185. }
  186. result := make(map[string]V)
  187. for k, v := range val {
  188. value, err := parser.UnmarshalJson[V](v)
  189. if err != nil {
  190. continue
  191. }
  192. result[k] = value
  193. }
  194. return result, nil
  195. }
  196. // ScanMap scan the map with match pattern, format like "key*"
  197. func ScanMap[V any](key string, match string, context ...redis.Cmdable) (map[string]V, error) {
  198. if client == nil {
  199. return nil, ErrDBNotInit
  200. }
  201. result := make(map[string]V)
  202. ScanMapAsync[V](key, match, func(m map[string]V) error {
  203. for k, v := range m {
  204. result[k] = v
  205. }
  206. return nil
  207. })
  208. return result, nil
  209. }
  210. // ScanMapAsync scan the map with match pattern, format like "key*"
  211. func ScanMapAsync[V any](key string, match string, fn func(map[string]V) error, context ...redis.Cmdable) error {
  212. if client == nil {
  213. return ErrDBNotInit
  214. }
  215. cursor := uint64(0)
  216. for {
  217. kvs, new_cursor, err := getCmdable(context...).
  218. HScan(ctx, serialKey(key), cursor, match, 32).
  219. Result()
  220. if err != nil {
  221. return err
  222. }
  223. result := make(map[string]V)
  224. for i := 0; i < len(kvs); i += 2 {
  225. value, err := parser.UnmarshalJson[V](kvs[i+1])
  226. if err != nil {
  227. continue
  228. }
  229. result[kvs[i]] = value
  230. }
  231. if err := fn(result); err != nil {
  232. return err
  233. }
  234. if new_cursor == 0 {
  235. break
  236. }
  237. cursor = new_cursor
  238. }
  239. return nil
  240. }
  241. // SetNX set the key-value pair with expire time
  242. func SetNX[T any](key string, value T, expire time.Duration, context ...redis.Cmdable) (bool, error) {
  243. if client == nil {
  244. return false, ErrDBNotInit
  245. }
  246. return getCmdable(context...).SetNX(ctx, serialKey(key), value, expire).Result()
  247. }
  248. var (
  249. ErrLockTimeout = errors.New("lock timeout")
  250. )
  251. // Lock key, expire time takes responsibility for expiration time
  252. // try_lock_timeout takes responsibility for the timeout of trying to lock
  253. func Lock(key string, expire time.Duration, try_lock_timeout time.Duration, context ...redis.Cmdable) error {
  254. if client == nil {
  255. return ErrDBNotInit
  256. }
  257. const LOCK_DURATION = 20 * time.Millisecond
  258. ticker := time.NewTicker(LOCK_DURATION)
  259. defer ticker.Stop()
  260. for range ticker.C {
  261. if _, err := getCmdable(context...).SetNX(ctx, serialKey(key), "1", expire).Result(); err == nil {
  262. return nil
  263. }
  264. try_lock_timeout -= LOCK_DURATION
  265. if try_lock_timeout <= 0 {
  266. return ErrLockTimeout
  267. }
  268. }
  269. return nil
  270. }
  271. func Unlock(key string, context ...redis.Cmdable) error {
  272. if client == nil {
  273. return ErrDBNotInit
  274. }
  275. return getCmdable(context...).Del(ctx, serialKey(key)).Err()
  276. }
  277. func Expire(key string, time time.Duration, context ...redis.Cmdable) (bool, error) {
  278. if client == nil {
  279. return false, ErrDBNotInit
  280. }
  281. return getCmdable(context...).Expire(ctx, serialKey(key), time).Result()
  282. }
  283. func Transaction(fn func(redis.Pipeliner) error) error {
  284. if client == nil {
  285. return ErrDBNotInit
  286. }
  287. return client.Watch(ctx, func(tx *redis.Tx) error {
  288. _, err := tx.TxPipelined(ctx, func(p redis.Pipeliner) error {
  289. return fn(p)
  290. })
  291. if err == redis.Nil {
  292. return nil
  293. }
  294. return err
  295. })
  296. }