persistence.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package persistence
  2. import (
  3. "encoding/hex"
  4. "fmt"
  5. "time"
  6. "github.com/langgenius/dify-plugin-daemon/internal/utils/cache"
  7. )
  8. type Persistence struct {
  9. storage PersistenceStorage
  10. }
  11. const (
  12. CACHE_KEY_PREFIX = "persistence:cache"
  13. )
  14. func (c *Persistence) getCacheKey(tenant_id string, plugin_id string, key string) string {
  15. return fmt.Sprintf("%s:%s:%s:%s", CACHE_KEY_PREFIX, tenant_id, plugin_id, key)
  16. }
  17. func (c *Persistence) Save(tenant_id string, plugin_id string, key string, data []byte) error {
  18. if len(key) > 64 {
  19. return fmt.Errorf("key length must be less than 64 characters")
  20. }
  21. if err := c.storage.Save(tenant_id, plugin_id, key, data); err != nil {
  22. return err
  23. }
  24. // delete from cache
  25. return cache.Del(c.getCacheKey(tenant_id, plugin_id, key))
  26. }
  27. func (c *Persistence) Load(tenant_id string, plugin_id string, key string) ([]byte, error) {
  28. // check if the key exists in cache
  29. h, err := cache.GetString(c.getCacheKey(tenant_id, plugin_id, key))
  30. if err != nil && err != cache.ErrNotFound {
  31. return nil, err
  32. }
  33. if err == nil {
  34. return hex.DecodeString(h)
  35. }
  36. // load from storage
  37. data, err := c.storage.Load(tenant_id, plugin_id, key)
  38. if err != nil {
  39. return nil, err
  40. }
  41. // add to cache
  42. cache.Store(c.getCacheKey(tenant_id, plugin_id, key), hex.EncodeToString(data), time.Minute*5)
  43. return data, nil
  44. }
  45. func (c *Persistence) Delete(tenant_id string, plugin_id string, key string) error {
  46. // delete from cache and storage
  47. err := cache.Del(c.getCacheKey(tenant_id, plugin_id, key))
  48. if err != nil {
  49. return err
  50. }
  51. return c.storage.Delete(tenant_id, plugin_id, key)
  52. }