This repository has been archived by the owner on Mar 1, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
autocompletions.go
141 lines (112 loc) · 2.34 KB
/
autocompletions.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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
package main
import (
"regexp"
"strings"
"sync"
"time"
"golang.org/x/exp/slog"
)
const (
autocompleteLimit = 25
defaultAutocompletionExpiry = 15 * time.Second
)
type AutoCompletions struct {
mu sync.Mutex
ac map[string]*haystack
expiry time.Time
subscriptions *Subscriptions
}
func (ac *AutoCompletions) CollectionNames(serverID, input string) ([]string, error) {
ac.mu.Lock()
defer ac.mu.Unlock()
now := time.Now()
if now.UTC().After(ac.expiry.UTC()) {
ac.ac = make(map[string]*haystack)
ac.expiry = now.Add(defaultAutocompletionExpiry)
slog.Info("Evicting autocompletions cache", slog.Time("autocomplete_cache_expires_at", ac.expiry))
}
lookup, ok := ac.ac[serverID]
if !ok {
collections, err := ac.subscriptions.GetCollectionNames(serverID)
if err != nil {
return nil, err
}
h := NewHaystack(collections)
ac.ac[serverID] = h
lookup = h
}
// Just match as much as possible if there's no input.
if input == "" {
input = "."
} else {
input = regexp.QuoteMeta(input)
}
input = strings.ToLower(input)
re, err := regexp.Compile(input)
if err != nil {
return nil, err
}
suggestions := lookup.FindAll(re)
if len(suggestions) > autocompleteLimit {
suggestions = suggestions[:autocompleteLimit]
}
return suggestions, nil
}
type haystack struct {
search []byte
domain []byte
spans []span
}
func NewHaystack(s []string) *haystack {
domain := strings.Join(s, "")
h := &haystack{
search: []byte(strings.ToLower(domain)),
domain: []byte(domain),
}
next := 0
for _, c := range s {
s := span{
start: next,
end: next + len(c),
}
h.spans = append(h.spans, s)
next += len(c)
}
return h
}
func (h *haystack) FindAll(re *regexp.Regexp) []string {
matches := re.FindAllIndex(h.search, -1)
set := make(map[string]struct{})
for _, m := range matches {
start, end := m[0], m[1]
for _, s := range h.spans {
if !s.Overlaps(start, end) {
continue
}
set[string(h.domain[s.start:s.end])] = struct{}{}
}
}
var found []string
for k := range set {
found = append(found, k)
}
return found
}
type span struct {
start, end int
}
func (s span) Overlaps(start, end int) bool {
min := func(a, b int) int {
if a < b {
return a
}
return b
}
max := func(a, b int) int {
if a > b {
return a
}
return b
}
return max(s.start, start) < min(s.end, end)
}