This repository has been archived by the owner on Jul 31, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprocessor.go
74 lines (66 loc) · 1.59 KB
/
processor.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
package commands
import (
"sync"
"errors"
)
type commandProcessEntry struct {
cmd Command
handler CommandHandler
callback CommandCallback
}
type CommandProcessor interface {
Process(cmd Command, handler CommandHandler, callback CommandCallback) error
Stop()
}
type defaultCommandProcessor struct {
ch chan *commandProcessEntry
running bool
mutex *sync.RWMutex
}
func NewDefaultCommandProcessor(bufferSize int) CommandProcessor {
p := &defaultCommandProcessor{
ch: make(chan *commandProcessEntry, bufferSize),
running: true,
mutex: new(sync.RWMutex),
}
go p.run()
return p
}
func (p *defaultCommandProcessor) Process(cmd Command, handler CommandHandler, callback CommandCallback) error {
if cmd == nil {
return errors.New("command processor process failed, cmd is nil.")
}
if handler == nil {
return errors.New("command processor process failed, handler is nil.")
}
if callback == nil {
return errors.New("command processor process failed, callback is nil.")
}
p.mutex.RLock()
defer p.mutex.RUnlock()
if !p.running {
return errors.New("command processor process failed, stopped.")
}
p.ch <- &commandProcessEntry{cmd:cmd, handler:handler, callback:callback}
return nil
}
func (p *defaultCommandProcessor) Stop() {
p.mutex.Lock()
defer p.mutex.Unlock()
close(p.ch)
p.running = false
}
func (p *defaultCommandProcessor) run() {
for p.running {
entry, ok := <- p.ch
if !ok {
break
}
resultData, err := entry.handler.Handle(entry.cmd, nil)
if err != nil {
entry.callback.On(nil, err)
continue
}
entry.callback.On(newDefaultCommandResult(resultData), nil)
}
}