nmdc-telegramfrontend/coalesce.go

47 lines
1.1 KiB
Go
Raw Permalink Normal View History

package main
import (
"time"
)
const (
coalesceWorkerRescanEvery time.Duration = 10 * time.Second
coalesceWorkerExpireAfter time.Duration = 20 * time.Second
)
func coalesceKey(hubNick, message string) string {
return hubNick + "\x00" + message
}
func (this *NTFServer) coalesceWorker() {
for {
time.Sleep(coalesceWorkerRescanEvery)
deadLine := time.Now().Add(-coalesceWorkerExpireAfter)
this.coalesceBufferMut.Lock()
for k, v := range this.coalesceBuffer {
if v.Before(deadLine) {
delete(this.coalesceBuffer, k)
}
}
this.coalesceBufferMut.Unlock()
}
}
// Coalesce returns true if the message sticks to an existing one.
// It adds it into the coalesce buffer anyway.
func (this *NTFServer) Coalesce(hubNick, message string) bool {
ckey := coalesceKey(hubNick, message)
this.coalesceBufferMut.Lock()
if _, ok := this.coalesceBuffer[ckey]; ok {
this.coalesceBufferMut.Unlock()
return true // stuck to existing
} else {
this.coalesceBuffer[ckey] = time.Now()
this.coalesceBufferMut.Unlock()
return false // first we've seen it
}
}