File: loop_test.go

package info (click to toggle)
golang-github-tideland-golib 4.24.2-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,144 kB
  • sloc: makefile: 4
file content (828 lines) | stat: -rw-r--r-- 22,375 bytes parent folder | download | duplicates (2)
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
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
// Tideland Go Library - Loop - Unit Test
//
// Copyright (C) 2013-2017 Frank Mueller / Tideland / Oldenburg / Germany
//
// All rights reserved. Use of this source code is governed
// by the new BSD license.

package loop_test

//--------------------
// IMPORTS
//--------------------

import (
	"errors"
	"testing"
	"time"

	"github.com/tideland/golib/audit"
	"github.com/tideland/golib/logger"
	"github.com/tideland/golib/loop"
)

//--------------------
// CONSTANTS
//--------------------

// timeout is the waitng time for events from inside of loops.
var timeout time.Duration = 5 * time.Second

//--------------------
// TESTS
//--------------------

// TestSimpleStop tests the simple backend returning nil
// after a stop.
func TestSimpleStop(t *testing.T) {
	assert := audit.NewTestingAssertion(t, true)
	bundle := newChannelBundle()
	l := loop.Go(makeSimpleLF(bundle), "simple-stop")

	assert.Wait(bundle.startedc, true, timeout)
	assert.Nil(l.Stop(), "no error after simple stop")
	assert.Wait(bundle.donec, true, timeout)

	status, _ := l.Error()

	assert.Equal(loop.Stopped, status, "loop is stopped")
}

// TestLogging tests running a loop without logging.
func TestLogging(t *testing.T) {
	assert := audit.NewTestingAssertion(t, true)
	tl := logger.NewTestLogger()
	ol := logger.SetLogger(tl)
	defer logger.SetLogger(ol)

	// With description, so logging.
	bundle := newChannelBundle()
	l := loop.Go(makeSimpleLF(bundle), "logger")

	assert.Wait(bundle.startedc, true, timeout)
	assert.Nil(l.Stop(), "no error after simple stop")
	assert.Wait(bundle.donec, true, timeout)

	status, _ := l.Error()

	assert.Equal(loop.Stopped, status, "loop is stopped")
	assert.Length(tl, 2)
	tl.Reset()

	// Without description, so no logging.
	bundle = newChannelBundle()
	l = loop.Go(makeSimpleLF(bundle))

	assert.Wait(bundle.startedc, true, timeout)
	assert.Nil(l.Stop(), "no error after simple stop")
	assert.Wait(bundle.donec, true, timeout)

	status, _ = l.Error()

	assert.Equal(loop.Stopped, status, "loop is stopped")
	assert.Length(tl, 0)
	tl.Reset()
}

// TestSimpleRestart tests restarting when not stopped and
// when stopped.
func TestSimpleRestart(t *testing.T) {
	assert := audit.NewTestingAssertion(t, true)
	bundle := newChannelBundle()
	l := loop.Go(makeSimpleLF(bundle), "simple-restart")

	assert.Wait(bundle.startedc, true, timeout)
	assert.ErrorMatch(l.Restart(), ".*cannot restart unstopped.*")

	status, _ := l.Error()

	assert.Equal(loop.Running, status)
	assert.Nil(l.Stop())
	assert.Wait(bundle.donec, true, timeout)

	status, _ = l.Error()

	assert.Equal(loop.Stopped, status)
	assert.Nil(l.Restart())
	assert.Wait(bundle.startedc, true, timeout)

	status, _ = l.Error()

	assert.Equal(loop.Running, status)
	assert.Nil(l.Stop())
	assert.Wait(bundle.donec, true, timeout)
}

// TestSimpleKill tests the simple backend returning an error
// after a kill.
func TestSimpleKill(t *testing.T) {
	assert := audit.NewTestingAssertion(t, true)
	bundle := newChannelBundle()
	l := loop.Go(makeSimpleLF(bundle), "simple-kill")

	assert.Wait(bundle.startedc, true, timeout)

	l.Kill(errors.New("ouch"))

	assert.ErrorMatch(l.Stop(), "ouch")
	assert.Wait(bundle.donec, true, timeout)

	status, _ := l.Error()

	assert.Equal(status, loop.Stopped)
}

