redis.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  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. // GetMapFieldString get the string
  168. func GetMapFieldString(key string, field string, context ...redis.Cmdable) (string, error) {
  169. if client == nil {
  170. return "", ErrDBNotInit
  171. }
  172. val, err := getCmdable(context...).HGet(ctx, serialKey(key), field).Result()
  173. if err != nil {
  174. if err == redis.Nil {
  175. return "", ErrNotFound
  176. }
  177. return "", err
  178. }
  179. return val, nil
  180. }
  181. // DelMapField delete the map field with key
  182. func DelMapField(key string, field string, context ...redis.Cmdable) error {
  183. if client == nil {
  184. return ErrDBNotInit
  185. }
  186. return getCmdable(context...).HDel(ctx, serialKey(key), field).Err()
  187. }
  188. // GetMap get the map with key
  189. func GetMap[V any](key string, context ...redis.Cmdable) (map[string]V, error) {
  190. if client == nil {
  191. return nil, ErrDBNotInit
  192. }
  193. val, err := getCmdable(context...).HGetAll(ctx, serialKey(key)).Result()
  194. if err != nil {
  195. if err == redis.Nil {
  196. return nil, ErrNotFound
  197. }
  198. return nil, err
  199. }
  200. result := make(map[string]V)
  201. for k, v := range val {
  202. value, err := parser.UnmarshalJson[V](v)
  203. if err != nil {
  204. continue
  205. }
  206. result[k] = value
  207. }
  208. return result, nil
  209. }
  210. // ScanKeys scan the keys with match pattern
  211. func ScanKeys(match string, context ...redis.Cmdable) ([]string, error) {
  212. if client == nil {
  213. return nil, ErrDBNotInit
  214. }
  215. result := make([]string, 0)
  216. if err := ScanKeysAsync(match, func(keys []string) error {
  217. result = append(result, keys...)
  218. return nil
  219. }); err != nil {
  220. return nil, err
  221. }
  222. return result, nil
  223. }
  224. // ScanKeysAsync scan the keys with match pattern, format like "key*"
  225. func ScanKeysAsync(match string, fn func([]string) error, context ...redis.Cmdable) error {
  226. if client == nil {
  227. return ErrDBNotInit
  228. }
  229. cursor := uint64(0)
  230. for {
  231. keys, newCursor, err := getCmdable(context...).Scan(ctx, cursor, match, 32).Result()
  232. if err != nil {
  233. return err
  234. }
  235. if err := fn(keys); err != nil {
  236. return err
  237. }
  238. if newCursor == 0 {
  239. break
  240. }
  241. cursor = newCursor
  242. }
  243. return nil
  244. }
  245. // ScanMap scan the map with match pattern, format like "key*"
  246. func ScanMap[V any](key string, match string, context ...redis.Cmdable) (map[string]V, error) {
  247. if client == nil {
  248. return nil, ErrDBNotInit
  249. }
  250. result := make(map[string]V)
  251. ScanMapAsync[V](key, match, func(m map[string]V) error {
  252. for k, v := range m {
  253. result[k] = v
  254. }
  255. return nil
  256. })
  257. return result, nil
  258. }
  259. // ScanMapAsync scan the map with match pattern, format like "key*"
  260. func ScanMapAsync[V any](key string, match string, fn func(map[string]V) error, context ...redis.Cmdable) error {
  261. if client == nil {
  262. return ErrDBNotInit
  263. }
  264. cursor := uint64(0)
  265. for {
  266. kvs, newCursor, err := getCmdable(context...).
  267. HScan(ctx, serialKey(key), cursor, match, 32).
  268. Result()
  269. if err != nil {
  270. return err
  271. }
  272. result := make(map[string]V)
  273. for i := 0; i < len(kvs); i += 2 {
  274. value, err := parser.UnmarshalJson[V](kvs[i+1])
  275. if err != nil {
  276. continue
  277. }
  278. result[kvs[i]] = value
  279. }
  280. if err := fn(result); err != nil {
  281. return err
  282. }
  283. if newCursor == 0 {
  284. break
  285. }
  286. cursor = newCursor
  287. }
  288. return nil
  289. }
  290. // SetNX set the key-value pair with expire time
  291. func SetNX[T any](key string, value T, expire time.Duration, context ...redis.Cmdable) (bool, error) {
  292. if client == nil {
  293. return false, ErrDBNotInit
  294. }
  295. return getCmdable(context...).SetNX(ctx, serialKey(key), value, expire).Result()
  296. }
  297. var (
  298. ErrLockTimeout = errors.New("lock timeout")
  299. )
  300. // Lock key, expire time takes responsibility for expiration time
  301. // try_lock_timeout takes responsibility for the timeout of trying to lock
  302. func Lock(key string, expire time.Duration, tryLockTimeout time.Duration, context ...redis.Cmdable) error {
  303. if client == nil {
  304. return ErrDBNotInit
  305. }
  306. const LOCK_DURATION = 20 * time.Millisecond
  307. ticker := time.NewTicker(LOCK_DURATION)
  308. defer ticker.Stop()
  309. for range ticker.C {
  310. if _, err := getCmdable(context...).SetNX(ctx, serialKey(key), "1", expire).Result(); err == nil {
  311. return nil
  312. }
  313. tryLockTimeout -= LOCK_DURATION
  314. if tryLockTimeout <= 0 {
  315. return ErrLockTimeout
  316. }
  317. }
  318. return nil
  319. }
  320. func Unlock(key string, context ...redis.Cmdable) error {
  321. if client == nil {
  322. return ErrDBNotInit
  323. }
  324. return getCmdable(context...).Del(ctx, serialKey(key)).Err()
  325. }
  326. func Expire(key string, time time.Duration, context ...redis.Cmdable) (bool, error) {
  327. if client == nil {
  328. return false, ErrDBNotInit
  329. }
  330. return getCmdable(context...).Expire(ctx, serialKey(key), time).Result()
  331. }
  332. func Transaction(fn func(redis.Pipeliner) error) error {
  333. if client == nil {
  334. return ErrDBNotInit
  335. }
  336. return client.Watch(ctx, func(tx *redis.Tx) error {
  337. _, err := tx.TxPipelined(ctx, func(p redis.Pipeliner) error {
  338. return fn(p)
  339. })
  340. if err == redis.Nil {
  341. return nil
  342. }
  343. return err
  344. })
  345. }
  346. func Publish(channel string, message any, context ...redis.Cmdable) error {
  347. if client == nil {
  348. return ErrDBNotInit
  349. }
  350. if _, ok := message.(string); !ok {
  351. message = parser.MarshalJson(message)
  352. }
  353. return getCmdable(context...).Publish(ctx, channel, message).Err()
  354. }
  355. func Subscribe[T any](channel string) (<-chan T, func()) {
  356. pubsub := client.Subscribe(ctx, channel)
  357. ch := make(chan T)
  358. connectionEstablished := make(chan bool)
  359. go func() {
  360. defer close(ch)
  361. defer close(connectionEstablished)
  362. alive := true
  363. for alive {
  364. iface, err := pubsub.Receive(context.Background())
  365. if err != nil {
  366. alive = false
  367. break
  368. }
  369. switch data := iface.(type) {
  370. case *redis.Subscription:
  371. connectionEstablished <- true
  372. case *redis.Message:
  373. v, err := parser.UnmarshalJson[T](data.Payload)
  374. if err != nil {
  375. continue
  376. }
  377. ch <- v
  378. case *redis.Pong:
  379. default:
  380. alive = false
  381. }
  382. }
  383. }()
  384. // wait for the connection to be established
  385. <-connectionEstablished
  386. return ch, func() {
  387. pubsub.Close()
  388. }
  389. }