summaryrefslogtreecommitdiff
path: root/internal/controlplane/manager_test.go
blob: 8dd4012ac74f3396170676db154ddd9b845b6167 (plain)
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
package controlplane

import (
	"bytes"
	"context"
	"errors"
	"log/slog"
	"strings"
	"sync"
	"sync/atomic"
	"testing"
	"time"

	"aigw/internal/auth"
	"aigw/internal/catalog"
)

type fakeManagerStore struct {
	redisEnabled       bool
	snapshot           atomic.Value
	databaseGeneration atomic.Int64
	publishCalls       atomic.Int64
	subscribeCalls     atomic.Int64
	publishErr         error
	published          chan ChangeEvent
	subscribe          func(context.Context, int64) (<-chan ChangeMessage, func() error, error)
}

type safeLogBuffer struct {
	mu  sync.Mutex
	buf bytes.Buffer
}

func (b *safeLogBuffer) Write(data []byte) (int, error) {
	b.mu.Lock()
	defer b.mu.Unlock()
	return b.buf.Write(data)
}

func (b *safeLogBuffer) String() string {
	b.mu.Lock()
	defer b.mu.Unlock()
	return b.buf.String()
}

func newFakeManagerStore(generation int64) *fakeManagerStore {
	store := &fakeManagerStore{published: make(chan ChangeEvent, 8)}
	store.snapshot.Store(Snapshot{Generation: generation})
	store.databaseGeneration.Store(generation)
	return store
}

func (s *fakeManagerStore) LoadSnapshot(context.Context) (Snapshot, error) {
	return s.snapshot.Load().(Snapshot), nil
}

func (s *fakeManagerStore) DatabaseGeneration(context.Context) (int64, error) {
	return s.databaseGeneration.Load(), nil
}

func (s *fakeManagerStore) PublishChange(_ context.Context, event ChangeEvent) error {
	s.publishCalls.Add(1)
	s.published <- event
	return s.publishErr
}

func (s *fakeManagerStore) Subscribe(ctx context.Context) (<-chan ChangeMessage, func() error, error) {
	call := s.subscribeCalls.Add(1)
	if s.subscribe != nil {
		return s.subscribe(ctx, call)
	}
	channel := make(chan ChangeMessage)
	return channel, func() error { return nil }, nil
}

func (s *fakeManagerStore) RedisEnabled() bool {
	return s.redisEnabled
}

func newTestManager(store managerStore, logger *slog.Logger, interval time.Duration) *Manager {
	return NewManager(store, catalog.NewModels(nil), auth.NewDynamic(nil, false), logger, interval)
}

func TestAfterMutationReloadsLocallyWhenRedisPublishFails(t *testing.T) {
	store := newFakeManagerStore(7)
	store.redisEnabled = true
	store.publishErr = errors.New("redis unavailable")
	var logs safeLogBuffer
	manager := newTestManager(store, slog.New(slog.NewTextHandler(&logs, nil)), 10*time.Millisecond)
	ctx, cancel := context.WithCancel(context.Background())
	done := make(chan struct{})
	go func() {
		manager.Run(ctx)
		close(done)
	}()

	if err := manager.AfterMutation(context.Background(), 7, "model", "model-1"); err != nil {
		t.Fatalf("mutation unexpectedly failed: %v", err)
	}
	if manager.Generation() != 7 {
		t.Fatalf("local generation = %d, want 7", manager.Generation())
	}
	select {
	case event := <-store.published:
		if event.Generation != 7 || event.Resource != "model" {
			t.Fatalf("unexpected event: %+v", event)
		}
	case <-time.After(time.Second):
		t.Fatal("broadcast was not attempted")
	}
	waitUntil(t, time.Second, func() bool { return strings.Contains(logs.String(), "control_plane_publish_failed") })

	cancel()
	select {
	case <-done:
	case <-time.After(time.Second):
		t.Fatal("manager did not stop")
	}
}

func TestPollingContinuesWhileRedisSubscribeIsBlocked(t *testing.T) {
	store := newFakeManagerStore(1)
	store.redisEnabled = true
	store.subscribe = func(ctx context.Context, _ int64) (<-chan ChangeMessage, func() error, error) {
		<-ctx.Done()
		return nil, nil, ctx.Err()
	}
	manager := newTestManager(store, slog.New(slog.NewTextHandler(&safeLogBuffer{}, nil)), 10*time.Millisecond)
	if _, err := manager.Reload(context.Background()); err != nil {
		t.Fatal(err)
	}

	ctx, cancel := context.WithCancel(context.Background())
	done := make(chan struct{})
	go func() {
		manager.Run(ctx)
		close(done)
	}()
	store.snapshot.Store(Snapshot{Generation: 2})
	store.databaseGeneration.Store(2)
	waitUntil(t, time.Second, func() bool { return manager.Generation() == 2 })

	cancel()
	select {
	case <-done:
	case <-time.After(time.Second):
		t.Fatal("manager did not stop")
	}
}

func TestSubscriptionReconnectsAfterChannelCloses(t *testing.T) {
	store := newFakeManagerStore(1)
	store.redisEnabled = true
	first := make(chan ChangeMessage)
	second := make(chan ChangeMessage, 1)
	store.subscribe = func(_ context.Context, call int64) (<-chan ChangeMessage, func() error, error) {
		if call == 1 {
			return first, func() error { return nil }, nil
		}
		return second, func() error { return nil }, nil
	}
	manager := newTestManager(store, slog.New(slog.NewTextHandler(&safeLogBuffer{}, nil)), 10*time.Millisecond)
	if _, err := manager.Reload(context.Background()); err != nil {
		t.Fatal(err)
	}

	ctx, cancel := context.WithCancel(context.Background())
	done := make(chan struct{})
	go func() {
		manager.Run(ctx)
		close(done)
	}()
	waitUntil(t, time.Second, func() bool { return store.subscribeCalls.Load() == 1 })
	close(first)
	waitUntil(t, time.Second, func() bool { return store.subscribeCalls.Load() >= 2 && manager.RedisConnected() })
	store.snapshot.Store(Snapshot{Generation: 2})
	second <- ChangeMessage{Payload: `{"generation":2,"resource":"model"}`}
	waitUntil(t, time.Second, func() bool { return manager.Generation() == 2 })

	cancel()
	select {
	case <-done:
	case <-time.After(time.Second):
		t.Fatal("manager did not stop")
	}
}

func TestRedisCanBeDisabled(t *testing.T) {
	store := newFakeManagerStore(3)
	manager := newTestManager(store, slog.New(slog.NewTextHandler(&bytes.Buffer{}, nil)), 10*time.Millisecond)
	if err := manager.AfterMutation(context.Background(), 3, "tenant", "tenant-1"); err != nil {
		t.Fatal(err)
	}
	if manager.RedisConfigured() || manager.RedisConnected() {
		t.Fatal("Redis unexpectedly reported as available")
	}
	if store.publishCalls.Load() != 0 || store.subscribeCalls.Load() != 0 {
		t.Fatal("Redis operations were attempted while disabled")
	}
}

func waitUntil(t *testing.T, timeout time.Duration, condition func() bool) {
	t.Helper()
	deadline := time.Now().Add(timeout)
	for time.Now().Before(deadline) {
		if condition() {
			return
		}
		time.Sleep(5 * time.Millisecond)
	}
	t.Fatal("condition was not met before timeout")
}