storage.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package pricing
  2. import (
  3. "context"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "github.com/opencost/opencost/core/pkg/storage"
  8. )
  9. type StoragePricingStore struct {
  10. store storage.Storage
  11. path string
  12. }
  13. func NewStoragePricingStore(ctx context.Context, store storage.Storage, path string) (*StoragePricingStore, error) {
  14. if store == nil {
  15. return nil, errors.New("nil storage")
  16. }
  17. if path == "" {
  18. return nil, errors.New("empty path")
  19. }
  20. sps := &StoragePricingStore{
  21. store: store,
  22. path: path,
  23. }
  24. exists, err := store.Exists(path)
  25. if err != nil {
  26. return nil, fmt.Errorf("checking pricing path %q: %w", path, err)
  27. }
  28. if !exists {
  29. if err := sps.SetPricingSet(ctx, &PricingSet{}); err != nil {
  30. return nil, fmt.Errorf("initializing empty pricing set at %q: %w", path, err)
  31. }
  32. }
  33. return sps, nil
  34. }
  35. func (sps *StoragePricingStore) GetPricingSet(ctx context.Context) (*PricingSet, error) {
  36. data, err := sps.store.Read(sps.path)
  37. if err != nil {
  38. return nil, fmt.Errorf("reading path '%s': %w", sps.path, err)
  39. }
  40. var pricing PricingSet
  41. err = json.Unmarshal(data, &pricing)
  42. if err != nil {
  43. return nil, fmt.Errorf("decoding pricing: %w", err)
  44. }
  45. return &pricing, nil
  46. }
  47. func (sps *StoragePricingStore) SetPricingSet(ctx context.Context, pricing *PricingSet) error {
  48. if pricing == nil {
  49. return errors.New("nil pricing")
  50. }
  51. data, err := json.Marshal(pricing)
  52. if err != nil {
  53. return fmt.Errorf("encoding pricing: %w", err)
  54. }
  55. err = sps.store.Write(sps.path, data)
  56. if err != nil {
  57. return fmt.Errorf("writing pricing: %w", err)
  58. }
  59. return nil
  60. }