You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

81 lines
1.5 KiB

3 years ago
package watcher
import (
"context"
4 months ago
"errors"
3 years ago
"fmt"
4 months ago
"log/slog"
3 years ago
"time"
"gitoa.ru/go-4devs/config"
)
var (
_ config.Provider = (*Provider)(nil)
_ config.WatchProvider = (*Provider)(nil)
)
4 months ago
func New(duration time.Duration, provider config.Provider, opts ...Option) *Provider {
12 months ago
prov := &Provider{
4 months ago
Provider: provider,
duration: duration,
logger: slog.ErrorContext,
3 years ago
}
for _, opt := range opts {
12 months ago
opt(prov)
3 years ago
}
12 months ago
return prov
3 years ago
}
4 months ago
func WithLogger(l func(context.Context, string, ...any)) Option {
3 years ago
return func(p *Provider) {
p.logger = l
}
}
type Option func(*Provider)
type Provider struct {
4 months ago
config.Provider
duration time.Duration
logger func(context.Context, string, ...any)
3 years ago
}
func (p *Provider) Watch(ctx context.Context, callback config.WatchCallback, key ...string) error {
4 months ago
old, err := p.Provider.Value(ctx, key...)
3 years ago
if err != nil {
return fmt.Errorf("failed watch variable: %w", err)
3 years ago
}
4 months ago
go func(oldVar config.Value) {
ticker := time.NewTicker(p.duration)
defer func() {
ticker.Stop()
}()
3 years ago
for {
select {
4 months ago
case <-ticker.C:
newVar, err := p.Provider.Value(ctx, key...)
3 years ago
if err != nil {
4 months ago
p.logger(ctx, "get value%v:%v", key, err.Error())
3 years ago
} else if !newVar.IsEquals(oldVar) {
4 months ago
if err := callback(ctx, oldVar, newVar); err != nil {
if errors.Is(err, config.ErrStopWatch) {
return
}
p.logger(ctx, "callback %v:%v", key, err)
}
3 years ago
oldVar = newVar
}
case <-ctx.Done():
return
}
}
4 months ago
}(old)
3 years ago
return nil
}