-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdecode_worker.go
More file actions
89 lines (80 loc) · 1.78 KB
/
decode_worker.go
File metadata and controls
89 lines (80 loc) · 1.78 KB
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
package xray
import (
"context"
"sync"
)
type decodeChunk struct {
stream *wrappedStream
dir Direction
data []byte
}
// decodeWorker processes decode chunks from all streams in a single goroutine,
// keeping proto unmarshalling entirely off the hot path.
type decodeWorker struct {
ch chan decodeChunk
cancel context.CancelFunc
wg sync.WaitGroup
}
func newDecodeWorker() *decodeWorker {
ctx, cancel := context.WithCancel(context.Background())
w := &decodeWorker{
ch: make(chan decodeChunk, 4096),
cancel: cancel,
}
w.wg.Go(func() {
for {
select {
case <-ctx.Done():
return
case chunk := <-w.ch:
w.process(chunk)
}
}
})
return w
}
func (w *decodeWorker) process(chunk decodeChunk) {
s := chunk.stream
if s.failed {
return
}
emit := func(wireBytes int, tags []Tag, parsed any) {
msg := DecodedMessage{
StreamID: s.streamID,
ConnID: s.wconn.connID,
Protocol: s.protocol,
Direction: chunk.dir,
WireBytes: wireBytes,
Tags: tags,
Parsed: parsed,
}
for _, fn := range s.handlers {
fn(msg)
}
}
var err error
switch chunk.dir {
case DirectionIn:
err = s.decoder.ObserveRead(chunk.data, emit)
case DirectionOut:
err = s.decoder.ObserveWrite(chunk.data, emit)
}
if err != nil {
s.decoder.Reset()
s.failed = true
}
}
// sendShared enqueues data for async decoding without copying. The caller must
// guarantee the slice is not mutated after this call (e.g. it was just allocated
// for the matching envelope and is not reused). Drops silently if the channel
// is full.
func (w *decodeWorker) sendShared(s *wrappedStream, dir Direction, data []byte) {
select {
case w.ch <- decodeChunk{stream: s, dir: dir, data: data}:
default:
}
}
func (w *decodeWorker) stop() {
w.cancel()
w.wg.Wait()
}