Skip to content

Commit dca2f0f

Browse files
committed
log if discord messages are dropped because of full buffer
1 parent 277c501 commit dca2f0f

1 file changed

Lines changed: 28 additions & 5 deletions

File tree

fact/util.go

Lines changed: 28 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import (
1212
"sort"
1313
"strings"
1414
"sync"
15+
"sync/atomic"
1516
"time"
1617

1718
"github.com/bwmarrin/discordgo"
@@ -34,6 +35,9 @@ var (
3435
banLock sync.Mutex
3536
AutoLaunchLock sync.Mutex
3637
FactRunningLock sync.Mutex
38+
39+
cmsDropCount uint64
40+
cmsLastDropLogUnixNano int64
3741
)
3842

3943
func GetFactUPS() (float64, float64, float64) {
@@ -1389,11 +1393,30 @@ func CMS(channel string, text string) {
13891393
lines := strings.Split(text, "\n")
13901394

13911395
for _, line := range lines {
1392-
var item disc.CMSBuf
1393-
item.Channel = channel
1394-
item.Text = line
1395-
1396-
disc.CMSChan <- item
1396+
item := disc.CMSBuf{Channel: channel, Text: line}
1397+
1398+
select {
1399+
case disc.CMSChan <- item:
1400+
default:
1401+
// Buffer is full; drop the oldest message to make room, otherwise drop this one.
1402+
select {
1403+
case <-disc.CMSChan:
1404+
default:
1405+
}
1406+
select {
1407+
case disc.CMSChan <- item:
1408+
default:
1409+
atomic.AddUint64(&cmsDropCount, 1)
1410+
now := time.Now().UnixNano()
1411+
last := atomic.LoadInt64(&cmsLastDropLogUnixNano)
1412+
if now-last > int64(10*time.Second) && atomic.CompareAndSwapInt64(&cmsLastDropLogUnixNano, last, now) {
1413+
dropped := atomic.SwapUint64(&cmsDropCount, 0)
1414+
if dropped > 0 {
1415+
cwlog.DoLogCW("Discord CMS buffer full; dropped %d messages (Discord down or rate-limited).", dropped)
1416+
}
1417+
}
1418+
}
1419+
}
13971420
}
13981421
}
13991422

0 commit comments

Comments
 (0)