This repository has been archived by the owner on Aug 2, 2022. It is now read-only.
/
pumper.go
397 lines (336 loc) · 8.11 KB
/
pumper.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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
// Copyright 2015 someonegg. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package bdmsg
import (
"errors"
"github.com/someonegg/gocontainer/bufpool"
"github.com/someonegg/gox/syncx"
"golang.org/x/net/context"
"sync"
"sync/atomic"
)
var (
errUnknownPanic = errors.New("unknown panic")
)
type msgEntry struct {
t MsgType
m Msg
}
// PumperHandler is the interface that can be registered
// to process messages in the message pumper.
type PumperHandler interface {
Process(ctx context.Context, p *Pumper, t MsgType, m Msg)
}
type PumperStatis struct {
// message count
InTotal int64
InProcess int64
OutTotal int64
OutProcess int64
// message bytes
BytesReaded int64 // from rw
BytesWritten int64 // to rw
}
// Pumper represents a message pumper. It has a working loop
// which reads, processes and writes messages continuously.
//
// Multiple goroutines can invoke methods on a Pumper simultaneously.
type Pumper struct {
err error
quitF context.CancelFunc
stopD syncx.DoneChan
rw MsgReadWriter
h PumperHandler
ud interface{}
// read
rerr error
rD syncx.DoneChan
rQ chan msgEntry
// write
werr error
wD syncx.DoneChan
wQ chan msgEntry
stat PumperStatis
}
// NewPumper allocates and returns a new Pumper.
func NewPumper(rw MsgReadWriter, h PumperHandler, inN, outN int) *Pumper {
t := &Pumper{}
t.init(rw, h, inN, outN)
return t
}
func (p *Pumper) init(rw MsgReadWriter, h PumperHandler, inN, outN int) {
p.stopD = syncx.NewDoneChan()
p.rw = rw
p.h = h
p.rD = syncx.NewDoneChan()
p.rQ = make(chan msgEntry, inN)
p.wD = syncx.NewDoneChan()
p.wQ = make(chan msgEntry, outN)
}
// Start the pumper, parent and/or sn can be nil.
// If sn is not nil, it will be called when the working loop exits.
func (p *Pumper) Start(parent context.Context, sn StopNotifier) {
if parent == nil {
parent = context.Background()
}
var ctx context.Context
ctx, p.quitF = context.WithCancel(parent)
rwctx, rwqF := context.WithCancel(context.Background())
go p.reading(rwctx)
go p.writing(rwctx)
go p.work(ctx, rwqF, sn)
}
func (p *Pumper) work(ctx context.Context,
rwqF context.CancelFunc, sn StopNotifier) {
defer p.ending(rwqF, sn)
for q := false; !q; {
select {
case <-ctx.Done():
q = true
case e := <-p.rQ:
atomic.AddInt64(&p.stat.InProcess, 1)
p.procMsg(ctx, e.t, e.m)
bufpool.Put(e.m)
case <-p.rD:
q = true
case <-p.wD:
q = true
}
}
}
func (p *Pumper) ending(rwqF context.CancelFunc, sn StopNotifier) {
if e := recover(); e != nil {
switch v := e.(type) {
case error:
p.err = v
default:
p.err = errUnknownPanic
}
}
defer func() { recover() }()
defer p.stopD.SetDone()
// if ending from error.
p.quitF()
rwqF()
if sn != nil {
sn.OnStop()
}
<-p.rD
<-p.wD
}
func (p *Pumper) procMsg(ctx context.Context, t MsgType, m Msg) {
p.h.Process(ctx, p, t, m)
}
func (p *Pumper) reading(ctx context.Context) {
defer func() {
if e := recover(); e != nil {
switch v := e.(type) {
case error:
p.rerr = v
default:
p.rerr = errUnknownPanic
}
}
p.rD.SetDone()
}()
for q := false; !q; {
t, m := p.readMsg()
select {
case <-ctx.Done():
q = true
case p.rQ <- msgEntry{t, m}:
atomic.AddInt64(&p.stat.InTotal, 1)
}
}
}
func (p *Pumper) readMsg() (MsgType, Msg) {
t, m, err := p.rw.ReadMsg()
if err != nil {
panic(err)
}
atomic.AddInt64(&p.stat.BytesReaded, int64(len(m)))
return t, m
}
func (p *Pumper) writing(ctx context.Context) {
defer func() {
if e := recover(); e != nil {
switch v := e.(type) {
case error:
p.werr = v
default:
p.werr = errUnknownPanic
}
}
p.wD.SetDone()
}()
for q := false; !q; {
select {
case <-ctx.Done():
q = true
case e := <-p.wQ:
atomic.AddInt64(&p.stat.OutProcess, 1)
p.writeMsg(e.t, e.m)
bufpool.Put(e.m)
}
}
}
func (p *Pumper) writeMsg(t MsgType, m Msg) {
err := p.rw.WriteMsg(t, m)
if err != nil {
panic(err)
}
atomic.AddInt64(&p.stat.BytesWritten, int64(len(m)))
}
// Err returns non-nil if an error has happened.
// When errored, the pumper will stop.
func (p *Pumper) Err() error {
if p.err != nil {
return p.err
}
if p.rerr != nil {
return p.rerr
}
return p.werr
}
// Stop requests to stop the working loop.
func (p *Pumper) Stop() {
p.quitF()
}
// StopD returns a done channel, it will be
// signaled when the pumper is stopped.
func (p *Pumper) StopD() syncx.DoneChanR {
return p.stopD.R()
}
func (p *Pumper) Stopped() bool {
return p.stopD.R().Done()
}
// Input copies the message data to the in-queue.
func (p *Pumper) Input(t MsgType, m Msg) {
cp := bufpool.Get(len(m))
copy(cp, m)
select {
case p.rQ <- msgEntry{t, cp}:
atomic.AddInt64(&p.stat.InTotal, 1)
case <-p.stopD:
bufpool.Put(cp)
}
}
// TryInput tries to copy the message data to the in-queue.
func (p *Pumper) TryInput(t MsgType, m Msg) bool {
cp := bufpool.Get(len(m))
copy(cp, m)
select {
case p.rQ <- msgEntry{t, cp}:
atomic.AddInt64(&p.stat.InTotal, 1)
return true
default:
bufpool.Put(cp)
return false
}
}
// Output copies the message data to the out-queue.
func (p *Pumper) Output(t MsgType, m Msg) {
cp := bufpool.Get(len(m))
copy(cp, m)
select {
case p.wQ <- msgEntry{t, cp}:
atomic.AddInt64(&p.stat.OutTotal, 1)
case <-p.stopD:
bufpool.Put(cp)
}
}
// TryOutput tries to copy the message data to the out-queue.
func (p *Pumper) TryOutput(t MsgType, m Msg) bool {
cp := bufpool.Get(len(m))
copy(cp, m)
select {
case p.wQ <- msgEntry{t, cp}:
atomic.AddInt64(&p.stat.OutTotal, 1)
return true
default:
bufpool.Put(cp)
return false
}
}
func (p *Pumper) Statis() *PumperStatis {
return &PumperStatis{
InTotal: atomic.LoadInt64(&p.stat.InTotal),
InProcess: atomic.LoadInt64(&p.stat.InProcess),
OutTotal: atomic.LoadInt64(&p.stat.OutTotal),
OutProcess: atomic.LoadInt64(&p.stat.OutProcess),
BytesReaded: atomic.LoadInt64(&p.stat.BytesReaded),
BytesWritten: atomic.LoadInt64(&p.stat.BytesWritten),
}
}
// UserData returns the data user setted.
func (p *Pumper) UserData() interface{} {
return p.ud
}
func (p *Pumper) SetUserData(ud interface{}) {
p.ud = ud
}
// InnerMsgRW returns the inner message readwriter.
// You should make sure that its implements support concurrently
// access if you want to call its methods.
func (p *Pumper) InnerMsgRW() MsgReadWriter {
return p.rw
}
// PumpMux is an message request multiplexer.
//
// It matches the type of each message against a list of registered
// types and calls the matched handler.
//
// Multiple goroutines can invoke methods on a PumpMux simultaneously.
type PumpMux struct {
mu sync.RWMutex
m map[MsgType]PumperHandler
orphan PumperHandler
}
// NewPumpMux allocates and returns a new PumpMux.
func NewPumpMux(orphan PumperHandler) *PumpMux {
return &PumpMux{
m: make(map[MsgType]PumperHandler),
orphan: orphan,
}
}
// Process dispatches the request to the handler whose
// type matches the message type.
func (mux *PumpMux) Process(ctx context.Context, p *Pumper, t MsgType, m Msg) {
mux.mu.RLock()
defer mux.mu.RUnlock()
if h, ok := mux.m[t]; ok {
h.Process(ctx, p, t, m)
} else {
if mux.orphan != nil {
mux.orphan.Process(ctx, p, t, m)
}
}
}
// Handle registers the handler for the given type.
// If a handler already exists for type, Handle panics.
func (mux *PumpMux) Handle(t MsgType, h PumperHandler) {
mux.mu.Lock()
defer mux.mu.Unlock()
if h == nil {
panic("msgpump: nil handler")
}
if _, ok := mux.m[t]; ok {
panic("msgpump: multiple registrations")
}
mux.m[t] = h
}
// HandleFunc registers the handler function for the given type.
func (mux *PumpMux) HandleFunc(t MsgType, h func(context.Context,
*Pumper, MsgType, Msg)) {
mux.Handle(t, HandlerFunc(h))
}
// The HandlerFunc type is an adapter to allow the use of
// ordinary functions as message handlers. If f is a function
// with the appropriate signature, HandlerFunc(f) is a
// PumperHandler object that calls f.
type HandlerFunc func(context.Context, *Pumper, MsgType, Msg)
// Process calls f(ctx, p, t, m).
func (f HandlerFunc) Process(ctx context.Context, p *Pumper, t MsgType, m Msg) {
f(ctx, p, t, m)
}