This repository has been archived by the owner on Feb 20, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
paralleldispatcher.go
127 lines (105 loc) · 2.35 KB
/
paralleldispatcher.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
124
125
126
127
package command
import (
"sync"
"sync/atomic"
"github.com/nproc/errorgroup-go"
)
// NewParallelDispatcher creates a new PrallelDispatcher with the given handlers
func NewParallelDispatcher(handlers []Handler) Dispatcher {
return &ParallelDispatcher{
handlers: handlers,
mutex: sync.RWMutex{},
}
}
// ParallelDispatcher is a command dispatcher wich will run all handlers in
// parallel and wait all handlers to finish before returning.
//
// All errors returned by the handlers will be grouped in a
// `errorgroup.ErrorGroup`.
//
// This dispatcher is *thread safe*.
type ParallelDispatcher struct {
handlers []Handler
mutex sync.RWMutex
}
// AppendHandlers implements `Dispatcher.AppendHandlers`
func (d *ParallelDispatcher) AppendHandlers(handlers ...Handler) {
d.mutex.Lock()
defer d.mutex.Unlock()
Loop:
for _, newHandler := range handlers {
for _, existingHandler := range d.handlers {
if newHandler == existingHandler {
continue Loop
}
}
d.handlers = append(d.handlers, newHandler)
}
}
// Dispatch implements `Dispatcher.Dispatch`
func (d *ParallelDispatcher) Dispatch(cmd interface{}) (err error) {
d.mutex.RLock()
defer d.mutex.RUnlock()
defer func() {
if e := recover(); e != nil {
err = e.(error)
}
}()
var found int32
wg := &sync.WaitGroup{}
errCh := make(chan error, len(d.handlers))
for _, handler := range d.handlers {
wg.Add(1)
go d.dispatch(wg, errCh, &found, handler, cmd)
}
wg.Wait()
close(errCh)
if found != 1 {
return &NoHandlerFoundError{
Command: cmd,
}
}
errs := []error{}
for {
e, ok := <-errCh
if !ok {
break
}
if e == nil {
continue
}
errs = append(errs, e)
}
if len(errs) == 0 {
return
}
err = errorgroup.New(errs)
return
}
func (d *ParallelDispatcher) dispatch(wg *sync.WaitGroup, errCh chan error, found *int32, handler Handler, cmd interface{}) {
var err error
defer func() {
if e := recover(); e != nil {
err = e.(error)
}
errCh <- err
wg.Done()
}()
if !handler.CanHandle(cmd) {
return
}
atomic.StoreInt32(found, 1)
err = handler.Handle(cmd, d)
}
// DispatchOptional implements `Dispatcher.DispatchOptional`
func (d *ParallelDispatcher) DispatchOptional(cmd interface{}) (err error) {
d.mutex.RLock()
defer d.mutex.RUnlock()
err = d.Dispatch(cmd)
switch err.(type) {
case *NoHandlerFoundError:
return nil
default:
return err
}
}