summaryrefslogtreecommitdiffhomepage
path: root/util/syspolicy/source/test_store.go
blob: 1baa138319337dfc6eca7f58eda6d4d41d696501 (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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
// Copyright (c) Tailscale Inc & contributors
// SPDX-License-Identifier: BSD-3-Clause

package source

import (
	"fmt"
	"sync"
	"sync/atomic"

	xmaps "golang.org/x/exp/maps"
	"tailscale.com/util/mak"
	"tailscale.com/util/set"
	"tailscale.com/util/slicesx"
	"tailscale.com/util/syspolicy/pkey"
	"tailscale.com/util/syspolicy/setting"
	"tailscale.com/util/testenv"
)

var (
	_ Store      = (*TestStore)(nil)
	_ Lockable   = (*TestStore)(nil)
	_ Changeable = (*TestStore)(nil)
	_ Expirable  = (*TestStore)(nil)
)

// TestValueType is a constraint that allows types supported by [TestStore].
type TestValueType interface {
	bool | uint64 | string | []string
}

// TestSetting is a policy setting in a [TestStore].
type TestSetting[T TestValueType] struct {
	// Key is the setting's unique identifier.
	Key pkey.Key
	// Error is the error to be returned by the [TestStore] when reading
	// a policy setting with the specified key.
	Error error
	// Value is the value to be returned by the [TestStore] when reading
	// a policy setting with the specified key.
	// It is only used if the Error is nil.
	Value T
}

// TestSettingOf returns a [TestSetting] representing a policy setting
// configured with the specified key and value.
func TestSettingOf[T TestValueType](key pkey.Key, value T) TestSetting[T] {
	return TestSetting[T]{Key: key, Value: value}
}

// TestSettingWithError returns a [TestSetting] representing a policy setting
// with the specified key and error.
func TestSettingWithError[T TestValueType](key pkey.Key, err error) TestSetting[T] {
	return TestSetting[T]{Key: key, Error: err}
}

// testReadOperation describes a single policy setting read operation.
type testReadOperation struct {
	// Key is the setting's unique identifier.
	Key pkey.Key
	// Type is a value type of a read operation.
	// [setting.BooleanValue], [setting.IntegerValue], [setting.StringValue] or [setting.StringListValue]
	Type setting.Type
}

// TestExpectedReads is the number of read operations with the specified details.
type TestExpectedReads struct {
	// Key is the setting's unique identifier.
	Key pkey.Key
	// Type is a value type of a read operation.
	// [setting.BooleanValue], [setting.IntegerValue], [setting.StringValue] or [setting.StringListValue]
	Type setting.Type
	// NumTimes is how many times a setting with the specified key and type should have been read.
	NumTimes int
}

func (r TestExpectedReads) operation() testReadOperation {
	return testReadOperation{r.Key, r.Type}
}

// TestStore is a [Store] that can be used in tests.
type TestStore struct {
	tb testenv.TB

	done chan struct{}

	storeLock      sync.RWMutex // its RLock is exposed via [Store.Lock]/[Store.Unlock].
	storeLockCount atomic.Int32

	mu           sync.RWMutex
	suspendCount int              // change callback are suspended if > 0
	mr, mw       map[pkey.Key]any // maps for reading and writing; they're the same unless the store is suspended.
	cbs          set.HandleSet[func()]
	closed       bool

	readsMu sync.Mutex
	reads   map[testReadOperation]int // how many times a policy setting was read
}

// NewTestStore returns a new [TestStore].
// The tb will be used to report coding errors detected by the [TestStore].
func NewTestStore(tb testenv.TB) *TestStore {
	m := make(map[pkey.Key]any)
	store := &TestStore{
		tb:   tb,
		done: make(chan struct{}),
		mr:   m,
		mw:   m,
	}
	tb.Cleanup(store.Close)
	return store
}

// NewTestStoreOf is a shorthand for [NewTestStore] followed by [TestStore.SetBooleans],
// [TestStore.SetUInt64s], [TestStore.SetStrings] or [TestStore.SetStringLists].
func NewTestStoreOf[T TestValueType](tb testenv.TB, settings ...TestSetting[T]) *TestStore {
	store := NewTestStore(tb)
	switch settings := any(settings).(type) {
	case []TestSetting[bool]:
		store.SetBooleans(settings...)
	case []TestSetting[uint64]:
		store.SetUInt64s(settings...)
	case []TestSetting[string]:
		store.SetStrings(settings...)
	case []TestSetting[[]string]:
		store.SetStringLists(settings...)
	}
	return store
}

// Lock implements [Lockable].
func (s *TestStore) Lock() error {
	s.storeLock.RLock()
	s.storeLockCount.Add(1)
	return nil
}

// Unlock implements [Lockable].
func (s *TestStore) Unlock() {
	if s.storeLockCount.Add(-1) < 0 {
		s.tb.Fatal("negative storeLockCount")
	}
	s.storeLock.RUnlock()
}

// RegisterChangeCallback implements [Changeable].
func (s *TestStore) RegisterChangeCallback(callback func()) (unregister func(), err error) {
	s.mu.Lock()
	defer s.mu.Unlock()
	handle := s.cbs.Add(callback)
	return func() {
		s.mu.Lock()
		defer s.mu.Unlock()
		delete(s.cbs, handle)
	}, nil
}

// IsEmpty reports whether the store does not contain any settings.
func (s *TestStore) IsEmpty() bool {
	s.mu.RLock()
	defer s.mu.RUnlock()
	return len(s.mr) == 0
}

// ReadString implements [Store].
func (s *TestStore) ReadString(key pkey.Key) (string, error) {
	defer s.recordRead(key, setting.StringValue)
	s.mu.RLock()
	defer s.mu.RUnlock()
	v, ok := s.mr[key]
	if !ok {
		return "", setting.ErrNotConfigured
	}
	if err, ok := v.(error); ok {
		return "", err
	}
	str, ok := v.(string)
	if !ok {
		return "", fmt.Errorf("%w in ReadString: got %T", setting.ErrTypeMismatch, v)
	}
	return str, nil
}

// ReadUInt64 implements [Store].
func (s *TestStore) ReadUInt64(key pkey.Key) (uint64, error) {
	defer s.recordRead(key, setting.IntegerValue)
	s.mu.RLock()
	defer s.mu.RUnlock()
	v, ok := s.mr[key]
	if !ok {
		return 0, setting.ErrNotConfigured
	}
	if err, ok := v.(error); ok {
		return 0, err
	}
	u64, ok := v.(uint64)
	if !ok {
		return 0, fmt.Errorf("%w in ReadUInt64: got %T", setting.ErrTypeMismatch, v)
	}
	return u64, nil
}

// ReadBoolean implements [Store].
func (s *TestStore) ReadBoolean(key pkey.Key) (bool, error) {
	defer s.recordRead(key, setting.BooleanValue)
	s.mu.RLock()
	defer s.mu.RUnlock()
	v, ok := s.mr[key]
	if !ok {
		return false, setting.ErrNotConfigured
	}
	if err, ok := v.(error); ok {
		return false, err
	}
	b, ok := v.(bool)
	if !ok {
		return false, fmt.Errorf("%w in ReadBoolean: got %T", setting.ErrTypeMismatch, v)
	}
	return b, nil
}

// ReadStringArray implements [Store].
func (s *TestStore) ReadStringArray(key pkey.Key) ([]string, error) {
	defer s.recordRead(key, setting.StringListValue)
	s.mu.RLock()
	defer s.mu.RUnlock()
	v, ok := s.mr[key]
	if !ok {
		return nil, setting.ErrNotConfigured
	}
	if err, ok := v.(error); ok {
		return nil, err
	}
	slice, ok := v.([]string)
	if !ok {
		return nil, fmt.Errorf("%w in ReadStringArray: got %T", setting.ErrTypeMismatch, v)
	}
	return slice, nil
}

func (s *TestStore) recordRead(key pkey.Key, typ setting.Type) {
	s.readsMu.Lock()
	op := testReadOperation{key, typ}
	num := s.reads[op]
	num++
	mak.Set(&s.reads, op, num)
	s.readsMu.Unlock()
}

func (s *TestStore) ResetCounters() {
	s.readsMu.Lock()
	clear(s.reads)
	s.readsMu.Unlock()
}

// ReadsMustEqual fails the test if the actual reads differs from the specified reads.
func (s *TestStore) ReadsMustEqual(reads ...TestExpectedReads) {
	s.tb.Helper()
	s.readsMu.Lock()
	defer s.readsMu.Unlock()
	s.readsMustContainLocked(reads...)
	s.readMustNoExtraLocked(reads...)
}

// ReadsMustContain fails the test if the specified reads have not been made,
// or have been made a different number of times. It permits other values to be
// read in addition to the ones being tested.
func (s *TestStore) ReadsMustContain(reads ...TestExpectedReads) {
	s.tb.Helper()
	s.readsMu.Lock()
	defer s.readsMu.Unlock()
	s.readsMustContainLocked(reads...)
}

func (s *TestStore) readsMustContainLocked(reads ...TestExpectedReads) {
	s.tb.Helper()
	for _, r := range reads {
		if numTimes := s.reads[r.operation()]; numTimes != r.NumTimes {
			s.tb.Errorf("%q (%v) reads: got %v, want %v", r.Key, r.Type, numTimes, r.NumTimes)
		}
	}
}

func (s *TestStore) readMustNoExtraLocked(reads ...TestExpectedReads) {
	s.tb.Helper()
	rs := make(set.Set[testReadOperation])
	for i := range reads {
		rs.Add(reads[i].operation())
	}
	for ro, num := range s.reads {
		if !rs.Contains(ro) {
			s.tb.Errorf("%q (%v) reads: got %v, want 0", ro.Key, ro.Type, num)
		}
	}
}

// Suspend suspends the store, batching changes and notifications
// until [TestStore.Resume] is called the same number of times as Suspend.
func (s *TestStore) Suspend() {
	s.mu.Lock()
	defer s.mu.Unlock()
	if s.suspendCount++; s.suspendCount == 1 {
		s.mw = xmaps.Clone(s.mr)
	}
}

// Resume resumes the store, applying the changes and invoking
// the change callbacks.
func (s *TestStore) Resume() {
	s.storeLock.Lock()
	s.mu.Lock()
	switch s.suspendCount--; {
	case s.suspendCount == 0:
		s.mr = s.mw
		s.mu.Unlock()
		s.storeLock.Unlock()
		s.NotifyPolicyChanged()
	case s.suspendCount < 0:
		s.tb.Fatal("negative suspendCount")
	default:
		s.mu.Unlock()
		s.storeLock.Unlock()
	}
}

// SetBooleans sets the specified boolean settings in s.
func (s *TestStore) SetBooleans(settings ...TestSetting[bool]) {
	s.storeLock.Lock()
	for _, setting := range settings {
		if setting.Key == "" {
			s.tb.Fatal("empty keys disallowed")
		}
		s.mu.Lock()
		if setting.Error != nil {
			mak.Set(&s.mw, setting.Key, any(setting.Error))
		} else {
			mak.Set(&s.mw, setting.Key, any(setting.Value))
		}
		s.mu.Unlock()
	}
	s.storeLock.Unlock()
	s.NotifyPolicyChanged()
}

// SetUInt64s sets the specified integer settings in s.
func (s *TestStore) SetUInt64s(settings ...TestSetting[uint64]) {
	s.storeLock.Lock()
	for _, setting := range settings {
		if setting.Key == "" {
			s.tb.Fatal("empty keys disallowed")
		}
		s.mu.Lock()
		if setting.Error != nil {
			mak.Set(&s.mw, setting.Key, any(setting.Error))
		} else {
			mak.Set(&s.mw, setting.Key, any(setting.Value))
		}
		s.mu.Unlock()
	}
	s.storeLock.Unlock()
	s.NotifyPolicyChanged()
}

// SetStrings sets the specified string settings in s.
func (s *TestStore) SetStrings(settings ...TestSetting[string]) {
	s.storeLock.Lock()
	for _, setting := range settings {
		if setting.Key == "" {
			s.tb.Fatal("empty keys disallowed")
		}
		s.mu.Lock()
		if setting.Error != nil {
			mak.Set(&s.mw, setting.Key, any(setting.Error))
		} else {
			mak.Set(&s.mw, setting.Key, any(setting.Value))
		}
		s.mu.Unlock()
	}
	s.storeLock.Unlock()
	s.NotifyPolicyChanged()
}

// SetStrings sets the specified string list settings in s.
func (s *TestStore) SetStringLists(settings ...TestSetting[[]string]) {
	s.storeLock.Lock()
	for _, setting := range settings {
		if setting.Key == "" {
			s.tb.Fatal("empty keys disallowed")
		}
		s.mu.Lock()
		if setting.Error != nil {
			mak.Set(&s.mw, setting.Key, any(setting.Error))
		} else {
			mak.Set(&s.mw, setting.Key, any(setting.Value))
		}
		s.mu.Unlock()
	}
	s.storeLock.Unlock()
	s.NotifyPolicyChanged()
}

// Delete deletes the specified settings from s.
func (s *TestStore) Delete(keys ...pkey.Key) {
	s.storeLock.Lock()
	for _, key := range keys {
		s.mu.Lock()
		delete(s.mw, key)
		s.mu.Unlock()
	}
	s.storeLock.Unlock()
	s.NotifyPolicyChanged()
}

// Clear deletes all settings from s.
func (s *TestStore) Clear() {
	s.storeLock.Lock()
	s.mu.Lock()
	clear(s.mw)
	s.mu.Unlock()
	s.storeLock.Unlock()
	s.NotifyPolicyChanged()
}

func (s *TestStore) NotifyPolicyChanged() {
	s.mu.RLock()
	if s.suspendCount != 0 {
		s.mu.RUnlock()
		return
	}
	cbs := slicesx.MapValues(s.cbs)
	s.mu.RUnlock()

	var wg sync.WaitGroup
	wg.Add(len(cbs))
	for _, cb := range cbs {
		go func() {
			defer wg.Done()
			cb()
		}()
	}
	wg.Wait()
}

// Close closes s, notifying its users that it has expired.
func (s *TestStore) Close() {
	s.mu.Lock()
	defer s.mu.Unlock()
	if !s.closed {
		close(s.done)
		s.closed = true
	}
}

// Done implements [Expirable].
func (s *TestStore) Done() <-chan struct{} {
	return s.done
}