redis.go 10 KB

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