// TestError tests an internal error.
func TestError(t *testing.T) {
	assert := audit.NewTestingAssertion(t, true)
	bundle := newChannelBundle()
	l := loop.Go(makeErrorLF(bundle), "error")

	assert.Wait(bundle.startedc, true, timeout)

	bundle.errorc <- true

	assert.ErrorMatch(l.Stop(), "internal loop error")
	assert.Wait(bundle.donec, true, timeout)

	status, _ := l.Error()

	assert.Equal(status, loop.Stopped)
}

// TestDeferredError tests an error in a deferred function inside the loop.
func TestDeferredError(t *testing.T) {
	assert := audit.NewTestingAssertion(t, true)
	bundle := newChannelBundle()
	l := loop.Go(makeDeferredErrorLF(bundle), "deferred-error")

	assert.Wait(bundle.startedc, true, timeout)
	assert.ErrorMatch(l.Stop(), "deferred error")
	assert.Wait(bundle.donec, true, timeout)

	status, _ := l.Error()

	assert.Equal(status, loop.Stopped)
}

// TestStopRecoverings tests the regular stop of a recovered loop.
func TestStopRecoverings(t *testing.T) {
	assert := audit.NewTestingAssertion(t, true)
	lbundle := newChannelBundle()
	rbundle := newChannelBundle()
	l := loop.GoRecoverable(makeRecoverPanicLF(lbundle), makeIgnorePanicsRF(rbundle), "stop-recoverings")

	assert.Wait(lbundle.startedc, true, timeout)

	lbundle.errorc <- true

	assert.Nil(l.Stop())
	assert.Wait(rbundle.donec, "recovered", timeout)

	status, _ := l.Error()

	assert.Equal(loop.Stopped, status, "loop is stopped")
}

// TestEndRecoverings tests the regular internal stop of a recovered loop.
func TestEndRecoverings(t *testing.T) {
	assert := audit.NewTestingAssertion(t, true)
	lbundle := newChannelBundle()
	rbundle := newChannelBundle()
	l := loop.GoRecoverable(makeRecoverNoErrorLF(lbundle), makeIgnorePanicsRF(rbundle), "end-recoverings")

	assert.Wait(lbundle.startedc, true, timeout)

	lbundle.stopc <- true

	assert.Wait(lbundle.donec, true, timeout)

	status, _ := l.Error()
	assert.Equal(status, loop.Stopped)
}

// TestRecoveringsPanic test recoverings after panics.
func TestRecoveringsPanic(t *testing.T) {
	assert := audit.NewTestingAssertion(t, true)
	lbundle := newChannelBundle()
	rbundle := newChannelBundle()
	l := loop.GoRecoverable(makeRecoverPanicLF(lbundle), makeCheckCountRF(rbundle), "recoverings-panic")

	go func() {
		for i := 0; i < 10; i++ {
			<-lbundle.startedc

			lbundle.errorc <- true

			<-rbundle.startedc
		}
	}()

	assert.Wait(rbundle.donec, 5, timeout)
	assert.ErrorMatch(l.Stop(), "too many panics")

	status, _ := l.Error()

	assert.Equal(status, loop.Stopped)
}

// TestRecoveringsError tests recoverings after errors.
func TestRecoveringsError(t *testing.T) {
	assert := audit.NewTestingAssertion(t, true)
	lbundle := newChannelBundle()
	rbundle := newChannelBundle()
	l := loop.GoRecoverable(makeRecoverErrorLF(lbundle), makeCatchErrorRF(rbundle), "recoverings-error")

	assert.Wait(lbundle.startedc, true, timeout)

	lbundle.errorc <- true

	assert.ErrorMatch(l.Stop(), "error")
	assert.Wait(rbundle.donec, "error", timeout)

	status, _ := l.Error()

	assert.Equal(loop.Stopped, status, "loop is stopped")
}

