-
Notifications
You must be signed in to change notification settings - Fork 27
/
mplex.go
91 lines (76 loc) · 1.88 KB
/
mplex.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
package proximitytransport
/*
The mplex struct as NOT relationship with libp2p mplex package!!!
This mplex struct is a multiplexer taken multiple inputs for one output.
You must initialize mplex by setting input and output before running it.
There are two types of input:
1) RingBufferMap
2) builtin chan []byte
There is only one type of output: *io.PipeWriter
When you start mplex, its flushed buffers first in the order you set them,
and read on its chan []byte.
*/
import (
"context"
"io"
"sync"
"go.uber.org/zap"
"berty.tech/weshnet/pkg/logutil"
)
type mplex struct {
inputCaches []*RingBufferMap
inputLock sync.Mutex
input chan []byte
output *io.PipeWriter
ctx context.Context
logger *zap.Logger
}
func newMplex(ctx context.Context, logger *zap.Logger) *mplex {
logger = logger.Named("mplex")
return &mplex{
input: make(chan []byte),
ctx: ctx,
logger: logger,
}
}
func (m *mplex) setOutput(o *io.PipeWriter) {
m.output = o
}
func (m *mplex) addInputCache(c *RingBufferMap) {
m.inputLock.Lock()
m.inputCaches = append(m.inputCaches, c)
m.inputLock.Unlock()
}
func (m *mplex) write(s []byte) {
m.logger.Debug("write", logutil.PrivateBinary("payload", s))
_, err := m.output.Write(s)
if err != nil {
m.logger.Error("write: write pipe error", zap.Error(err))
} else {
m.logger.Debug("write: successful write pipe")
}
}
// run flushes caches and read input channel
func (m *mplex) run(peerID string) {
m.logger.Debug("run: started")
// flush caches
m.inputLock.Lock()
for _, cache := range m.inputCaches {
m.logger.Debug("run: flushing one cache")
payloads := cache.Flush(peerID)
for payload := range payloads {
m.write(payload)
}
}
m.inputLock.Unlock()
// read input
m.logger.Debug("run: reading input channel")
for {
select {
case payload := <-m.input:
m.write(payload)
case <-m.ctx.Done():
return
}
}
}