/
token.go
123 lines (96 loc) · 2.29 KB
/
token.go
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
package token
import (
"fmt"
"sync"
"sync/atomic"
"time"
mqtt "github.com/eclipse/paho.mqtt.golang"
)
type Tokens struct {
tokens map[string]mqtt.Token
}
func NewTokens() *Tokens {
return &Tokens{
tokens: make(map[string]mqtt.Token),
}
}
func (ts *Tokens) Append(name string, t mqtt.Token) {
ts.tokens[name] = t
}
// Wait will wait indefinitely for the Token to complete, ie the Publish
// to be sent and confirmed receipt from the broker.
func (ts *Tokens) Wait() bool {
result := true
for _, t := range ts.tokens {
result = result && t.Wait()
}
return result
}
// WaitTimeout takes a time.Duration to wait for the flow associated with the
// Token to complete, returns true if it returned before the timeout or
// returns false if the timeout occurred. In the case of a timeout the Token
// does not have an error set in case the caller wishes to wait again.
func (ts *Tokens) WaitTimeout(d time.Duration) bool {
result := atomic.Value{}
result.Store(true)
wg := &sync.WaitGroup{}
wg.Add(len(ts.tokens))
for _, t := range ts.tokens {
t := t
go func() {
defer wg.Done()
result.Store(result.Load().(bool) && t.WaitTimeout(d))
}()
}
done := make(chan struct{})
go func() {
defer close(done)
wg.Wait()
}()
select {
case <-done:
return result.Load().(bool)
case <-time.After(d):
return false
}
}
// Done returns a channel that is closed when the flow associated
// with the Token completes. Clients should call Error after the
// channel is closed to check if the flow completed successfully.
//
// Done is provided for use in select statements. Simple use cases may
// use Wait or WaitTimeout.
func (ts *Tokens) Done() <-chan struct{} {
ch := make(chan struct{})
go func() {
for _, t := range ts.tokens {
<-t.Done()
}
close(ch)
}()
return ch
}
type Errors []error
func (es Errors) Error() string {
result := ""
for _, e := range []error(es) {
if result == "" {
result = e.Error()
} else {
result = fmt.Sprintf("%s,%s", result, e.Error())
}
}
return result
}
func (ts *Tokens) Error() error {
errors := make([]error, 0, len(ts.tokens))
for name, token := range ts.tokens {
if token.Error() != nil {
errors = append(errors, fmt.Errorf("%s: %w", name, token.Error()))
}
}
if len(errors) == 0 {
return nil
}
return Errors(errors)
}