-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbusiness_dedup.go
More file actions
61 lines (49 loc) · 1.63 KB
/
Copy pathbusiness_dedup.go
File metadata and controls
61 lines (49 loc) · 1.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package botapi
import (
"strconv"
"sync"
"github.com/gotd/td/tg"
)
// businessDedupSize is the number of recent business messages remembered for
// deduplication. Telegram may redeliver updates (notably to bots after a
// reconnect), and the qts sequence does not always suppress this; the window
// only needs to cover the burst a redelivery replays.
const businessDedupSize = 4096
// businessDedup remembers recently delivered business messages so a redelivered
// update does not fire handlers — and reply — twice. It is a fixed-size set with
// FIFO eviction: safe for concurrent use, bounded in memory.
type businessDedup struct {
mu sync.Mutex
seen map[string]struct{}
ring []string
pos int
}
func newBusinessDedup(size int) *businessDedup {
return &businessDedup{
seen: make(map[string]struct{}, size),
ring: make([]string, size),
}
}
// fresh reports whether key has not been seen recently, recording it. A repeated
// key (a redelivered update) returns false.
func (d *businessDedup) fresh(key string) bool {
d.mu.Lock()
defer d.mu.Unlock()
if _, ok := d.seen[key]; ok {
return false
}
if old := d.ring[d.pos]; old != "" {
delete(d.seen, old)
}
d.ring[d.pos] = key
d.pos = (d.pos + 1) % len(d.ring)
d.seen[key] = struct{}{}
return true
}
// businessMessageKey identifies a business message for deduplication. The edit
// date distinguishes a genuine edit (which should be handled) from a redelivery
// of the same message (which should not).
func businessMessageKey(connectionID string, m *tg.Message) string {
edit, _ := m.GetEditDate()
return connectionID + ":" + strconv.Itoa(m.ID) + ":" + strconv.Itoa(edit)
}