// TestDescription tests the handling of loop and
// sentinel descriptions.
func TestDescription(t *testing.T) {
	assert := audit.NewTestingAssertion(t, true)
	abundle := newChannelBundle()
	bbundle := newChannelBundle()

	s := loop.GoSentinel("one")
	lA := loop.Go(makeSimpleLF(abundle), "two", "three", "four")
	lB := loop.Go(makeSimpleLF(bbundle))

	assert.Wait(abundle.startedc, true, timeout)
	assert.Wait(bbundle.startedc, true, timeout)

	s.Observe(lA, lB)

	assert.Equal(s.String(), "one")
	assert.Equal(lA.String(), "two::three::four")

	assert.Nil(s.Stop())
}

// TestSimpleSentinel tests the simple starting and
// stopping of a sentinel.
func TestSimpleSentinel(t *testing.T) {
	assert := audit.NewTestingAssertion(t, true)
	abundle := newChannelBundle()
	bbundle := newChannelBundle()
	cbundle := newChannelBundle()

	s := loop.GoSentinel("simple-sentinel")
	lA := loop.Go(makeSimpleLF(abundle), "loop", "a")
	lB := loop.Go(makeSimpleLF(bbundle), "loop", "b")
	lC := loop.Go(makeSimpleLF(cbundle), "loop", "c")

	assert.Wait(abundle.startedc, true, timeout)
	assert.Wait(bbundle.startedc, true, timeout)
	assert.Wait(cbundle.startedc, true, timeout)

	s.Observe(lA, lB, lC)

	assert.Nil(s.Stop())
	assert.Wait(abundle.donec, true, timeout)
	assert.Wait(bbundle.donec, true, timeout)
	assert.Wait(cbundle.donec, true, timeout)

	status, _ := s.Error()

	assert.Equal(status, loop.Stopped)
}

// TestSentinelStoppingLoop tests the stopping
// of a loop before sentinel stops.
func TestSentinelStoppingLoop(t *testing.T) {
	assert := audit.NewTestingAssertion(t, true)
	abundle := newChannelBundle()
	bbundle := newChannelBundle()
	cbundle := newChannelBundle()

	s := loop.GoSentinel("sentinel-stopping-loop")
	lA := loop.Go(makeSimpleLF(abundle), "loop", "a")
	lB := loop.Go(makeSimpleLF(bbundle), "loop", "b")
	lC := loop.Go(makeSimpleLF(cbundle), "loop", "c")

	assert.Wait(abundle.startedc, true, timeout)
	assert.Wait(bbundle.startedc, true, timeout)
	assert.Wait(cbundle.startedc, true, timeout)

	s.Observe(lA, lB, lC)

	assert.Nil(lB.Stop())
	assert.Wait(bbundle.donec, true, timeout)

	assert.Nil(s.Stop())
	assert.Wait(abundle.donec, true, timeout)
	assert.Wait(cbundle.donec, true, timeout)

	status, _ := s.Error()

	assert.Equal(status, loop.Stopped)
}

// TestSentinelForget tests the forgetting of loops
// by a sentinel.
func TestSentineForget(t *testing.T) {
	assert := audit.NewTestingAssertion(t, true)
	abundle := newChannelBundle()
	bbundle := newChannelBundle()
	cbundle := newChannelBundle()
	dbundle := newChannelBundle()

	s := loop.GoSentinel("sentinel-forget")
	lA := loop.Go(makeSimpleLF(abundle), "loop", "a")
	lB := loop.Go(makeSimpleLF(bbundle), "loop", "b")
	lC := loop.Go(makeSimpleLF(cbundle), "loop", "c")
	lD := loop.Go(makeSimpleLF(dbundle), "loop", "d")

	assert.Wait(abundle.startedc, true, timeout)
	assert.Wait(bbundle.startedc, true, timeout)
	assert.Wait(cbundle.startedc, true, timeout)
	assert.Wait(dbundle.startedc, true, timeout)

	s.Observe(lA, lB, lC, lD)
	s.Forget(lB, lC)

	assert.Nil(s.Stop())
	assert.Wait(abundle.donec, true, timeout)
	assert.Wait(dbundle.donec, true, timeout)

	status, _ := s.Error()

	assert.Equal(loop.Stopped, status)
}

