forked from lonng/nano
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pipeline.go
78 lines (65 loc) · 1.53 KB
/
pipeline.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
package pipeline
import (
"sync"
"github.com/lonng/nano/internal/message"
"github.com/lonng/nano/session"
)
type (
// Message is the alias of `message.Message`
Message = message.Message
Func func(s *session.Session, msg *message.Message) error
Pipeline interface {
Outbound() Channel
Inbound() Channel
}
pipeline struct {
outbound, inbound *pipelineChannel
}
Channel interface {
PushFront(h Func)
PushBack(h Func)
Process(s *session.Session, msg *message.Message) error
}
pipelineChannel struct {
mu sync.RWMutex
handlers []Func
}
)
func New() Pipeline {
return &pipeline{
outbound: &pipelineChannel{},
inbound: &pipelineChannel{},
}
}
func (p *pipeline) Outbound() Channel { return p.outbound }
func (p *pipeline) Inbound() Channel { return p.inbound }
// PushFront push a function to the front of the pipeline
func (p *pipelineChannel) PushFront(h Func) {
p.mu.Lock()
defer p.mu.Unlock()
handlers := make([]Func, len(p.handlers)+1)
handlers[0] = h
copy(handlers[1:], p.handlers)
p.handlers = handlers
}
// PushFront push a function to the end of the pipeline
func (p *pipelineChannel) PushBack(h Func) {
p.mu.Lock()
defer p.mu.Unlock()
p.handlers = append(p.handlers, h)
}
// Process process message with all pipeline functions
func (p *pipelineChannel) Process(s *session.Session, msg *message.Message) error {
p.mu.RLock()
defer p.mu.RUnlock()
if len(p.handlers) < 1 {
return nil
}
for _, h := range p.handlers {
err := h(s, msg)
if err != nil {
return err
}
}
return nil
}