redis.go 10 KB

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