summaryrefslogtreecommitdiff
path: root/internal/execute.go
blob: d8f426ff8cb093c5c00f1393fd789570eaf3aa77 (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
package internal

import (
	"context"
	"log"
	"sync"
	"time"
)

func execute(state state, config config) state {
	limiterCh := make(chan struct{}, config.CheckConcurrency)
	inputCh := make(chan namedCheck)
	outputCh := make(chan checkResult)

	go func() {
		for name, check := range config.Checks {
			inputCh <- namedCheck{check, name}
		}
		close(inputCh)
	}()

	var outputWg sync.WaitGroup
	outputWg.Add(1)

	go func() {
		for checkResult := range outputCh {
			state.update(checkResult)
		}
		outputWg.Done()
	}()

	var inputWg sync.WaitGroup
	inputWg.Add(len(config.Checks))

	for check := range inputCh {
		go func(check namedCheck) {
			limiterCh <- struct{}{}
			defer func() {
				<-limiterCh
				inputWg.Done()
			}()

			ctx, cancel := context.WithTimeout(context.Background(),
				time.Duration(config.CheckTimeoutS)*time.Second)
			defer cancel()

			outputCh <- check.execute(ctx)
		}(check)
	}

	inputWg.Wait()
	log.Println("All checks completed!")
	close(outputCh)

	outputWg.Wait()
	log.Println("All outputs collected!")

	return state
}