// TestSentinelKillingLoopNoHandler tests the killing
// of a loop before sentinel stops. The sentinel has
// no handler and so ignores the error.
func TestSentinelKillingLoopNoHandler(t *testing.T) {
	assert := audit.NewTestingAssertion(t, true)
	abundle := newChannelBundle()
	bbundle := newChannelBundle()
	cbundle := newChannelBundle()

	s := loop.GoSentinel("sentinel-killing-loop-no-handler")
	lA := loop.Go(makeSimpleLF(abundle), "loop", "a")
	lB := loop.Go(makeSimpleLF(bbundle), "loop", "b")
	lC := loop.Go(makeSimpleLF(cbundle), "loop", "c")

	s.Observe(lA, lB, lC)

	assert.Wait(abundle.startedc, true, timeout)
	assert.Wait(bbundle.startedc, true, timeout)
	assert.Wait(cbundle.startedc, true, timeout)

	lB.Kill(errors.New("bang!"))
	assert.Wait(abundle.donec, true, timeout)
	assert.Wait(bbundle.donec, true, timeout)
	assert.Wait(cbundle.donec, true, timeout)

	assert.ErrorMatch(s.Stop(), ".*bang!.*")

	status, _ := s.Error()

	assert.Equal(loop.Stopped, status)
}

// TestSentinelKillingLoopHandlerRestarts tests the killing
// of a loop before sentinel stops. The sentinel has
// a handler and restarts the loop.
func TestSentinelKillingLoopHandlerRestarts(t *testing.T) {
	assert := audit.NewTestingAssertion(t, true)
	abundle := newChannelBundle()
	bbundle := newChannelBundle()
	cbundle := newChannelBundle()
	sbundle := newChannelBundle()
	shandler := func(s loop.Sentinel, o loop.Observable, rs loop.Recoverings) (loop.Recoverings, error) {
		o.Restart()
		sbundle.donec <- true
		return nil, nil
	}

	s := loop.GoNotifiedSentinel(shandler, "sentinel-killing-loop-handler-restarts")
	lA := loop.Go(makeSimpleLF(abundle), "loop", "a")
	lB := loop.Go(makeSimpleLF(bbundle), "loop", "b")
	lC := loop.Go(makeSimpleLF(cbundle), "loop", "c")

	s.Observe(lA, lB, lC)

	assert.Wait(abundle.startedc, true, timeout)
	assert.Wait(bbundle.startedc, true, timeout)
	assert.Wait(cbundle.startedc, true, timeout)

	lB.Kill(errors.New("bang!"))

	assert.Wait(bbundle.donec, true, timeout)
	assert.Wait(sbundle.donec, true, timeout)
	assert.Nil(s.Stop())
	assert.Wait(abundle.donec, true, timeout)
	assert.Wait(bbundle.donec, true, timeout)
	assert.Wait(cbundle.donec, true, timeout)

	status, _ := s.Error()

	assert.Equal(loop.Stopped, status)
}

