/
assembler.go
56 lines (49 loc) · 1.31 KB
/
assembler.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
package gelf
import (
"bytes"
"time"
)
// Assembler provides GELF message de-chunking
type Assembler struct {
deadline time.Time
fullMsg [][]byte
processed int
totalBytes, maxMessageSize int
}
// NewAssembler returns empty Assembler with maximum message size and duration
// specified.
func NewAssembler(maxMessageSize int, timeout time.Duration) (res *Assembler) {
res = new(Assembler)
res.deadline = time.Now().Add(timeout)
res.maxMessageSize = maxMessageSize
return
}
// Bytes returns message bytes, not nessesarily fully assembled
func (a *Assembler) Bytes() []byte {
return bytes.Join(a.fullMsg, nil)
}
// Expired returns true if first chunk is too old
func (a *Assembler) Expired() bool {
return time.Now().After(a.deadline)
}
// Update feeds the byte chunk to Assembler, returns ok when the message is
// complete.
func (a *Assembler) Update(chunk Chunk) bool {
num, count := chunk.Sequence()
if a.fullMsg == nil {
a.fullMsg = make([][]byte, count)
}
if count != len(a.fullMsg) || num >= count {
return false
}
body := chunk.Body()
if a.fullMsg[num] == nil {
a.totalBytes += len(body)
if a.maxMessageSize > 0 && a.totalBytes > a.maxMessageSize {
return false
}
a.fullMsg[num] = body
a.processed++
}
return a.processed == len(a.fullMsg)
}