github.com/artisanhe/tools@v1.0.1-0.20210607022958-19a8fef2eb04/catgo/cat-go/cat/aggregator.go (about) 1 package cat 2 3 import ( 4 "bytes" 5 "strconv" 6 7 "github.com/artisanhe/tools/catgo/cat-go/message" 8 ) 9 10 const batchFlag = '@' 11 const batchSplit = ';' 12 13 type catLocalAggregator struct { 14 event *eventAggregator 15 transaction *transactionAggregator 16 metric *metricAggregator 17 } 18 19 func (p *catLocalAggregator) flush(m message.Messager) { 20 switch m := m.(type) { 21 case *message.Transaction: 22 23 sender.handleTransaction(m) 24 default: 25 logger.Warning("Aggregator flusher expected a transaction.") 26 } 27 } 28 29 func (p *catLocalAggregator) Background() { 30 go background(p.event) 31 go background(p.transaction) 32 go background(p.metric) 33 } 34 35 type Buf struct { 36 bytes.Buffer 37 } 38 39 func newBuf() *Buf { 40 return &Buf{ 41 *bytes.NewBuffer([]byte{}), 42 } 43 } 44 45 func (b *Buf) WriteInt(i int) (err error) { 46 if _, err = b.WriteString(strconv.Itoa(i)); err != nil { 47 return 48 } 49 return 50 } 51 52 func (b *Buf) WriteUInt64(i uint64) (err error) { 53 if _, err = b.WriteString(strconv.FormatUint(i, 10)); err != nil { 54 return 55 } 56 return 57 } 58 59 func computeDuration(durationInMillis int) int { 60 if durationInMillis < 1 { 61 return 1 62 } else if durationInMillis < 20 { 63 return durationInMillis 64 } else if durationInMillis < 200 { 65 return durationInMillis - durationInMillis%5 66 } else if durationInMillis < 500 { 67 return durationInMillis - durationInMillis%20 68 } else if durationInMillis < 2000 { 69 return durationInMillis - durationInMillis%50 70 } else if durationInMillis < 20000 { 71 return durationInMillis - durationInMillis%500 72 } else if durationInMillis < 1000000 { 73 return durationInMillis - durationInMillis%10000 74 } else { 75 dk := 524288 76 if durationInMillis > 3600*1000 { 77 dk = 3600 * 1000 78 } else { 79 for dk < durationInMillis { 80 dk <<= 1 81 } 82 } 83 return dk 84 } 85 } 86 87 var aggregator = catLocalAggregator{ 88 event: newEventAggregator(), 89 transaction: newTransactionAggregator(), 90 metric: newMetricAggregator(), 91 }