github.com/artisanhe/tools@v1.0.1-0.20210607022958-19a8fef2eb04/catgo/cat-go/cat/manager.go (about) 1 package cat 2 3 import ( 4 "fmt" 5 "sync/atomic" 6 "time" 7 8 "github.com/artisanhe/tools/catgo/cat-go/message" 9 ) 10 11 type catMessageManager struct { 12 index uint32 13 offset uint32 14 hour int 15 messageIdPrefix string 16 } 17 18 func (p *catMessageManager) sendTransaction(t *message.Transaction) { 19 sender.handleTransaction(t) 20 } 21 22 func (p *catMessageManager) sendEvent(t *message.Event) { 23 sender.handleEvent(t) 24 } 25 26 func (p *catMessageManager) flush(m message.Messager) { 27 switch m := m.(type) { 28 case *message.Transaction: 29 if m.Status != SUCCESS { 30 sender.handleTransaction(m) 31 } else if p.hitSample(router.sample) { 32 sender.handleTransaction(m) 33 } else { 34 aggregator.transaction.Put(m) 35 } 36 case *message.Event: 37 if m.Status != SUCCESS { 38 sender.handleEvent(m) 39 } else { 40 aggregator.event.Put(m) 41 } 42 default: 43 logger.Warning("Unrecognized message type.") 44 } 45 } 46 47 func (p *catMessageManager) hitSample(sampleRate float64) bool { 48 if sampleRate > 1.0 { 49 return true 50 } else if sampleRate < 1e-9 { 51 return false 52 } 53 var cycle = uint32(1 / sampleRate) 54 55 var current, next uint32 56 for { 57 current = atomic.LoadUint32(&p.offset) 58 next = (current + 1) % cycle 59 if atomic.CompareAndSwapUint32(&p.offset, current, next) { 60 break 61 } 62 } 63 return next == 0 64 } 65 66 func (p *catMessageManager) nextId() string { 67 hour := int(time.Now().Unix() / 3600) 68 69 if hour != p.hour { 70 p.hour = hour 71 p.messageIdPrefix = fmt.Sprintf("%s-%s-%d", config.domain, config.ipHex, hour) 72 73 currentIndex := atomic.LoadUint32(&p.index) 74 if atomic.CompareAndSwapUint32(&p.index, currentIndex, 0) { 75 logger.Info("MessageId prefix has changed to: %s", p.messageIdPrefix) 76 } 77 } 78 79 return fmt.Sprintf("%s-%d", p.messageIdPrefix, atomic.AddUint32(&p.index, 1)) 80 } 81 82 var manager = catMessageManager{ 83 index: 0, 84 offset: 0, 85 hour: 0, 86 }