redis.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  1. package cache
  2. import (
  3. "context"
  4. "crypto/tls"
  5. "errors"
  6. "strings"
  7. "time"
  8. "github.com/langgenius/dify-plugin-daemon/internal/utils/log"
  9. "github.com/langgenius/dify-plugin-daemon/internal/utils/parser"
  10. "github.com/redis/go-redis/v9"
  11. )
  12. var (
  13. client *redis.Client
  14. ctx = context.Background()
  15. ErrDBNotInit = errors.New("redis client not init")
  16. ErrNotFound = errors.New("key not found")
  17. )
  18. func getRedisOptions(addr, password string, useSsl bool) *redis.Options {
  19. opts := &redis.Options{
  20. Addr: addr,
  21. Password: password,
  22. }
  23. if useSsl {
  24. opts.TLSConfig = &tls.Config{}
  25. }
  26. return opts
  27. }
  28. func InitRedisClient(addr, password string, useSsl bool) error {
  29. opts := getRedisOptions(addr, password, useSsl)
  30. client = redis.NewClient(opts)
  31. if _, err := client.Ping(ctx).Result(); err != nil {
  32. return err
  33. }
  34. return nil
  35. }
  36. // Close the redis client
  37. func Close() error {
  38. if client == nil {
  39. return ErrDBNotInit
  40. }
  41. return client.Close()
  42. }
  43. func getCmdable(context ...redis.Cmdable) redis.Cmdable {
  44. if len(context) > 0 {
  45. return context[0]
  46. }
  47. return client
  48. }
  49. func serialKey(keys ...string) string {
  50. return strings.Join(append(
  51. []string{"plugin_daemon"},
  52. keys...,
  53. ), ":")
  54. }
  55. // Store the key-value pair
  56. func Store(key string, value any, time time.Duration, context ...redis.Cmdable) error {
  57. if client == nil {
  58. return ErrDBNotInit
  59. }
  60. if _, ok := value.(string); !ok {
  61. var err error
  62. value, err = parser.MarshalCBOR(value)
  63. if err != nil {
  64. return err
  65. }
  66. }
  67. return getCmdable(context...).Set(ctx, serialKey(key), value, time).Err()
  68. }
  69. // Get the value with key
  70. func Get[T any](key string, context ...redis.Cmdable) (*T, error) {
  71. if client == nil {
  72. return nil, ErrDBNotInit
  73. }
  74. val, err := getCmdable(context...).Get(ctx, serialKey(key)).Bytes()
  75. if err != nil {
  76. if err == redis.Nil {
  77. return nil, ErrNotFound
  78. }
  79. return nil, err
  80. }
  81. if len(val) == 0 {
  82. return nil, ErrNotFound
  83. }
  84. result, err := parser.UnmarshalCBOR[T](val)
  85. return &result, err
  86. }
  87. // GetString get the string with key
  88. func GetString(key string, context ...redis.Cmdable) (string, error) {
  89. if client == nil {
  90. return "", ErrDBNotInit
  91. }
  92. v, err := getCmdable(context...).Get(ctx, serialKey(key)).Result()
  93. if err != nil {
  94. if err == redis.Nil {
  95. return "", ErrNotFound
  96. }
  97. }
  98. return v, err
  99. }
  100. // Del the key
  101. func Del(key string, context ...redis.Cmdable) error {
  102. if client == nil {
  103. return ErrDBNotInit
  104. }
  105. _, err := getCmdable(context...).Del(ctx, serialKey(key)).Result()
  106. if err != nil {
  107. if err == redis.Nil {
  108. return ErrNotFound
  109. }
  110. return err
  111. }
  112. return nil
  113. }
  114. // Exist check the key exist or not
  115. func Exist(key string, context ...redis.Cmdable) (int64, error) {
  116. if client == nil {
  117. return 0, ErrDBNotInit
  118. }
  119. return getCmdable(context...).Exists(ctx, serialKey(key)).Result()
  120. }
  121. // Increase the key
  122. func Increase(key string, context ...redis.Cmdable) (int64, error) {
  123. if client == nil {
  124. return 0, ErrDBNotInit
  125. }
  126. num, err := getCmdable(context...).Incr(ctx, serialKey(key)).Result()
  127. if err != nil {
  128. if err == redis.Nil {
  129. return 0, ErrNotFound
  130. }
  131. return 0, err
  132. }
  133. return num, nil
  134. }
  135. // Decrease the key
  136. func Decrease(key string, context ...redis.Cmdable) (int64, error) {
  137. if client == nil {
  138. return 0, ErrDBNotInit
  139. }
  140. return getCmdable(context...).Decr(ctx, serialKey(key)).Result()
  141. }
  142. // SetExpire set the expire time for the key
  143. func SetExpire(key string, time time.Duration, context ...redis.Cmdable) error {
  144. if client == nil {
  145. return ErrDBNotInit
  146. }
  147. return getCmdable(context...).Expire(ctx, serialKey(key), time).Err()
  148. }
  149. // SetMapField set the map field with key
  150. func SetMapField(key string, v map[string]any, context ...redis.Cmdable) error {
  151. if client == nil {
  152. return ErrDBNotInit
  153. }
  154. return getCmdable(context...).HMSet(ctx, serialKey(key), v).Err()
  155. }
  156. // SetMapOneField set the map field with key
  157. func SetMapOneField(key string, field string, value any, context ...redis.Cmdable) error {
  158. if client == nil {
  159. return ErrDBNotInit
  160. }
  161. if _, ok := value.(string); !ok {
  162. value = parser.MarshalJson(value)
  163. }
  164. return getCmdable(context...).HSet(ctx, serialKey(key), field, value).Err()
  165. }
  166. // GetMapField get the map field with key
  167. func GetMapField[T any](key string, field string, context ...redis.Cmdable) (*T, error) {
  168. if client == nil {
  169. return nil, ErrDBNotInit
  170. }
  171. val, err := getCmdable(context...).HGet(ctx, serialKey(key), field).Result()
  172. if err != nil {
  173. if err == redis.Nil {
  174. return nil, ErrNotFound
  175. }
  176. return nil, err
  177. }
  178. result, err := parser.UnmarshalJson[T](val)
  179. return &result, err
  180. }
  181. // GetMapFieldString get the string
  182. func GetMapFieldString(key string, field string, context ...redis.Cmdable) (string, error) {
  183. if client == nil {
  184. return "", ErrDBNotInit
  185. }
  186. val, err := getCmdable(context...).HGet(ctx, serialKey(key), field).Result()
  187. if err != nil {
  188. if err == redis.Nil {
  189. return "", ErrNotFound
  190. }
  191. return "", err
  192. }
  193. return val, nil
  194. }
  195. // DelMapField delete the map field with key
  196. func DelMapField(key string, field string, context ...redis.Cmdable) error {
  197. if client == nil {
  198. return ErrDBNotInit
  199. }
  200. return getCmdable(context...).HDel(ctx, serialKey(key), field).Err()
  201. }
  202. // GetMap get the map with key
  203. func GetMap[V any](key string, context ...redis.Cmdable) (map[string]V, error) {
  204. if client == nil {
  205. return nil, ErrDBNotInit
  206. }
  207. val, err := getCmdable(context...).HGetAll(ctx, serialKey(key)).Result()
  208. if err != nil {
  209. if err == redis.Nil {
  210. return nil, ErrNotFound
  211. }
  212. return nil, err
  213. }
  214. result := make(map[string]V)
  215. for k, v := range val {
  216. value, err := parser.UnmarshalJson[V](v)
  217. if err != nil {
  218. continue
  219. }
  220. result[k] = value
  221. }
  222. return result, nil
  223. }
  224. // ScanKeys scan the keys with match pattern
  225. func ScanKeys(match string, context ...redis.Cmdable) ([]string, error) {
  226. if client == nil {
  227. return nil, ErrDBNotInit
  228. }
  229. result := make([]string, 0)
  230. if err := ScanKeysAsync(match, func(keys []string) error {
  231. result = append(result, keys...)
  232. return nil
  233. }); err != nil {
  234. return nil, err
  235. }
  236. return result, nil
  237. }
  238. // ScanKeysAsync scan the keys with match pattern, format like "key*"
  239. func ScanKeysAsync(match string, fn func([]string) error, context ...redis.Cmdable) error {
  240. if client == nil {
  241. return ErrDBNotInit
  242. }
  243. cursor := uint64(0)
  244. for {
  245. keys, newCursor, err := getCmdable(context...).Scan(ctx, cursor, match, 32).Result()
  246. if err != nil {
  247. return err
  248. }
  249. if err := fn(keys); err != nil {
  250. return err
  251. }
  252. if newCursor == 0 {
  253. break
  254. }
  255. cursor = newCursor
  256. }
  257. return nil
  258. }
  259. // ScanMap scan the map with match pattern, format like "key*"
  260. func ScanMap[V any](key string, match string, context ...redis.Cmdable) (map[string]V, error) {
  261. if client == nil {
  262. return nil, ErrDBNotInit
  263. }
  264. result := make(map[string]V)
  265. ScanMapAsync[V](key, match, func(m map[string]V) error {
  266. for k, v := range m {
  267. result[k] = v
  268. }
  269. return nil
  270. })
  271. return result, nil
  272. }
  273. // ScanMapAsync scan the map with match pattern, format like "key*"
  274. func ScanMapAsync[V any](key string, match string, fn func(map[string]V) error, context ...redis.Cmdable) error {
  275. if client == nil {
  276. return ErrDBNotInit
  277. }
  278. cursor := uint64(0)
  279. for {
  280. kvs, newCursor, err := getCmdable(context...).
  281. HScan(ctx, serialKey(key), cursor, match, 32).
  282. Result()
  283. if err != nil {
  284. return err
  285. }
  286. result := make(map[string]V)
  287. for i := 0; i < len(kvs); i += 2 {
  288. value, err := parser.UnmarshalJson[V](kvs[i+1])
  289. if err != nil {
  290. continue
  291. }
  292. result[kvs[i]] = value
  293. }
  294. if err := fn(result); err != nil {
  295. return err
  296. }
  297. if newCursor == 0 {
  298. break
  299. }
  300. cursor = newCursor
  301. }
  302. return nil
  303. }
  304. // SetNX set the key-value pair with expire time
  305. func SetNX[T any](key string, value T, expire time.Duration, context ...redis.Cmdable) (bool, error) {
  306. if client == nil {
  307. return false, ErrDBNotInit
  308. }
  309. // marshal the value
  310. bytes, err := parser.MarshalCBOR(value)
  311. if err != nil {
  312. return false, err
  313. }
  314. return getCmdable(context...).SetNX(ctx, serialKey(key), bytes, expire).Result()
  315. }
  316. var (
  317. ErrLockTimeout = errors.New("lock timeout")
  318. )
  319. // Lock key, expire time takes responsibility for expiration time
  320. // try_lock_timeout takes responsibility for the timeout of trying to lock
  321. func Lock(key string, expire time.Duration, tryLockTimeout time.Duration, context ...redis.Cmdable) error {
  322. if client == nil {
  323. return ErrDBNotInit
  324. }
  325. const LOCK_DURATION = 20 * time.Millisecond
  326. ticker := time.NewTicker(LOCK_DURATION)
  327. defer ticker.Stop()
  328. for range ticker.C {
  329. if _, err := getCmdable(context...).SetNX(ctx, serialKey(key), "1", expire).Result(); err == nil {
  330. return nil
  331. }
  332. tryLockTimeout -= LOCK_DURATION
  333. if tryLockTimeout <= 0 {
  334. return ErrLockTimeout
  335. }
  336. }
  337. return nil
  338. }
  339. func Unlock(key string, context ...redis.Cmdable) error {
  340. if client == nil {
  341. return ErrDBNotInit
  342. }
  343. return getCmdable(context...).Del(ctx, serialKey(key)).Err()
  344. }
  345. func Expire(key string, time time.Duration, context ...redis.Cmdable) (bool, error) {
  346. if client == nil {
  347. return false, ErrDBNotInit
  348. }
  349. return getCmdable(context...).Expire(ctx, serialKey(key), time).Result()
  350. }
  351. func Transaction(fn func(redis.Pipeliner) error) error {
  352. if client == nil {
  353. return ErrDBNotInit
  354. }
  355. return client.Watch(ctx, func(tx *redis.Tx) error {
  356. _, err := tx.TxPipelined(ctx, func(p redis.Pipeliner) error {
  357. return fn(p)
  358. })
  359. if err == redis.Nil {
  360. return nil
  361. }
  362. return err
  363. })
  364. }
  365. func Publish(channel string, message any, context ...redis.Cmdable) error {
  366. if client == nil {
  367. return ErrDBNotInit
  368. }
  369. if _, ok := message.(string); !ok {
  370. message = parser.MarshalJson(message)
  371. }
  372. return getCmdable(context...).Publish(ctx, channel, message).Err()
  373. }
  374. func Subscribe[T any](channel string) (<-chan T, func()) {
  375. pubsub := client.Subscribe(ctx, channel)
  376. ch := make(chan T)
  377. connectionEstablished := make(chan bool)
  378. go func() {
  379. defer close(ch)
  380. defer close(connectionEstablished)
  381. alive := true
  382. for alive {
  383. iface, err := pubsub.Receive(context.Background())
  384. if err != nil {
  385. log.Error("failed to receive message from redis: %s, will retry in 1 second", err.Error())
  386. time.Sleep(1 * time.Second)
  387. continue
  388. }
  389. switch data := iface.(type) {
  390. case *redis.Subscription:
  391. connectionEstablished <- true
  392. case *redis.Message:
  393. v, err := parser.UnmarshalJson[T](data.Payload)
  394. if err != nil {
  395. continue
  396. }
  397. ch <- v
  398. case *redis.Pong:
  399. default:
  400. alive = false
  401. }
  402. }
  403. }()
  404. // wait for the connection to be established
  405. <-connectionEstablished
  406. return ch, func() {
  407. pubsub.Close()
  408. }
  409. }