// TestSentinelKillingLoopHandlerStops tests the killing
// of a loop before sentinel stops. The sentinel has
// a handler which stops the processing.
func TestSentinelKillingLoopHandlerStops(t *testing.T) {
	assert := audit.NewTestingAssertion(t, true)
	abundle := newChannelBundle()
	bbundle := newChannelBundle()
	cbundle := newChannelBundle()
	sbundle := newChannelBundle()
	shandler := func(s loop.Sentinel, o loop.Observable, rs loop.Recoverings) (loop.Recoverings, error) {
		sbundle.donec <- true
		return nil, errors.New("oh no!")
	}

	s := loop.GoNotifiedSentinel(shandler, "sentinel-killing-loop-with-stops")
	lA := loop.Go(makeSimpleLF(abundle), "loop", "a")
	lB := loop.Go(makeSimpleLF(bbundle), "loop", "b")
	lC := loop.Go(makeSimpleLF(cbundle), "loop", "c")

	s.Observe(lA, lB, lC)

	assert.Wait(abundle.startedc, true, timeout)
	assert.Wait(bbundle.startedc, true, timeout)
	assert.Wait(cbundle.startedc, true, timeout)

	lB.Kill(errors.New("bang!"))

	assert.Wait(abundle.donec, true, timeout)
	assert.Wait(bbundle.donec, true, timeout)
	assert.Wait(cbundle.donec, true, timeout)
	assert.Wait(sbundle.donec, true, timeout)

	assert.ErrorMatch(s.Stop(), ".*oh no!.*")

	status, _ := s.Error()

	assert.Equal(loop.Stopped, status)
}

// TestSentinelKillingLoopHandlerRestartAll tests the killing
// of a loop before sentinel stops. The sentinel has
// a handler which restarts all observables.
func TestSentinelKillingLoopHandlerRestartAll(t *testing.T) {
	assert := audit.NewTestingAssertion(t, true)
	abundle := newChannelBundle()
	bbundle := newChannelBundle()
	cbundle := newChannelBundle()
	sbundle := newChannelBundle()
	shandler := func(s loop.Sentinel, _ loop.Observable, _ loop.Recoverings) (loop.Recoverings, error) {
		s.ObservablesDo(func(o loop.Observable) error {
			o.Restart()
			return nil
		})
		sbundle.donec <- true
		return nil, nil
	}

	s := loop.GoNotifiedSentinel(shandler, "sentinel-killing-loop-restarting-all")
	lA := loop.Go(makeSimpleLF(abundle), "loop", "a")
	lB := loop.Go(makeSimpleLF(bbundle), "loop", "b")
	lC := loop.Go(makeSimpleLF(cbundle), "loop", "c")

	s.Observe(lA, lB, lC)

	assert.Wait(abundle.startedc, true, timeout)
	assert.Wait(bbundle.startedc, true, timeout)
	assert.Wait(cbundle.startedc, true, timeout)

	lB.Kill(errors.New("bang!"))

	assert.Wait(bbundle.donec, true, timeout)
	assert.Wait(sbundle.donec, true, timeout)
	assert.Nil(s.Stop())
	assert.Wait(abundle.donec, true, timeout)
	assert.Wait(bbundle.donec, true, timeout)
	assert.Wait(cbundle.donec, true, timeout)

	status, _ := s.Error()

	assert.Equal(loop.Stopped, status)
}

// TestNestedSentinelKill tests the killing and restarting of a
// nested sentinel.
func TestNestedSentinelKill(t *testing.T) {
	assert := audit.NewTestingAssertion(t, true)
	abundle := newChannelBundle()
	bbundle := newChannelBundle()
	sbundle := newChannelBundle()
	shandler := func(s loop.Sentinel, o loop.Observable, rs loop.Recoverings) (loop.Recoverings, error) {
		o.Restart()
		sbundle.donec <- true
		return nil, nil
	}

	sT := loop.GoNotifiedSentinel(shandler, "nested-sentinel-kill", "top")
	lA := loop.Go(makeSimpleLF(abundle), "loop", "a")
	sN := loop.GoNotifiedSentinel(shandler, "nested-sentinel-kill", "nested")
	lB := loop.Go(makeSimpleLF(bbundle), "loop", "b")

	sT.Observe(lA, sN)
	sN.Observe(lB)

	assert.Wait(abundle.startedc, true, timeout)
	assert.Wait(bbundle.startedc, true, timeout)

	sN.Kill(errors.New("bang!"))

	assert.Wait(sbundle.donec, true, timeout)

	assert.Nil(sT.Stop())
	assert.Wait(bbundle.donec, true, timeout)
	assert.Wait(abundle.donec, true, timeout)

	status, _ := sT.Error()

	assert.Equal(loop.Stopped, status)
}

