49 lines
1.1 KiB
Go
49 lines
1.1 KiB
Go
package store
|
|
|
|
import (
|
|
"context"
|
|
"crypto/rand"
|
|
"encoding/hex"
|
|
"fmt"
|
|
"time"
|
|
|
|
"github.com/redis/go-redis/v9"
|
|
)
|
|
|
|
// TTL is how long any stored file lives in Redis before automatic deletion.
|
|
const TTL = 2 * time.Hour
|
|
|
|
type Store struct {
|
|
rdb *redis.Client
|
|
}
|
|
|
|
func New(addr string) (*Store, error) {
|
|
rdb := redis.NewClient(&redis.Options{Addr: addr})
|
|
if err := rdb.Ping(context.Background()).Err(); err != nil {
|
|
return nil, fmt.Errorf("redis connect %s: %w", addr, err)
|
|
}
|
|
return &Store{rdb: rdb}, nil
|
|
}
|
|
|
|
// Set stores binary data under key with the global TTL.
|
|
func (s *Store) Set(ctx context.Context, key string, data []byte) error {
|
|
return s.rdb.Set(ctx, key, data, TTL).Err()
|
|
}
|
|
|
|
// Get retrieves binary data by key.
|
|
func (s *Store) Get(ctx context.Context, key string) ([]byte, error) {
|
|
return s.rdb.Get(ctx, key).Bytes()
|
|
}
|
|
|
|
// Delete removes a key immediately (called after download).
|
|
func (s *Store) Delete(ctx context.Context, key string) {
|
|
s.rdb.Del(ctx, key)
|
|
}
|
|
|
|
// NewID generates a random hex ID for use as a Redis key suffix.
|
|
func NewID() string {
|
|
b := make([]byte, 16)
|
|
rand.Read(b)
|
|
return hex.EncodeToString(b)
|
|
}
|