-
Notifications
You must be signed in to change notification settings - Fork 0
/
replaydecoder.go
71 lines (59 loc) · 1.52 KB
/
replaydecoder.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
package channel
import (
"sync"
"github.com/kklab-com/gone/utils"
kklogger "github.com/kklab-com/goth-kklogger"
"github.com/kklab-com/goth-kkutil/buf"
kkpanic "github.com/kklab-com/goth-panic"
)
type ReplayState int
type ReplayDecoder struct {
ByteToMessageDecoder
in buf.ByteBuf
state ReplayState
op sync.Mutex
}
var replayDecoderTruncateLen = 1 << 20
func NewReplayDecoder(state ReplayState, decode func(ctx HandlerContext, in buf.ByteBuf, out *utils.Queue)) *ReplayDecoder {
return &ReplayDecoder{
ByteToMessageDecoder: ByteToMessageDecoder{
Decode: decode,
},
state: state,
}
}
func (h *ReplayDecoder) Skip() {
panic(buf.ErrInsufficientSize)
}
func (h *ReplayDecoder) State() ReplayState {
return h.state
}
func (h *ReplayDecoder) Checkpoint(state ReplayState) {
h.state = state
if h.in.Cap()-h.in.ReadableBytes() > replayDecoderTruncateLen {
h.op.Lock()
defer h.op.Unlock()
bs := h.in.Bytes()
h.in.Reset()
h.in.Write(bs)
}
}
func (h *ReplayDecoder) Added(ctx HandlerContext) {
h.in = buf.EmptyByteBuf()
}
func (h *ReplayDecoder) Read(ctx HandlerContext, obj interface{}) {
if h.Decode != nil {
h.in.Write(obj.(buf.ByteBuf).Bytes())
out := &utils.Queue{}
kkpanic.CatchExcept(func() {
h.Decode(ctx, h.in, out)
}, buf.ErrInsufficientSize, func(r kkpanic.Caught) {
kklogger.ErrorJ("ReplayDecoder.Read#Decode", r.String())
})
for elem := out.Pop(); elem != nil; elem = out.Pop() {
ctx.FireRead(elem)
}
} else {
kklogger.WarnJ("ReplayDecoder.Read#Decode", "no decoder")
}
}