persistence.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. package persistence
  2. import (
  3. "encoding/hex"
  4. "fmt"
  5. "github.com/langgenius/dify-plugin-daemon/internal/utils/cache"
  6. )
  7. type Persistence struct {
  8. storage PersistenceStorage
  9. }
  10. const (
  11. CACHE_KEY_PREFIX = "persistence:cache"
  12. )
  13. func (c *Persistence) getCacheKey(tenant_id string, plugin_checksum string) string {
  14. return fmt.Sprintf("%s:%s:%s", CACHE_KEY_PREFIX, tenant_id, plugin_checksum)
  15. }
  16. func (c *Persistence) Save(tenant_id string, plugin_checksum string, key string, data []byte) error {
  17. // add to cache
  18. h := hex.EncodeToString(data)
  19. return cache.SetMapOneField(c.getCacheKey(tenant_id, plugin_checksum), key, h)
  20. }
  21. func (c *Persistence) Load(tenant_id string, plugin_checksum string, key string) ([]byte, error) {
  22. // check if the key exists in cache
  23. h, err := cache.GetMapFieldString(c.getCacheKey(tenant_id, plugin_checksum), key)
  24. if err != nil && err != cache.ErrNotFound {
  25. return nil, err
  26. }
  27. if err == nil {
  28. return hex.DecodeString(h)
  29. }
  30. // load from storage
  31. return c.storage.Load(tenant_id, plugin_checksum, key)
  32. }
  33. func (c *Persistence) Delete(tenant_id string, plugin_checksum string, key string) error {
  34. // delete from cache and storage
  35. err := cache.DelMapField(c.getCacheKey(tenant_id, plugin_checksum), key)
  36. if err != nil {
  37. return err
  38. }
  39. return c.storage.Delete(tenant_id, plugin_checksum, key)
  40. }