persistence.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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_identity string, key string) string {
  15. return fmt.Sprintf("%s:%s:%s:%s", CACHE_KEY_PREFIX, tenant_id, plugin_identity, key)
  16. }
  17. func (c *Persistence) Save(tenant_id string, plugin_identity 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. return c.storage.Save(tenant_id, plugin_identity, key, data)
  22. }
  23. func (c *Persistence) Load(tenant_id string, plugin_identity string, key string) ([]byte, error) {
  24. // check if the key exists in cache
  25. h, err := cache.GetString(c.getCacheKey(tenant_id, plugin_identity, key))
  26. if err != nil && err != cache.ErrNotFound {
  27. return nil, err
  28. }
  29. if err == nil {
  30. return hex.DecodeString(h)
  31. }
  32. // load from storage
  33. data, err := c.storage.Load(tenant_id, plugin_identity, key)
  34. if err != nil {
  35. return nil, err
  36. }
  37. // add to cache
  38. cache.Store(c.getCacheKey(tenant_id, plugin_identity, key), hex.EncodeToString(data), time.Minute*5)
  39. return data, nil
  40. }
  41. func (c *Persistence) Delete(tenant_id string, plugin_identity string, key string) error {
  42. // delete from cache and storage
  43. err := cache.Del(c.getCacheKey(tenant_id, plugin_identity, key))
  44. if err != nil {
  45. return err
  46. }
  47. return c.storage.Delete(tenant_id, plugin_identity, key)
  48. }