forked from dunglas/mercure
-
Notifications
You must be signed in to change notification settings - Fork 0
/
topic_selector.go
100 lines (83 loc) · 2.32 KB
/
topic_selector.go
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package mercure
import (
"fmt"
"regexp"
"strings"
"github.com/dgraph-io/ristretto"
uritemplate "github.com/yosida95/uritemplate/v3"
)
// Gather stats to find the best default values.
const (
TopicSelectorStoreDefaultCacheNumCounters = int64(6e7)
TopicSelectorStoreCacheMaxCost = int64(1e8) // 100 MB
)
// TopicSelectorStore caches compiled templates to improve memory and CPU usage.
type TopicSelectorStore struct {
cache *ristretto.Cache
}
// NewTopicSelectorStore creates a TopicSelectorStore instance.
// See https://github.com/dgraph-io/ristretto, set values to 0 to disable.
func NewTopicSelectorStore(cacheNumCounters, cacheMaxCost int64) (*TopicSelectorStore, error) {
if cacheNumCounters == 0 {
return &TopicSelectorStore{}, nil
}
cache, err := ristretto.NewCache(&ristretto.Config{
NumCounters: cacheNumCounters,
MaxCost: cacheMaxCost,
BufferItems: 64,
})
if err != nil {
return nil, fmt.Errorf("unable to create cache: %w", err)
}
return &TopicSelectorStore{cache: cache}, nil
}
func (tss *TopicSelectorStore) match(topic, topicSelector string) bool {
// Always do an exact matching comparison first
// Also check if the topic selector is the reserved keyword *
if topicSelector == "*" || topic == topicSelector {
return true
}
r := tss.getRegexp(topicSelector)
if r == nil {
return false
}
var k string
if tss.cache != nil {
k = "m_" + topicSelector + "_" + topic
value, found := tss.cache.Get(k)
if found {
return value.(bool)
}
}
// Use template.Regexp() instead of template.Match() for performance
// See https://github.com/yosida95/uritemplate/pull/7
match := r.MatchString(topic)
if tss.cache != nil {
tss.cache.Set(k, match, 4)
}
return match
}
// getRegexp retrieves regexp for this template selector.
func (tss *TopicSelectorStore) getRegexp(topicSelector string) *regexp.Regexp {
// If it's definitely not an URI template, skip to save some resources
if !strings.Contains(topicSelector, "{") {
return nil
}
var k string
if tss.cache != nil {
k = "t_" + topicSelector
value, found := tss.cache.Get(k)
if found {
return value.(*regexp.Regexp)
}
}
// If an error occurs, it's a raw string
if tpl, err := uritemplate.New(topicSelector); err == nil {
r := tpl.Regexp()
if tss.cache != nil {
tss.cache.Set(k, r, 19)
}
return r
}
return nil
}