go-libp2p-pubsub/midgen.go

46 lines
939 B
Go
Raw Normal View History

package pubsub
2022-01-09 18:14:39 +02:00
import (
"sync"
)
2022-01-09 18:14:39 +02:00
// msgIDGenerator handles computing IDs for msgs
// It allows setting custom generators(MsgIdFunction) per topic
type msgIDGenerator struct {
2022-01-09 18:14:39 +02:00
Default MsgIdFunction
topicGens map[string]MsgIdFunction
topicGensLk sync.RWMutex
}
2022-01-09 18:14:39 +02:00
func newMsgIdGenerator() *msgIDGenerator{
return &msgIDGenerator{
Default: DefaultMsgIdFn,
topicGens: make(map[string]MsgIdFunction),
}
}
// Set sets custom id generator(MsgIdFunction) for topic.
func (m *msgIDGenerator) Set(topic string, gen MsgIdFunction) {
m.topicGensLk.Lock()
m.topicGens[topic] = gen
m.topicGensLk.Unlock()
}
2022-01-09 18:14:39 +02:00
// ID computes ID for the msg or short-circuits with the cached value.
func (m *msgIDGenerator) ID(msg *Message) string {
if msg.ID != "" {
return msg.ID
}
m.topicGensLk.RLock()
gen, ok := m.topicGens[msg.GetTopic()]
m.topicGensLk.RUnlock()
if !ok {
2022-01-09 18:14:39 +02:00
gen = m.Default
}
msg.ID = gen(msg.Message)
return msg.ID
}