redis.go 11 KB

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