Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(config): Implement notification system for Config #517

Merged
merged 3 commits into from
Feb 1, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions windows-agent/internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,9 @@ type Config struct {

// Sync
mu *sync.Mutex

// notifiers are called after any configuration changes.
notifiers []func()
CarlosNihelton marked this conversation as resolved.
Show resolved Hide resolved
}

// New creates and initializes a new Config object.
Expand All @@ -44,6 +47,11 @@ func New(ctx context.Context, cachePath string) (m *Config) {
return m
}

// Notify appends a callback. It'll be called very time any configuration changes.
EduardGomezEscandell marked this conversation as resolved.
Show resolved Hide resolved
func (c *Config) Notify(f func()) {
c.notifiers = append(c.notifiers, f)
}

// Subscription returns the ProToken and the method it was acquired with (if any).
func (c *Config) Subscription(ctx context.Context) (token string, source Source, err error) {
c.mu.Lock()
Expand Down Expand Up @@ -130,6 +138,10 @@ func (c *Config) set(ctx context.Context, field *string, value string) error {
old := *field
*field = value

for _, f := range c.notifiers {
go f()
CarlosNihelton marked this conversation as resolved.
Show resolved Hide resolved
}

if err := c.dump(); err != nil {
log.Errorf(ctx, "Could not update settings: %v", err)
*field = old
Expand Down Expand Up @@ -250,6 +262,10 @@ func (c *Config) collectRegistrySettingsTasks(ctx context.Context, data Registry
log.Warningf(ctx, "Could not obtain some updated registry settings: %v", errs)
}

for _, f := range c.notifiers {
go f()
CarlosNihelton marked this conversation as resolved.
Show resolved Hide resolved
}

// Dump updated checksums
if err := c.dump(); err != nil {
return nil, fmt.Errorf("could not store updated registry settings: %v", err)
Expand Down
78 changes: 78 additions & 0 deletions windows-agent/internal/config/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"net/url"
"os"
"path/filepath"
"sync/atomic"
"testing"
"time"

Expand Down Expand Up @@ -638,6 +639,83 @@ func loadChecksums(t *testing.T, confDir string) (string, string) {
return fileData.Subscription.Checksum, fileData.Landscape.Checksum
}

func TestNotify(t *testing.T) {
ctx := context.Background()
if wsl.MockAvailable() {
t.Parallel()
ctx = wsl.WithMock(ctx, wslmock.New())
}

db, err := database.New(ctx, t.TempDir(), nil)
require.NoError(t, err, "Setup: could not create empty database")

_, dir := setUpMockSettings(t, ctx, db, untouched, false)
c := config.New(ctx, dir)

var notifyCount atomic.Int32
var wantNotifyCount int32

c.Notify(func() { notifyCount.Add(1) })

err = c.SetUserSubscription(ctx, "TOKEN_1")
require.NoError(t, err, "SetUserSubscription should return no error")
wantNotifyCount++

eventually(t, notifyCount.Load, func(got int32) bool { return wantNotifyCount == got },
time.Second, 100*time.Millisecond, "Attached function should have been called after changing the pro token")

err = c.SetLandscapeAgentUID(ctx, "UID_1")
require.NoError(t, err, "SetLandscapeAgentUID should return no error")
wantNotifyCount++

eventually(t, notifyCount.Load, func(got int32) bool { return wantNotifyCount == got },
time.Second, 100*time.Millisecond, "Attached function should have been called after changing the landscape UID")

err = c.UpdateRegistryData(ctx, config.RegistryData{UbuntuProToken: "TOKEN_2"}, db)
require.NoError(t, err, "UpdateRegistryData should return no error")
wantNotifyCount++

eventually(t, notifyCount.Load, func(got int32) bool { return wantNotifyCount == got },
time.Second, 100*time.Millisecond, "Attached function should have been called after changing registry data")
}

// eventually solves the main issue with 'require.Eventually': you don't know what failed.
// See what happens if you try to build the 'want vs. got' error message:
//
// require.Eventuallyf(t, func()bool{ return 5==got() },
// t, trate, "Mismatch: wanted %d but got %d", 5, got())
// ^^^
// OUTDATED!
//
// Got is passed by value so we have the value obtained at t=0, not at t=timeout.
//
CarlosNihelton marked this conversation as resolved.
Show resolved Hide resolved
//nolint:thelper // This is not a helper but an assertion itself.
func eventually[T any](t *testing.T, getter func() T, predicate func(T) bool, timeout, tickRate time.Duration, message string, args ...any) {
tk := time.NewTicker(tickRate)
defer tk.Stop()

tm := time.NewTimer(timeout)
defer tk.Stop()

got := getter()
if predicate(got) {
return
}

for {
select {
case <-tm.C:
require.Failf(t, "Condition not satisfied", "Last value: %v\n%s", got, fmt.Sprintf(message, args...))
case <-tk.C:
}

got = getter()
if predicate(got) {
return
}
}
}

// is defines equality between flags. It is convenience function to check if a settingsState matches a certain state.
func (state settingsState) is(flag settingsState) bool {
return state&flag == flag
Expand Down
Loading