File size: 1,748 Bytes
d6f631f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package adapter

import (
	"errors"
	"log/slog"
	"time"

	"github.com/redis/go-redis/v9"

	"github.com/openmeterio/openmeter/openmeter/progressmanager"
)

type Config struct {
	Expiration time.Duration
	Redis      *redis.Client
	Logger     *slog.Logger
	KeyPrefix  string
}

func (c Config) Validate() error {
	if c.Expiration <= 0 {
		return errors.New("expiration must be greater than 0")
	}

	if c.Redis == nil {
		return errors.New("redis client is required")
	}

	if c.Logger == nil {
		return errors.New("logger must not be nil")
	}

	return nil
}

func New(config Config) (progressmanager.Adapter, error) {
	if err := config.Validate(); err != nil {
		return nil, err
	}

	return &adapter{
		expiration: config.Expiration,
		redis:      config.Redis,
		logger:     config.Logger,
		keyPrefix:  config.KeyPrefix,
	}, nil
}

var _ progressmanager.Adapter = (*adapter)(nil)

type adapter struct {
	// keyPrefix is the prefix for progress data in the Redis store, if needed, the key format will be "<keyPrefix>:progress:<namespace>:<id>" or "progress:<namespace>:<id>" if the prefix is empty
	keyPrefix string
	// expiration defines how long progress data is stored in Redis before automatic removal
	expiration time.Duration
	// redis is the client for storing and retrieving progress data
	redis *redis.Client
	// logger is used for logging errors and debug information
	logger *slog.Logger
}

// NewNoop creates a no-operation adapter that implements the progressmanager.Adapter interface
// but performs no actual operations. This is useful for testing or when progress tracking
// is disabled.
func NewNoop() progressmanager.Adapter {
	return &adapterNoop{}
}

var _ progressmanager.Adapter = (*adapterNoop)(nil)

type adapterNoop struct{}