forked from dunglas/mercure
-
Notifications
You must be signed in to change notification settings - Fork 0
/
topic_selector.go
79 lines (65 loc) · 1.7 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
package mercure
import (
"regexp"
"strings"
uritemplate "github.com/yosida95/uritemplate/v3"
)
type TopicSelectorStoreCache interface {
Get(interface{}) (interface{}, bool)
Set(interface{}, interface{}, int64) bool
}
// TopicSelectorStore caches compiled templates to improve memory and CPU usage.
type TopicSelectorStore struct {
cache TopicSelectorStoreCache
skipSelect bool
}
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
}
var k string
if tss.cache != nil {
k = "m_" + topicSelector + "_" + topic
value, found := tss.cache.Get(k)
if found {
return value.(bool)
}
}
r := tss.getRegexp(topicSelector)
if r == nil {
return false
}
// 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
}