// TestSentinelSwitch tests if the change of the assignment
// of a sentinel is handled correctly.
func TestSentinelSwitch(t *testing.T) {
	assert := audit.NewTestingAssertion(t, true)
	abundle := newChannelBundle()

	sA := loop.GoSentinel("sentinel-switch", "a")
	sB := loop.GoSentinel("sentinel-switch", "b")
	lA := loop.Go(makeSimpleLF(abundle), "loop", "a")

	sA.Observe(lA)

	assert.Wait(abundle.startedc, true, timeout)

	sB.Observe(lA)

	assert.Nil(sA.Stop())
	assert.Nil(sB.Stop())
	assert.Wait(abundle.donec, true, timeout)
}

//--------------------
// EXAMPLES
//--------------------

// ExampleLoopFunc shows the usage of loop.Go with one
// loop function and no recovery. The inner loop contains
// a select listening to the channel returned by ShallStop.
// Other channels are for the standard communication
// with the loop.
func ExampleLoopFunc() {
	printC := make(chan string)
	// Sample loop function.
	loopF := func(l loop.Loop) error {
		for {
			select {
			case <-l.ShallStop():
				// We shall stop.
				return nil
			case str := <-printC:
				if str == "panic" {
					return errors.New("panic")
				}
				println(str)
			}
		}
	}
	l := loop.Go(loopF, "simple loop demo")

	printC <- "Hello"
	printC <- "World"

	if err := l.Stop(); err != nil {
		panic(err)
	}
}

// ExampleRecoverFunc demonstrates the usage of a recovery
// function when using loop.GoRecoverable. Here the frequency
// of the recoverings (more than five in 10 milliseconds)
// or the total number is checked. If the total number is
// not interesting the recoverings could be trimmed by
// e.g. rs.Trim(5). The fields Time and Reason per
// recovering allow even more diagnosis.
func ExampleRecoverFunc() {
	printC := make(chan string)
	loopF := func(l loop.Loop) error {
		for {
			select {
			case <-l.ShallStop():
				return nil
			case str := <-printC:
				println(str)
			}
		}
	}
	// Recovery function checking frequency and total number.
	recoverF := func(rs loop.Recoverings) (loop.Recoverings, error) {
		if rs.Frequency(5, 10*time.Millisecond) {
			return nil, errors.New("too high error frequency")
		}
		if rs.Len() >= 10 {
			return nil, errors.New("too many errors")
		}
		return rs, nil
	}
	loop.GoRecoverable(loopF, recoverF, "recoverable loop demo")
}

// ExampleSentinel demonstrates the monitoring of loops and sentinel
// with a handler function trying to restart the faulty observable.
// The nested sentinel has no handler function. An error of a monitored
// observable would lead to the stop of all observables.
func ExampleSentinel() {
	loopF := func(l loop.Loop) error {
		for {
			select {
			case <-l.ShallStop():
				return nil
			}
		}
	}
	handleF := func(s loop.Sentinel, o loop.Observable, rs loop.Recoverings) (loop.Recoverings, error) {
		if rs.Frequency(5, 10*time.Millisecond) {
			return nil, errors.New("too high error frequency")
		}
		return nil, o.Restart()
	}
	loopA := loop.Go(loopF, "loop", "a")
	loopB := loop.Go(loopF, "loop", "b")
	loopC := loop.Go(loopF, "loop", "c")
	loopD := loop.Go(loopF, "loop", "d")
	sentinel := loop.GoNotifiedSentinel(handleF, "sentinel demo")

	sentinel.Observe(loopA, loopB)

	// Hierarchies are possible.
	observedSentinel := loop.GoSentinel("nested sentinel w/o handler")

	sentinel.Observe(observedSentinel)
	observedSentinel.Observe(loopC)
	observedSentinel.Observe(loopD)
}

//--------------------
// HELPERS
//--------------------

