local_storage.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. package local
  2. import (
  3. "io/fs"
  4. "log"
  5. "os"
  6. "path/filepath"
  7. "strings"
  8. "github.com/langgenius/dify-plugin-daemon/internal/oss"
  9. )
  10. type LocalStorage struct {
  11. root string
  12. }
  13. func NewLocalStorage(root string) oss.OSS {
  14. if err := os.MkdirAll(root, 0o755); err != nil {
  15. log.Panicf("Failed to create storage path: %s", err)
  16. }
  17. return &LocalStorage{root: root}
  18. }
  19. func (l *LocalStorage) Save(key string, data []byte) error {
  20. path := filepath.Join(l.root, key)
  21. filePath := filepath.Dir(path)
  22. if err := os.MkdirAll(filePath, 0o755); err != nil {
  23. return err
  24. }
  25. return os.WriteFile(path, data, 0o644)
  26. }
  27. func (l *LocalStorage) Load(key string) ([]byte, error) {
  28. path := filepath.Join(l.root, key)
  29. return os.ReadFile(path)
  30. }
  31. func (l *LocalStorage) Exists(key string) (bool, error) {
  32. path := filepath.Join(l.root, key)
  33. _, err := os.Stat(path)
  34. return err == nil, nil
  35. }
  36. func (l *LocalStorage) State(key string) (oss.OSSState, error) {
  37. path := filepath.Join(l.root, key)
  38. info, err := os.Stat(path)
  39. if err != nil {
  40. return oss.OSSState{}, err
  41. }
  42. return oss.OSSState{Size: info.Size(), LastModified: info.ModTime()}, nil
  43. }
  44. func (l *LocalStorage) List(prefix string) ([]oss.OSSPath, error) {
  45. paths := make([]oss.OSSPath, 0)
  46. // check if the patch exists
  47. exists, err := l.Exists(prefix)
  48. if err != nil {
  49. return nil, err
  50. }
  51. if !exists {
  52. return paths, nil
  53. }
  54. prefix = filepath.Join(l.root, prefix)
  55. err = filepath.WalkDir(prefix, func(path string, d fs.DirEntry, err error) error {
  56. if err != nil {
  57. return err
  58. }
  59. // remove prefix
  60. path = strings.TrimPrefix(path, prefix)
  61. if path == "" {
  62. return nil
  63. }
  64. // remove leading slash
  65. path = strings.TrimPrefix(path, "/")
  66. paths = append(paths, oss.OSSPath{
  67. Path: path,
  68. IsDir: d.IsDir(),
  69. })
  70. return nil
  71. })
  72. if err != nil {
  73. return nil, err
  74. }
  75. return paths, nil
  76. }
  77. func (l *LocalStorage) Delete(key string) error {
  78. path := filepath.Join(l.root, key)
  79. return os.RemoveAll(path)
  80. }