forked from ooni/probe-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
taskemitter.go
63 lines (51 loc) · 1.81 KB
/
taskemitter.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
package oonimkall
import "sync"
// taskEmitterUsingChan is a task emitter using a channel.
type taskEmitterUsingChan struct {
// eof indicates we should not emit anymore.
eof chan interface{}
// once ensures we close the eof channel just once.
once sync.Once
// out is the possibly buffered channel where to emit events.
out chan<- *event
}
// ensure that taskEmitterUsingChan is a taskEmitter.
var _ taskEmitterCloser = &taskEmitterUsingChan{}
// newTaskEmitterUsingChan creates a taskEmitterUsingChan.
func newTaskEmitterUsingChan(out chan<- *event) *taskEmitterUsingChan {
return &taskEmitterUsingChan{
eof: make(chan interface{}),
once: sync.Once{},
out: out,
}
}
// Emit implements taskEmitter.Emit.
func (ee *taskEmitterUsingChan) Emit(key string, value interface{}) {
// Prevent this goroutine from blocking on `ee.out` if the caller
// has already told us it's not going to accept more events.
select {
case ee.out <- &event{Key: key, Value: value}:
case <-ee.eof:
}
}
// Close implements taskEmitterCloser.Closer.
func (ee *taskEmitterUsingChan) Close() error {
ee.once.Do(func() { close(ee.eof) })
return nil
}
// taskEmitterWrapper is a convenient wrapper for taskEmitter.
type taskEmitterWrapper struct {
taskEmitter
}
// EmitFailureStartup emits the failureStartup event
func (ee *taskEmitterWrapper) EmitFailureStartup(failure string) {
ee.EmitFailureGeneric(eventTypeFailureStartup, failure)
}
// EmitFailureGeneric emits a failure event
func (ee *taskEmitterWrapper) EmitFailureGeneric(name, failure string) {
ee.Emit(name, eventFailure{Failure: failure})
}
// EmitStatusProgress emits the status.Progress event
func (ee *taskEmitterWrapper) EmitStatusProgress(percentage float64, message string) {
ee.Emit(eventTypeStatusProgress, eventStatusProgress{Message: message, Percentage: percentage})
}