feat: working version

1. implemented filesystem storage, NATS object storage
and saving to Vault.
2. Test coverage is fine for filesystem and Vault
(and NATS object does not really require extensive tests)
This commit is contained in:
2025-07-27 19:02:05 +03:00
parent 854de3865b
commit 48878e8433
13 changed files with 265 additions and 153 deletions

View File

@@ -5,32 +5,26 @@ import (
"encoding/base64"
"errors"
"code.uint32.ru/tiny/storage/internal/errinternal"
"github.com/hashicorp/vault/api"
)
var (
ErrNotFound = errinternal.ErrNotFound
)
type Storage struct {
client *api.Client
path string
kv *api.KVv1
// TODO: kv2: *api.KVv2
}
func Open(token string, path string, addr string) (*Storage, error) {
conf := &api.Config{
Address: addr,
}
c, err := api.NewClient(conf)
if err != nil {
return nil, err
}
c.SetToken(token)
return &Storage{client: c, path: path}, nil
// New returns Storage writing to the specified vault path.
// Object will be base64 encoded and written to path/key.
func New(c *api.Client, path string) *Storage {
return &Storage{kv: c.KVv1(path)}
}
func (s *Storage) Save(key string, data []byte) error {
kv := s.client.KVv1(s.path)
str := base64.StdEncoding.EncodeToString(data)
m := map[string]any{
"data": map[string]string{
@@ -38,7 +32,7 @@ func (s *Storage) Save(key string, data []byte) error {
},
}
if err := kv.Put(context.Background(), "testkey", m); err != nil {
if err := s.kv.Put(context.Background(), "testkey", m); err != nil {
return err
}
@@ -46,10 +40,10 @@ func (s *Storage) Save(key string, data []byte) error {
}
func (s *Storage) Load(key string) ([]byte, error) {
kv := s.client.KVv1(s.path)
m, err := kv.Get(context.Background(), key)
if err != nil {
m, err := s.kv.Get(context.Background(), key)
if err != nil && errors.Is(err, api.ErrSecretNotFound) {
return nil, errors.Join(ErrNotFound, err)
} else if err != nil {
return nil, err
}
@@ -84,16 +78,9 @@ func (s *Storage) Load(key string) ([]byte, error) {
}
func (s *Storage) Delete(key string) error {
kv := s.client.KVv1(s.path)
if err := kv.Delete(context.Background(), key); err != nil {
if err := s.kv.Delete(context.Background(), key); err != nil {
return err
}
return nil
}
func (s *Storage) Close() error {
s.client.ClearToken()
return nil
}

View File

@@ -4,6 +4,8 @@ import (
"bytes"
"os"
"testing"
"code.uint32.ru/tiny/storage/storageutil"
)
func TestVaultStorage(t *testing.T) {
@@ -25,7 +27,9 @@ func TestVaultStorage(t *testing.T) {
t.Log(addr)
t.Log(path)
st, err := Open(token, path, addr)
client, err := storageutil.NewVaultApiClient(token, addr)
st := New(client, path)
if err != nil {
t.Fatal(err)
}