// channelBundle enables communication from and to loop functions.
type channelBundle struct {
	startedc chan interface{}
	donec    chan interface{}
	stopc    chan interface{}
	errorc   chan interface{}
}

func newChannelBundle() *channelBundle {
	return &channelBundle{
		startedc: audit.MakeSigChan(),
		donec:    audit.MakeSigChan(),
		stopc:    audit.MakeSigChan(),
		errorc:   audit.MakeSigChan(),
	}
}

// makeSimpleLF creates a loop function doing nothing special.
func makeSimpleLF(bundle *channelBundle) loop.LoopFunc {
	return func(l loop.Loop) error {
		defer func() { bundle.donec <- true }()
		bundle.startedc <- true
		for {
			select {
			case <-l.ShallStop():
				return nil
			}
		}
	}
}

// makeErrorLF creates a loop function stopping with
// an error after receiving a signal.
func makeErrorLF(bundle *channelBundle) loop.LoopFunc {
	return func(l loop.Loop) error {
		defer func() { bundle.donec <- true }()
		bundle.startedc <- true
		for {
			select {
			case <-l.ShallStop():
				return nil
			case <-bundle.errorc:
				return errors.New("internal loop error")
			}
		}
	}
}

// makeDeferredErrorLF creates a loop function returning
// an error in its deferred function.
func makeDeferredErrorLF(bundle *channelBundle) loop.LoopFunc {
	return func(l loop.Loop) (err error) {
		defer func() { bundle.donec <- true }()
		defer func() {
			err = errors.New("deferred error")
		}()
		bundle.startedc <- true
		for {
			select {
			case <-l.ShallStop():
				return nil
			}
		}
	}
}

// makeRecoverPanicLF creates a loop function having a panic
// but getting recovered.
func makeRecoverPanicLF(bundle *channelBundle) loop.LoopFunc {
	return func(l loop.Loop) error {
		bundle.startedc <- true
		for {
			select {
			case <-l.ShallStop():
				return nil
			case <-bundle.errorc:
				panic("panic")
			}
		}
	}
}

// makeRecoverErrorLF creates a loop function having an error
// but getting recovered.
func makeRecoverErrorLF(bundle *channelBundle) loop.LoopFunc {
	return func(l loop.Loop) error {
		bundle.startedc <- true
		for {
			select {
			case <-l.ShallStop():
				return nil
			case <-bundle.errorc:
				return errors.New("error")
			}
		}
	}
}

// makeRecoverNoErrorLF creates a loop function stopping
// without an error so it won't be recovered.
func makeRecoverNoErrorLF(bundle *channelBundle) loop.LoopFunc {
	return func(l loop.Loop) error {
		bundle.startedc <- true
		<-bundle.stopc
		bundle.donec <- true
		return nil
	}
}

// makeCheckCountRF creates a recover function stopping
// recovering after 5 calls.
func makeCheckCountRF(bundle *channelBundle) loop.RecoverFunc {
	return func(rs loop.Recoverings) (loop.Recoverings, error) {
		bundle.startedc <- true
		if len(rs) >= 5 {
			bundle.donec <- len(rs)
			return nil, errors.New("too many panics")
		}
		return rs, nil
	}
}

// makeCatchErrorRF creates a recover function stopping
// recovering in case of the error "error".
func makeCatchErrorRF(bundle *channelBundle) loop.RecoverFunc {
	return func(rs loop.Recoverings) (loop.Recoverings, error) {
		if len(rs) > 0 {
			if err, ok := rs.Last().Reason.(error); ok {
				if err.Error() == "error" {
					bundle.donec <- "error"
					return nil, err
				}
			}
		}
		return nil, nil
	}
}

// makeIgnorePanicsRF creates a recover function always
// recovering the paniced loop function.
func makeIgnorePanicsRF(bundle *channelBundle) loop.RecoverFunc {
	return func(rs loop.Recoverings) (loop.Recoverings, error) {
		bundle.donec <- "recovered"
		return nil, nil
	}
}

// EOF