-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontrols_test.go
More file actions
535 lines (424 loc) · 13.8 KB
/
Copy pathcontrols_test.go
File metadata and controls
535 lines (424 loc) · 13.8 KB
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
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
package controls_test
import (
"bytes"
"context"
"fmt"
"log/slog"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"gitlab.com/phpboyscout/go/controls"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
type StateCounters struct {
Started atomic.Int64
Stopped atomic.Int64
Statused atomic.Int64
}
// syncBuffer is a thread-safe bytes.Buffer for use with slog in tests.
type syncBuffer struct {
mu sync.Mutex
buf bytes.Buffer
}
func (b *syncBuffer) Write(p []byte) (int, error) {
b.mu.Lock()
defer b.mu.Unlock()
return b.buf.Write(p)
}
func (b *syncBuffer) String() string {
b.mu.Lock()
defer b.mu.Unlock()
return b.buf.String()
}
func getNewController(ctx context.Context) (*controls.Controller, *StateCounters, *syncBuffer) {
cntrs := &StateCounters{}
startFunc := func(_ context.Context) error { cntrs.Started.Add(1); return nil }
stopFunc := func(_ context.Context) { cntrs.Stopped.Add(1) }
statusFunc := func() error { cntrs.Statused.Add(1); time.Sleep(500 * time.Microsecond); return nil }
buf := &syncBuffer{}
c := controls.NewController(ctx, controls.WithLogger(slog.New(slog.NewTextHandler(buf, nil))))
c.Register("test",
controls.WithStart(startFunc),
controls.WithStop(stopFunc),
controls.WithStatus(statusFunc),
)
return c, cntrs, buf
}
func TestController_Controls(t *testing.T) {
t.Run("stopping", func(t *testing.T) {
c, cntrs, _ := getNewController(context.Background())
assert.Equal(t, controls.Unknown, c.GetState())
c.Start()
assert.True(t, c.IsRunning())
c.Stop()
// The Stopped state lands just after the StopFunc runs (the shutdown
// sequence still awaits supervisor exit, D10), so poll for both.
assert.Eventually(t, func() bool {
return cntrs.Stopped.Load() == int64(1) && c.IsStopped()
}, 1*time.Second, 10*time.Millisecond)
})
t.Run("stop running controller", func(t *testing.T) {
c, cntrs, _ := getNewController(context.Background())
c.Start()
assert.True(t, c.IsRunning())
c.Messages() <- controls.Stop
// As above: the Stopped state lands just after the StopFunc runs.
assert.Eventually(t, func() bool {
return cntrs.Stopped.Load() == int64(1) && c.IsStopped()
}, 1*time.Second, 10*time.Millisecond)
})
}
func TestController_StartError(t *testing.T) {
c, _, output := getNewController(context.Background())
c.Register("test",
controls.WithStart(func(_ context.Context) error {
return fmt.Errorf("test error")
}),
controls.WithStop(func(_ context.Context) {}),
controls.WithStatus(func() error { return nil }),
)
c.Start()
assert.Eventually(t, func() bool {
return strings.Contains(output.String(), "test error")
}, 1*time.Second, 10*time.Millisecond)
}
func TestController_WaitGroup(t *testing.T) {
c, _, _ := getNewController(context.Background())
wg := &sync.WaitGroup{}
c.SetWaitGroup(wg)
wg2 := c.WaitGroup()
assert.Equal(t, wg, wg2)
}
func TestController_SetState(t *testing.T) {
c, _, _ := getNewController(context.Background())
c.SetState(controls.Running)
assert.True(t, c.IsRunning())
c.SetState(controls.Stopping)
assert.True(t, c.IsStopping())
c.SetState(controls.Stopped)
assert.True(t, c.IsStopped())
}
func TestController_Errors(t *testing.T) {
c, _, output := getNewController(context.Background())
errs := make(chan error)
c.SetErrorsChannel(errs)
c.Start()
c.Errors() <- fmt.Errorf("test error") //nolint:goerr113
assert.Eventually(t, func() bool {
return strings.Contains(output.String(), "test error")
}, 1*time.Second, 10*time.Millisecond)
}
func TestController_ContextCancel(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
c, _, _ := getNewController(ctx)
errs := make(chan error)
c.SetErrorsChannel(errs)
c.Start()
go func() {
time.Sleep(20 * time.Millisecond)
cancel()
}()
c.Wait()
assert.True(t, c.IsStopped())
}
func TestController_SetMessageChannels(t *testing.T) {
c, _, _ := getNewController(context.Background())
msgs := make(chan controls.Message)
c.SetMessageChannel(msgs)
assert.Equal(t, msgs, c.Messages())
}
func TestStop_ConcurrentCalls(t *testing.T) {
c, cntrs, _ := getNewController(context.Background())
c.Start()
assert.True(t, c.IsRunning())
var wg sync.WaitGroup
for i := 0; i < 100; i++ {
wg.Add(1)
go func() {
defer wg.Done()
c.Stop()
}()
}
wg.Wait()
assert.Eventually(t, func() bool {
return c.IsStopped()
}, 2*time.Second, 10*time.Millisecond)
// Stop function of the service should have been called exactly once
assert.Equal(t, int64(1), cntrs.Stopped.Load(), "stop should execute exactly once")
}
// Compile-time interface satisfaction checks (also exercised at test time).
var (
_ controls.Runner = (*controls.Controller)(nil)
_ controls.StateAccessor = (*controls.Controller)(nil)
_ controls.Configurable = (*controls.Controller)(nil)
_ controls.ChannelProvider = (*controls.Controller)(nil)
_ controls.Controllable = (*controls.Controller)(nil)
)
func TestControllerOpt_WithConfigurable(t *testing.T) {
// Verify that WithSignals works with the Configurable-typed parameter.
opt := controls.WithSignals()
c := controls.NewController(context.Background(), opt)
assert.NotNil(t, c.Signals())
}
func TestStop_AlreadyStopped(t *testing.T) {
c, _, _ := getNewController(context.Background())
c.Start()
assert.True(t, c.IsRunning())
c.Stop()
assert.Eventually(t, func() bool {
return c.IsStopped()
}, 2*time.Second, 10*time.Millisecond)
// Calling Stop again should be a no-op (not panic or block)
c.Stop()
assert.True(t, c.IsStopped())
}
func TestController_Status(t *testing.T) {
t.Parallel()
ctx := context.Background()
c := controls.NewController(ctx)
c.Register("healthy-service",
controls.WithStart(func(_ context.Context) error { return nil }),
controls.WithStop(func(_ context.Context) {}),
controls.WithStatus(func() error { return nil }),
)
c.Register("unhealthy-service",
controls.WithStart(func(_ context.Context) error { return nil }),
controls.WithStop(func(_ context.Context) {}),
controls.WithStatus(func() error { return fmt.Errorf("service failed") }),
)
report := c.Status()
assert.False(t, report.OverallHealthy)
assert.Len(t, report.Services, 2)
var healthy, unhealthy bool
for _, s := range report.Services {
if s.Name == "healthy-service" {
assert.Equal(t, "OK", s.Status)
assert.Empty(t, s.Error)
healthy = true
}
if s.Name == "unhealthy-service" {
assert.Equal(t, "ERROR", s.Status)
assert.Equal(t, "service failed", s.Error)
unhealthy = true
}
}
assert.True(t, healthy)
assert.True(t, unhealthy)
}
func TestController_Probes(t *testing.T) {
t.Parallel()
ctx := context.Background()
c := controls.NewController(ctx)
c.Register("service-1",
controls.WithStart(func(_ context.Context) error { return nil }),
controls.WithStop(func(_ context.Context) {}),
controls.WithLiveness(func() error { return nil }),
controls.WithReadiness(func() error { return fmt.Errorf("not ready") }),
)
c.Register("service-2",
controls.WithStart(func(_ context.Context) error { return nil }),
controls.WithStop(func(_ context.Context) {}),
// No probes provided, should fall back to Status which defaults to nil (OK)
)
// Liveness should be healthy (service-1 is OK, service-2 uses default OK)
liveReport := c.Liveness()
assert.True(t, liveReport.OverallHealthy)
// Readiness should be unhealthy (service-1 reports error)
readyReport := c.Readiness()
assert.False(t, readyReport.OverallHealthy)
var foundS1 bool
for _, s := range readyReport.Services {
if s.Name == "service-1" {
assert.Equal(t, "ERROR", s.Status)
assert.Equal(t, "not ready", s.Error)
foundS1 = true
}
}
assert.True(t, foundS1)
}
func TestController_Supervisor_NoPolicy(t *testing.T) {
t.Parallel()
ctx := context.Background()
c := controls.NewController(ctx)
starts := atomic.Int32{}
c.Register("failing-service",
controls.WithStart(func(_ context.Context) error {
starts.Add(1)
return fmt.Errorf("immediate failure")
}),
controls.WithStop(func(_ context.Context) {}),
)
c.Start()
// Wait a moment to see if it restarts
time.Sleep(50 * time.Millisecond)
c.Stop()
c.Wait()
assert.Equal(t, int32(1), starts.Load(), "Service should only start once without a policy")
}
func TestController_Supervisor_WithPolicy(t *testing.T) {
t.Parallel()
ctx := context.Background()
c := controls.NewController(ctx)
starts := atomic.Int32{}
c.Register("restarting-service",
controls.WithStart(func(_ context.Context) error {
starts.Add(1)
return fmt.Errorf("transient failure")
}),
controls.WithStop(func(_ context.Context) {}),
controls.WithRestartPolicy(controls.RestartPolicy{
MaxRestarts: 3,
InitialBackoff: 10 * time.Millisecond,
MaxBackoff: 50 * time.Millisecond,
}),
)
c.Start()
// Wait for the restart policy to exhaust all retries.
// Under the race detector, backoff sleeps take longer than wall-clock
// time, so use Eventually rather than a fixed sleep.
assert.Eventually(t, func() bool {
return starts.Load() >= 4
}, 5*time.Second, 10*time.Millisecond, "Service should restart up to MaxRestarts times")
c.Stop()
c.Wait()
// 1 initial start + 3 restarts
assert.Equal(t, int32(4), starts.Load(), "Service should restart up to MaxRestarts times")
}
func TestController_Supervisor_HealthTriggered(t *testing.T) {
t.Parallel()
ctx := context.Background()
c := controls.NewController(ctx)
starts := atomic.Int32{}
statusCalls := atomic.Int32{}
c.Register("health-monitored-service",
controls.WithStart(func(_ context.Context) error {
starts.Add(1)
return nil // starts successfully
}),
controls.WithStop(func(_ context.Context) {}),
controls.WithStatus(func() error {
calls := statusCalls.Add(1)
if calls > 1 {
return fmt.Errorf("unhealthy")
}
return nil
}),
controls.WithRestartPolicy(controls.RestartPolicy{
HealthFailureThreshold: 2,
HealthCheckInterval: 10 * time.Millisecond,
InitialBackoff: 5 * time.Millisecond,
}),
)
c.Start()
require.Eventually(t, func() bool {
return starts.Load() >= 2
}, 5*time.Second, 10*time.Millisecond, "service should restart due to health failures")
c.Stop()
c.Wait()
}
func TestController_ServiceInfo(t *testing.T) {
t.Parallel()
ctx := context.Background()
c := controls.NewController(ctx)
c.Register("test-service",
controls.WithStart(func(_ context.Context) error {
return fmt.Errorf("initial failure")
}),
controls.WithStop(func(_ context.Context) {}),
controls.WithRestartPolicy(controls.RestartPolicy{
MaxRestarts: 1,
InitialBackoff: 5 * time.Millisecond,
}),
)
c.Start()
// Wait for the restart policy to exhaust retries instead of using a fixed sleep.
var info controls.ServiceInfo
require.Eventually(t, func() bool {
si, ok := c.GetServiceInfo("test-service")
if !ok {
return false
}
info = si
return info.Error != nil && strings.Contains(info.Error.Error(), "max restarts exceeded")
}, 5*time.Second, 10*time.Millisecond, "service should exhaust restart policy")
c.Stop()
c.Wait()
assert.Equal(t, "test-service", info.Name)
assert.Equal(t, 1, info.RestartCount)
assert.NotZero(t, info.LastStarted)
assert.NotZero(t, info.LastStopped)
_, ok := c.GetServiceInfo("non-existent")
assert.False(t, ok)
}
func TestControllerErrorHandler_ExitsOnClose(t *testing.T) {
t.Parallel()
ctx := context.Background()
// Use a buffered channel so we can enqueue errors before the goroutine starts.
errs := make(chan error, 4)
c := controls.NewController(ctx, controls.WithLogger(slog.New(slog.DiscardHandler)))
c.SetErrorsChannel(errs)
c.Start()
// Enqueue a non-fatal error, then close the channel.
// When the error handler goroutine reads the buffered error it will log it,
// then the next read returns ok=false and the goroutine exits cleanly.
errs <- fmt.Errorf("test error")
close(errs)
// The controller should stop and Wait should not deadlock.
c.Stop()
c.Wait()
}
func TestControllerErrorHandler_ExitsOnCancel(t *testing.T) {
t.Parallel()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
c := controls.NewController(ctx, controls.WithLogger(slog.New(slog.DiscardHandler)))
c.Start()
// Cancelling the parent context triggers the ctx.Done() branch in the error
// handler goroutine, which then calls c.Stop() internally.
cancel()
// The controller should reach Stopped state without blocking.
require.Eventually(t, func() bool {
return c.GetState() == controls.Stopped
}, 5*time.Second, 10*time.Millisecond, "controller should reach Stopped state after context cancel")
c.Wait()
}
// TestRegister_AfterStart_WarnsUnsupervised verifies that calling Register after
// the controller has started emits a WARNING (the service cannot be supervised),
// does not panic, and leaves the controller running.
func TestRegister_AfterStart_WarnsUnsupervised(t *testing.T) {
t.Parallel()
buf := &syncBuffer{}
c := controls.NewController(context.Background(),
controls.WithLogger(slog.New(slog.NewTextHandler(buf, nil))),
)
c.Start()
require.True(t, c.IsRunning())
// Must not panic and must keep running.
c.Register("late-service",
controls.WithStart(func(_ context.Context) error { return nil }),
)
require.True(t, c.IsRunning())
assert.Contains(t, buf.String(), "Register called after Start")
assert.Contains(t, buf.String(), "late-service")
c.Stop()
c.Wait()
}
// TestRegister_BeforeStart_NoWarning verifies that the normal pre-Start
// registration path does not emit the after-start warning.
func TestRegister_BeforeStart_NoWarning(t *testing.T) {
t.Parallel()
buf := &syncBuffer{}
c := controls.NewController(context.Background(),
controls.WithLogger(slog.New(slog.NewTextHandler(buf, nil))),
)
c.Register("early-service",
controls.WithStart(func(_ context.Context) error { return nil }),
)
assert.NotContains(t, buf.String(), "Register called after Start")
c.Start()
c.Stop()
c.Wait()
}