You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
85 lines
1.4 KiB
Go
85 lines
1.4 KiB
Go
2 years ago
|
package pipeline
|
||
2 years ago
|
|
||
|
import (
|
||
2 years ago
|
"git.noahlan.cn/noahlan/nnet/entity"
|
||
2 years ago
|
"sync"
|
||
|
)
|
||
|
|
||
|
type (
|
||
2 years ago
|
Func func(entity entity.NetworkEntity, v interface{}) error
|
||
2 years ago
|
|
||
|
// Pipeline 消息管道
|
||
|
Pipeline interface {
|
||
|
Outbound() Channel
|
||
|
Inbound() Channel
|
||
|
}
|
||
|
|
||
|
pipeline struct {
|
||
|
outbound, inbound *pipelineChannel
|
||
|
}
|
||
|
|
||
|
Channel interface {
|
||
|
PushFront(h Func)
|
||
|
PushBack(h Func)
|
||
2 years ago
|
Process(entity entity.NetworkEntity, v interface{}) error
|
||
2 years ago
|
}
|
||
|
|
||
|
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 将func压入slice首位
|
||
|
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
|
||
|
}
|
||
|
|
||
|
// PushBack 将func压入slice末位
|
||
|
func (p *pipelineChannel) PushBack(h Func) {
|
||
|
p.mu.Lock()
|
||
|
defer p.mu.Unlock()
|
||
|
|
||
|
p.handlers = append(p.handlers, h)
|
||
|
}
|
||
|
|
||
|
// Process 处理所有的pipeline方法
|
||
2 years ago
|
func (p *pipelineChannel) Process(entity entity.NetworkEntity, v interface{}) error {
|
||
2 years ago
|
if len(p.handlers) < 1 {
|
||
|
return nil
|
||
|
}
|
||
|
|
||
2 years ago
|
p.mu.RLock()
|
||
|
defer p.mu.RUnlock()
|
||
|
|
||
2 years ago
|
for _, handler := range p.handlers {
|
||
2 years ago
|
err := handler(entity, v)
|
||
2 years ago
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
}
|
||
|
return nil
|
||
|
}
|