Skip to content
This repository was archived by the owner on Aug 23, 2023. It is now read-only.

Commit 0d06eae

Browse files
authored
Merge pull request #1236 from grafana/cleanup-find-cache-treeFromPath
treeFromPath: simplify and better comments
2 parents a7084bf + 17eff44 commit 0d06eae

File tree

2 files changed

+23
-15
lines changed

2 files changed

+23
-15
lines changed

idx/memory/find_cache.go

+12-15
Original file line numberDiff line numberDiff line change
@@ -149,7 +149,9 @@ func (c *FindCache) InvalidateFor(orgId uint32, path string) {
149149
}
150150

151151
// convert our path to a tree so that we can call `find(tree, pattern)`
152-
// for each pattern in the cache.
152+
// for each pattern in the cache and purge it if it matches the path or a subtree of it.
153+
// we can't simply prune all cache keys that equal path or a subtree of it, because
154+
// what's cached are search patterns which may contain wildcards and other expressions
153155
tree := treeFromPath(path)
154156

155157
for _, k := range cache.Keys() {
@@ -181,29 +183,23 @@ func (p *PartitionedMemoryIdx) PurgeFindCache() {
181183
}
182184
}
183185

184-
// treeFromPath creates a index tree from a series path.
186+
// treeFromPath creates an index tree from a series path.
185187
// The tree will have a single leaf node and nodes for
186188
// each branch.
187189
func treeFromPath(path string) *Tree {
188-
tree := &Tree{
190+
tree := Tree{
189191
Items: map[string]*Node{
190-
"": {
191-
Path: "",
192-
Children: make([]string, 0),
193-
Defs: make([]schema.MKey, 0),
194-
},
192+
"": {},
195193
},
196194
}
197195
pos := strings.Index(path, ".")
198-
prevPos := 0
196+
var parentBranch string
197+
prevPos := -1
199198
for {
200199
branch := path[:pos]
201-
// add as child of parent branch
202200
thisNode := branch[prevPos+1:]
203-
if prevPos == 0 {
204-
thisNode = branch[prevPos:]
205-
}
206-
tree.Items[path[:prevPos]].Children = []string{thisNode}
201+
202+
tree.Items[parentBranch].Children = []string{thisNode}
207203

208204
// create this branch/leaf
209205
tree.Items[branch] = &Node{
@@ -220,7 +216,8 @@ func treeFromPath(path string) *Tree {
220216
} else {
221217
pos = pos + nextPos + 1
222218
}
219+
parentBranch = branch
223220
}
224221

225-
return tree
222+
return &tree
226223
}

idx/memory/find_cache_test.go

+11
Original file line numberDiff line numberDiff line change
@@ -89,3 +89,14 @@ func TestFindCache(t *testing.T) {
8989
})
9090

9191
}
92+
93+
func BenchmarkTreeFromPath(b *testing.B) {
94+
numPaths := 1000
95+
paths := getSeriesNames(10, numPaths, "benchmark")
96+
b.ReportAllocs()
97+
b.ResetTimer()
98+
for i := 0; i < b.N; i++ {
99+
p := i % numPaths
100+
treeFromPath(paths[p])
101+
}
102+
}

0 commit comments

Comments
 (0)