summaryrefslogtreecommitdiffstats
path: root/hugolib/doctree
diff options
context:
space:
mode:
authorBjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com>2023-12-24 19:11:05 +0100
committerBjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com>2024-01-27 16:28:14 +0100
commit7285e74090852b5d52f25e577850fa75f4aa8573 (patch)
tree54d07cb4a7de2db5c89f2590266595f0aca6cbd6 /hugolib/doctree
parent5fd1e7490305570872d3899f5edda950903c5213 (diff)
all: Rework page store, add a dynacache, improve partial rebuilds, and some general spring cleaningdevelop2024
There are some breaking changes in this commit, see #11455. Closes #11455 Closes #11549 This fixes a set of bugs (see issue list) and it is also paying some technical debt accumulated over the years. We now build with Staticcheck enabled in the CI build. The performance should be about the same as before for regular sized Hugo sites, but it should perform and scale much better to larger data sets, as objects that uses lots of memory (e.g. rendered Markdown, big JSON files read into maps with transform.Unmarshal etc.) will now get automatically garbage collected if needed. Performance on partial rebuilds when running the server in fast render mode should be the same, but the change detection should be much more accurate. A list of the notable new features: * A new dependency tracker that covers (almost) all of Hugo's API and is used to do fine grained partial rebuilds when running the server. * A new and simpler tree document store which allows fast lookups and prefix-walking in all dimensions (e.g. language) concurrently. * You can now configure an upper memory limit allowing for much larger data sets and/or running on lower specced PCs. We have lifted the "no resources in sub folders" restriction for branch bundles (e.g. sections). Memory Limit * Hugos will, by default, set aside a quarter of the total system memory, but you can set this via the OS environment variable HUGO_MEMORYLIMIT (in gigabytes). This is backed by a partitioned LRU cache used throughout Hugo. A cache that gets dynamically resized in low memory situations, allowing Go's Garbage Collector to free the memory. New Dependency Tracker: Hugo has had a rule based coarse grained approach to server rebuilds that has worked mostly pretty well, but there have been some surprises (e.g. stale content). This is now revamped with a new dependency tracker that can quickly calculate the delta given a changed resource (e.g. a content file, template, JS file etc.). This handles transitive relations, e.g. $page -> js.Build -> JS import, or $page1.Content -> render hook -> site.GetPage -> $page2.Title, or $page1.Content -> shortcode -> partial -> site.RegularPages -> $page2.Content -> shortcode ..., and should also handle changes to aggregated values (e.g. site.Lastmod) effectively. This covers all of Hugo's API with 2 known exceptions (a list that may not be fully exhaustive): Changes to files loaded with template func os.ReadFile may not be handled correctly. We recommend loading resources with resources.Get Changes to Hugo objects (e.g. Page) passed in the template context to lang.Translate may not be detected correctly. We recommend having simple i18n templates without too much data context passed in other than simple types such as strings and numbers. Note that the cachebuster configuration (when A changes then rebuild B) works well with the above, but we recommend that you revise that configuration, as it in most situations should not be needed. One example where it is still needed is with TailwindCSS and using changes to hugo_stats.json to trigger new CSS rebuilds. Document Store: Previously, a little simplified, we split the document store (where we store pages and resources) in a tree per language. This worked pretty well, but the structure made some operations harder than they needed to be. We have now restructured it into one Radix tree for all languages. Internally the language is considered to be a dimension of that tree, and the tree can be viewed in all dimensions concurrently. This makes some operations re. language simpler (e.g. finding translations is just a slice range), but the idea is that it should also be relatively inexpensive to add more dimensions if needed (e.g. role). Fixes #10169 Fixes #10364 Fixes #10482 Fixes #10630 Fixes #10656 Fixes #10694 Fixes #10918 Fixes #11262 Fixes #11439 Fixes #11453 Fixes #11457 Fixes #11466 Fixes #11540 Fixes #11551 Fixes #11556 Fixes #11654 Fixes #11661 Fixes #11663 Fixes #11664 Fixes #11669 Fixes #11671 Fixes #11807 Fixes #11808 Fixes #11809 Fixes #11815 Fixes #11840 Fixes #11853 Fixes #11860 Fixes #11883 Fixes #11904 Fixes #7388 Fixes #7425 Fixes #7436 Fixes #7544 Fixes #7882 Fixes #7960 Fixes #8255 Fixes #8307 Fixes #8863 Fixes #8927 Fixes #9192 Fixes #9324
Diffstat (limited to 'hugolib/doctree')
-rw-r--r--hugolib/doctree/dimensions.go43
-rw-r--r--hugolib/doctree/dimensions_test.go37
-rw-r--r--hugolib/doctree/nodeshiftree_test.go374
-rw-r--r--hugolib/doctree/nodeshifttree.go433
-rw-r--r--hugolib/doctree/simpletree.go91
-rw-r--r--hugolib/doctree/support.go251
-rw-r--r--hugolib/doctree/treeshifttree.go101
-rw-r--r--hugolib/doctree/treeshifttree_test.go28
8 files changed, 1358 insertions, 0 deletions
diff --git a/hugolib/doctree/dimensions.go b/hugolib/doctree/dimensions.go
new file mode 100644
index 000000000..bcc3cae00
--- /dev/null
+++ b/hugolib/doctree/dimensions.go
@@ -0,0 +1,43 @@
+// Copyright 2024 The Hugo Authors. All rights reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package doctree
+
+const (
+ // Language is currently the only dimension in the Hugo build matrix.
+ DimensionLanguage DimensionFlag = 1 << iota
+)
+
+// Dimension is a row in the Hugo build matrix which currently has one value: language.
+type Dimension [1]int
+
+// DimensionFlag is a flag in the Hugo build matrix.
+type DimensionFlag byte
+
+// Has returns whether the given flag is set.
+func (d DimensionFlag) Has(o DimensionFlag) bool {
+ return d&o == o
+}
+
+// Set sets the given flag.
+func (d DimensionFlag) Set(o DimensionFlag) DimensionFlag {
+ return d | o
+}
+
+// Index returns this flag's index in the Dimensions array.
+func (d DimensionFlag) Index() int {
+ if d == 0 {
+ panic("dimension flag not set")
+ }
+ return int(d - 1)
+}
diff --git a/hugolib/doctree/dimensions_test.go b/hugolib/doctree/dimensions_test.go
new file mode 100644
index 000000000..598f22a2d
--- /dev/null
+++ b/hugolib/doctree/dimensions_test.go
@@ -0,0 +1,37 @@
+// Copyright 2024 The Hugo Authors. All rights reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package doctree
+
+import (
+ "testing"
+
+ qt "github.com/frankban/quicktest"
+)
+
+func TestDimensionFlag(t *testing.T) {
+ c := qt.New(t)
+
+ var zero DimensionFlag
+ var d DimensionFlag
+ var o DimensionFlag = 1
+ var p DimensionFlag = 12
+
+ c.Assert(d.Has(o), qt.Equals, false)
+ d = d.Set(o)
+ c.Assert(d.Has(o), qt.Equals, true)
+ c.Assert(d.Has(d), qt.Equals, true)
+ c.Assert(func() { zero.Index() }, qt.PanicMatches, "dimension flag not set")
+ c.Assert(DimensionLanguage.Index(), qt.Equals, 0)
+ c.Assert(p.Index(), qt.Equals, 11)
+}
diff --git a/hugolib/doctree/nodeshiftree_test.go b/hugolib/doctree/nodeshiftree_test.go
new file mode 100644
index 000000000..313be0bc4
--- /dev/null
+++ b/hugolib/doctree/nodeshiftree_test.go
@@ -0,0 +1,374 @@
+// Copyright 2024 The Hugo Authors. All rights reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package doctree_test
+
+import (
+ "context"
+ "fmt"
+ "math/rand"
+ "path"
+ "strings"
+ "testing"
+
+ qt "github.com/frankban/quicktest"
+ "github.com/gohugoio/hugo/common/para"
+ "github.com/gohugoio/hugo/hugolib/doctree"
+ "github.com/google/go-cmp/cmp"
+)
+
+var eq = qt.CmpEquals(
+ cmp.Comparer(func(n1, n2 *testValue) bool {
+ if n1 == n2 {
+ return true
+ }
+
+ return n1.ID == n2.ID && n1.Lang == n2.Lang
+ }),
+)
+
+func TestTree(t *testing.T) {
+ c := qt.New(t)
+
+ zeroZero := doctree.New(
+ doctree.Config[*testValue]{
+ Shifter: &testShifter{},
+ },
+ )
+
+ a := &testValue{ID: "/a"}
+ zeroZero.InsertIntoValuesDimension("/a", a)
+ ab := &testValue{ID: "/a/b"}
+ zeroZero.InsertIntoValuesDimension("/a/b", ab)
+
+ c.Assert(zeroZero.Get("/a"), eq, &testValue{ID: "/a", Lang: 0})
+ s, v := zeroZero.LongestPrefix("/a/b/c", true, nil)
+ c.Assert(v, eq, ab)
+ c.Assert(s, eq, "/a/b")
+
+ // Change language.
+ oneZero := zeroZero.Increment(0)
+ c.Assert(zeroZero.Get("/a"), eq, &testValue{ID: "/a", Lang: 0})
+ c.Assert(oneZero.Get("/a"), eq, &testValue{ID: "/a", Lang: 1})
+}
+
+func TestTreeData(t *testing.T) {
+ c := qt.New(t)
+
+ tree := doctree.New(
+ doctree.Config[*testValue]{
+ Shifter: &testShifter{},
+ },
+ )
+
+ tree.InsertIntoValuesDimension("", &testValue{ID: "HOME"})
+ tree.InsertIntoValuesDimension("/a", &testValue{ID: "/a"})
+ tree.InsertIntoValuesDimension("/a/b", &testValue{ID: "/a/b"})
+ tree.InsertIntoValuesDimension("/b", &testValue{ID: "/b"})
+ tree.InsertIntoValuesDimension("/b/c", &testValue{ID: "/b/c"})
+ tree.InsertIntoValuesDimension("/b/c/d", &testValue{ID: "/b/c/d"})
+
+ var values []string
+
+ ctx := &doctree.WalkContext[*testValue]{}
+
+ w := &doctree.NodeShiftTreeWalker[*testValue]{
+ Tree: tree,
+ WalkContext: ctx,
+ Handle: func(s string, t *testValue, match doctree.DimensionFlag) (bool, error) {
+ ctx.Data().Insert(s, map[string]any{
+ "id": t.ID,
+ })
+
+ if s != "" {
+ p, v := ctx.Data().LongestPrefix(path.Dir(s))
+ values = append(values, fmt.Sprintf("%s:%s:%v", s, p, v))
+ }
+ return false, nil
+ },
+ }
+
+ w.Walk(context.Background())
+
+ c.Assert(strings.Join(values, "|"), qt.Equals, "/a::map[id:HOME]|/a/b:/a:map[id:/a]|/b::map[id:HOME]|/b/c:/b:map[id:/b]|/b/c/d:/b/c:map[id:/b/c]")
+}
+
+func TestTreeEvents(t *testing.T) {
+ c := qt.New(t)
+
+ tree := doctree.New(
+ doctree.Config[*testValue]{
+ Shifter: &testShifter{echo: true},
+ },
+ )
+
+ tree.InsertIntoValuesDimension("/a", &testValue{ID: "/a", Weight: 2, IsBranch: true})
+ tree.InsertIntoValuesDimension("/a/p1", &testValue{ID: "/a/p1", Weight: 5})
+ tree.InsertIntoValuesDimension("/a/p", &testValue{ID: "/a/p2", Weight: 6})
+ tree.InsertIntoValuesDimension("/a/s1", &testValue{ID: "/a/s1", Weight: 5, IsBranch: true})
+ tree.InsertIntoValuesDimension("/a/s1/p1", &testValue{ID: "/a/s1/p1", Weight: 8})
+ tree.InsertIntoValuesDimension("/a/s1/p1", &testValue{ID: "/a/s1/p2", Weight: 9})
+ tree.InsertIntoValuesDimension("/a/s1/s2", &testValue{ID: "/a/s1/s2", Weight: 6, IsBranch: true})
+ tree.InsertIntoValuesDimension("/a/s1/s2/p1", &testValue{ID: "/a/s1/s2/p1", Weight: 8})
+ tree.InsertIntoValuesDimension("/a/s1/s2/p2", &testValue{ID: "/a/s1/s2/p2", Weight: 7})
+
+ w := &doctree.NodeShiftTreeWalker[*testValue]{
+ Tree: tree,
+ WalkContext: &doctree.WalkContext[*testValue]{},
+ }
+
+ w.Handle = func(s string, t *testValue, match doctree.DimensionFlag) (bool, error) {
+ if t.IsBranch {
+ w.WalkContext.AddEventListener("weight", s, func(e *doctree.Event[*testValue]) {
+ if e.Source.Weight > t.Weight {
+ t.Weight = e.Source.Weight
+ w.WalkContext.SendEvent(&doctree.Event[*testValue]{Source: t, Path: s, Name: "weight"})
+ }
+ // Reduces the amount of events bubbling up the tree. If the weight for this branch has
+ // increased, that will be announced in its own event.
+ e.StopPropagation()
+ })
+ } else {
+ w.WalkContext.SendEvent(&doctree.Event[*testValue]{Source: t, Path: s, Name: "weight"})
+ }
+
+ return false, nil
+ }
+
+ c.Assert(w.Walk(context.Background()), qt.IsNil)
+ c.Assert(w.WalkContext.HandleEventsAndHooks(), qt.IsNil)
+
+ c.Assert(tree.Get("/a").Weight, eq, 9)
+ c.Assert(tree.Get("/a/s1").Weight, eq, 9)
+ c.Assert(tree.Get("/a/p").Weight, eq, 6)
+ c.Assert(tree.Get("/a/s1/s2").Weight, eq, 8)
+ c.Assert(tree.Get("/a/s1/s2/p2").Weight, eq, 7)
+}
+
+func TestTreeInsert(t *testing.T) {
+ c := qt.New(t)
+
+ tree := doctree.New(
+ doctree.Config[*testValue]{
+ Shifter: &testShifter{},
+ },
+ )
+
+ a := &testValue{ID: "/a"}
+ tree.InsertIntoValuesDimension("/a", a)
+ ab := &testValue{ID: "/a/b"}
+ tree.InsertIntoValuesDimension("/a/b", ab)
+
+ c.Assert(tree.Get("/a"), eq, &testValue{ID: "/a", Lang: 0})
+ c.Assert(tree.Get("/notfound"), qt.IsNil)
+
+ ab2 := &testValue{ID: "/a/b", Lang: 0}
+ v, ok := tree.InsertIntoValuesDimension("/a/b", ab2)
+ c.Assert(ok, qt.IsTrue)
+ c.Assert(v, qt.DeepEquals, ab2)
+
+ tree1 := tree.Increment(0)
+ c.Assert(tree1.Get("/a/b"), qt.DeepEquals, &testValue{ID: "/a/b", Lang: 1})
+}
+
+func TestTreePara(t *testing.T) {
+ c := qt.New(t)
+
+ p := para.New(4)
+ r, _ := p.Start(context.Background())
+
+ tree := doctree.New(
+ doctree.Config[*testValue]{
+ Shifter: &testShifter{},
+ },
+ )
+
+ for i := 0; i < 8; i++ {
+ i := i
+ r.Run(func() error {
+ a := &testValue{ID: "/a"}
+ lock := tree.Lock(true)
+ defer lock()
+ tree.InsertIntoValuesDimension("/a", a)
+ ab := &testValue{ID: "/a/b"}
+ tree.InsertIntoValuesDimension("/a/b", ab)
+
+ key := fmt.Sprintf("/a/b/c/%d", i)
+ val := &testValue{ID: key}
+ tree.InsertIntoValuesDimension(key, val)
+ c.Assert(tree.Get(key), eq, val)
+ // s, _ := tree.LongestPrefix(key, nil)
+ // c.Assert(s, eq, "/a/b")
+
+ return nil
+ })
+ }
+
+ c.Assert(r.Wait(), qt.IsNil)
+}
+
+func TestValidateKey(t *testing.T) {
+ c := qt.New(t)
+
+ c.Assert(doctree.ValidateKey(""), qt.IsNil)
+ c.Assert(doctree.ValidateKey("/a/b/c"), qt.IsNil)
+ c.Assert(doctree.ValidateKey("/"), qt.IsNotNil)
+ c.Assert(doctree.ValidateKey("a"), qt.IsNotNil)
+ c.Assert(doctree.ValidateKey("abc"), qt.IsNotNil)
+ c.Assert(doctree.ValidateKey("/abc/"), qt.IsNotNil)
+}
+
+type testShifter struct {
+ echo bool
+}
+
+func (s *testShifter) ForEeachInDimension(n *testValue, d int, f func(n *testValue) bool) {
+ if d != doctree.DimensionLanguage.Index() {
+ panic("not implemented")
+ }
+ f(n)
+}
+
+func (s *testShifter) Insert(old, new *testValue) *testValue {
+ return new
+}
+
+func (s *testShifter) InsertInto(old, new *testValue, dimension doctree.Dimension) *testValue {
+ return new
+}
+
+func (s *testShifter) Delete(n *testValue, dimension doctree.Dimension) (bool, bool) {
+ return true, true
+}
+
+func (s *testShifter) Shift(n *testValue, dimension doctree.Dimension, exact bool) (*testValue, bool, doctree.DimensionFlag) {
+ if s.echo {
+ return n, true, doctree.DimensionLanguage
+ }
+ if n.NoCopy {
+ if n.Lang == dimension[0] {
+ return n, true, doctree.DimensionLanguage
+ }
+ return nil, false, doctree.DimensionLanguage
+ }
+ c := *n
+ c.Lang = dimension[0]
+ return &c, true, doctree.DimensionLanguage
+}
+
+func (s *testShifter) All(n *testValue) []*testValue {
+ return []*testValue{n}
+}
+
+type testValue struct {
+ ID string
+ Lang int
+
+ Weight int
+ IsBranch bool
+
+ NoCopy bool
+}
+
+func BenchmarkTreeInsert(b *testing.B) {
+ runBench := func(b *testing.B, numElements int) {
+ for i := 0; i < b.N; i++ {
+ tree := doctree.New(
+ doctree.Config[*testValue]{
+ Shifter: &testShifter{},
+ },
+ )
+
+ for i := 0; i < numElements; i++ {
+ lang := rand.Intn(2)
+ tree.InsertIntoValuesDimension(fmt.Sprintf("/%d", i), &testValue{ID: fmt.Sprintf("/%d", i), Lang: lang, Weight: i, NoCopy: true})
+ }
+ }
+ }
+
+ b.Run("1000", func(b *testing.B) {
+ runBench(b, 1000)
+ })
+
+ b.Run("10000", func(b *testing.B) {
+ runBench(b, 10000)
+ })
+
+ b.Run("100000", func(b *testing.B) {
+ runBench(b, 100000)
+ })
+
+ b.Run("300000", func(b *testing.B) {
+ runBench(b, 300000)
+ })
+}
+
+func BenchmarkWalk(b *testing.B) {
+ const numElements = 1000
+
+ createTree := func() *doctree.NodeShiftTree[*testValue] {
+ tree := doctree.New(
+ doctree.Config[*testValue]{
+ Shifter: &testShifter{},
+ },
+ )
+
+ for i := 0; i < numElements; i++ {
+ lang := rand.Intn(2)
+ tree.InsertIntoValuesDimension(fmt.Sprintf("/%d", i), &testValue{ID: fmt.Sprintf("/%d", i), Lang: lang, Weight: i, NoCopy: true})
+ }
+
+ return tree
+ }
+
+ handle := func(s string, t *testValue, match doctree.DimensionFlag) (bool, error) {
+ return false, nil
+ }
+
+ for _, numElements := range []int{1000, 10000, 100000} {
+
+ b.Run(fmt.Sprintf("Walk one dimension %d", numElements), func(b *testing.B) {
+ tree := createTree()
+ b.ResetTimer()
+ for i := 0; i < b.N; i++ {
+ w := &doctree.NodeShiftTreeWalker[*testValue]{
+ Tree: tree,
+ Handle: handle,
+ }
+ if err := w.Walk(context.Background()); err != nil {
+ b.Fatal(err)
+ }
+ }
+ })
+
+ b.Run(fmt.Sprintf("Walk all dimensions %d", numElements), func(b *testing.B) {
+ base := createTree()
+ b.ResetTimer()
+ for i := 0; i < b.N; i++ {
+ for d1 := 0; d1 < 1; d1++ {
+ for d2 := 0; d2 < 2; d2++ {
+ tree := base.Shape(d1, d2)
+ w := &doctree.NodeShiftTreeWalker[*testValue]{
+ Tree: tree,
+ Handle: handle,
+ }
+ if err := w.Walk(context.Background()); err != nil {
+ b.Fatal(err)
+ }
+ }
+ }
+ }
+ })
+
+ }
+}
diff --git a/hugolib/doctree/nodeshifttree.go b/hugolib/doctree/nodeshifttree.go
new file mode 100644
index 000000000..1c1175305
--- /dev/null
+++ b/hugolib/doctree/nodeshifttree.go
@@ -0,0 +1,433 @@
+// Copyright 2024 The Hugo Authors. All rights reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package doctree
+
+import (
+ "context"
+ "fmt"
+ "path"
+ "strings"
+ "sync"
+
+ radix "github.com/armon/go-radix"
+ "github.com/gohugoio/hugo/resources/resource"
+)
+
+type (
+ Config[T any] struct {
+ // Shifter handles tree transformations.
+ Shifter Shifter[T]
+ }
+
+ // Shifter handles tree transformations.
+ Shifter[T any] interface {
+ // ForEeachInDimension will call the given function for each value in the given dimension.
+ // If the function returns true, the walk will stop.
+ ForEeachInDimension(n T, d int, f func(T) bool)
+
+ // Insert inserts new into the tree into the dimension it provides.
+ // It may replace old.
+ // It returns a T (can be the same as old).
+ Insert(old, new T) T
+
+ // Insert inserts new into the given dimension.
+ // It may replace old.
+ // It returns a T (can be the same as old).
+ InsertInto(old, new T, dimension Dimension) T
+
+ // Delete deletes T from the given dimension and returns whether the dimension was deleted and if it's empty after the delete.
+ Delete(v T, dimension Dimension) (bool, bool)
+
+ // Shift shifts T into the given dimension
+ // and returns the shifted T and a bool indicating if the shift was successful and
+ // how accurate a match T is according to its dimensions.
+ Shift(v T, dimension Dimension, exact bool) (T, bool, DimensionFlag)
+ }
+)
+
+// NodeShiftTree is the root of a tree that can be shaped using the Shape method.
+// Note that multipled shapes of the same tree is meant to be used concurrently,
+// so use the applicable locking when needed.
+type NodeShiftTree[T any] struct {
+ tree *radix.Tree
+
+ // E.g. [language, role].
+ dims Dimension
+ shifter Shifter[T]
+
+ mu *sync.RWMutex
+}
+
+func New[T any](cfg Config[T]) *NodeShiftTree[T] {
+ if cfg.Shifter == nil {
+ panic("Shifter is required")
+ }
+
+ return &NodeShiftTree[T]{
+ mu: &sync.RWMutex{},
+ shifter: cfg.Shifter,
+ tree: radix.New(),
+ }
+}
+
+func (r *NodeShiftTree[T]) Delete(key string) {
+ r.delete(key)
+}
+
+func (r *NodeShiftTree[T]) DeleteAll(key string) {
+ r.tree.WalkPrefix(key, func(key string, value any) bool {
+ v, ok := r.tree.Delete(key)
+ if ok {
+ resource.MarkStale(v)
+ }
+ return false
+ })
+}
+
+func (r *NodeShiftTree[T]) DeletePrefix(prefix string) int {
+ count := 0
+ var keys []string
+ r.tree.WalkPrefix(prefix, func(key string, value any) bool {
+ keys = append(keys, key)
+ return false
+ })
+ for _, key := range keys {
+ if ok := r.delete(key); ok {
+ count++
+ }
+ }
+ return count
+}
+
+func (r *NodeShiftTree[T]) delete(key string) bool {
+ var wasDeleted bool
+ if v, ok := r.tree.Get(key); ok {
+ var isEmpty bool
+ wasDeleted, isEmpty = r.shifter.Delete(v.(T), r.dims)
+ if isEmpty {
+ r.tree.Delete(key)
+ }
+ }
+ return wasDeleted
+}
+
+func (t *NodeShiftTree[T]) DeletePrefixAll(prefix string) int {
+ count := 0
+
+ t.tree.WalkPrefix(prefix, func(key string, value any) bool {
+ if v, ok := t.tree.Delete(key); ok {
+ resource.MarkStale(v)
+ count++
+ }
+ return false
+ })
+
+ return count
+}
+
+// Increment the value of dimension d by 1.
+func (t *NodeShiftTree[T]) Increment(d int) *NodeShiftTree[T] {
+ return t.Shape(d, t.dims[d]+1)
+}
+
+func (r *NodeShiftTree[T]) InsertIntoCurrentDimension(s string, v T) (T, bool) {
+ s = mustValidateKey(cleanKey(s))
+ if vv, ok := r.tree.Get(s); ok {
+ v = r.shifter.InsertInto(vv.(T), v, r.dims)
+ }
+ r.tree.Insert(s, v)
+ return v, true
+}
+
+func (r *NodeShiftTree[T]) InsertIntoValuesDimension(s string, v T) (T, bool) {
+ s = mustValidateKey(cleanKey(s))
+ if vv, ok := r.tree.Get(s); ok {
+ v = r.shifter.Insert(vv.(T), v)
+ }
+ r.tree.Insert(s, v)
+ return v, true
+}
+
+func (r *NodeShiftTree[T]) InsertRawWithLock(s string, v any) (any, bool) {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ return r.tree.Insert(s, v)
+}
+
+func (r *NodeShiftTree[T]) InsertWithLock(s string, v T) (T, bool) {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ return r.InsertIntoValuesDimension(s, v)
+}
+
+func (t *NodeShiftTree[T]) Len() int {
+ return t.tree.Len()
+}
+
+func (t *NodeShiftTree[T]) CanLock() bool {
+ ok := t.mu.TryLock()
+ if ok {
+ t.mu.Unlock()
+ }
+ return ok
+}
+
+// Lock locks the data store for read or read/write access until commit is invoked.
+// Note that Root is not thread-safe outside of this transaction construct.
+func (t *NodeShiftTree[T]) Lock(writable bool) (commit func()) {
+ if writable {
+ t.mu.Lock()
+ } else {
+ t.mu.RLock()
+ }
+ return func() {
+ if writable {
+ t.mu.Unlock()
+ } else {
+ t.mu.RUnlock()
+ }
+ }
+}
+
+// LongestPrefix finds the longest prefix of s that exists in the tree that also matches the predicate (if set).
+// Set exact to true to only match exact in the current dimension (e.g. language).
+func (r *NodeShiftTree[T]) LongestPrefix(s string, exact bool, predicate func(v T) bool) (string, T) {
+ for {
+ longestPrefix, v, found := r.tree.LongestPrefix(s)
+
+ if found {
+ if t, ok, _ := r.shift(v.(T), exact); ok && (predicate == nil || predicate(t)) {
+ return longestPrefix, t
+ }
+ }
+
+ if s == "" || s == "/" {
+ var t T
+ return "", t
+ }
+
+ // Walk up to find a node in the correct dimension.
+ s = path.Dir(s)
+
+ }
+}
+
+// LongestPrefixAll returns the longest prefix considering all tree dimensions.
+func (r *NodeShiftTree[T]) LongestPrefixAll(s string) (string, bool) {
+ s, _, found := r.tree.LongestPrefix(s)
+ return s, found
+}
+
+func (r *NodeShiftTree[T]) GetRaw(s string) (T, bool) {
+ v, ok := r.tree.Get(s)
+ if !ok {
+ var t T
+ return t, false
+ }
+ return v.(T), true
+}
+
+func (r *NodeShiftTree[T]) WalkPrefixRaw(prefix string, walker func(key string, value T) bool) {
+ walker2 := func(key string, value any) bool {
+ return walker(key, value.(T))
+ }
+ r.tree.WalkPrefix(prefix, walker2)
+}
+
+// Shape the tree for dimension d to value v.
+func (t *NodeShiftTree[T]) Shape(d, v int) *NodeShiftTree[T] {
+ x := t.clone()
+ x.dims[d] = v
+ return x
+}
+
+func (t *NodeShiftTree[T]) String() string {
+ return fmt.Sprintf("Root{%v}", t.dims)
+}
+
+func (r *NodeShiftTree[T]) Get(s string) T {
+ t, _ := r.get(s)
+ return t
+}
+
+func (r *NodeShiftTree[T]) ForEeachInDimension(s string, d int, f func(T) bool) {
+ s = cleanKey(s)
+ v, ok := r.tree.Get(s)
+ if !ok {
+ return
+ }
+ r.shifter.ForEeachInDimension(v.(T), d, f)
+}
+
+type WalkFunc[T any] func(string, T) (bool, error)
+
+type NodeShiftTreeWalker[T any] struct {
+ // The tree to walk.
+ Tree *NodeShiftTree[T]
+
+ // Handle will be called for each node in the main tree.
+ // If the callback returns true, the walk will stop.
+ // The callback can optionally return a callback for the nested tree.
+ Handle func(s string, v T, exact DimensionFlag) (terminate bool, err error)
+
+ // Optional prefix filter.
+ Prefix string
+
+ // Enable read or write locking if needed.
+ LockType LockType
+
+ // When set, no dimension shifting will be performed.
+ NoShift bool
+
+ // Don't fall back to alternative dimensions (e.g. language).
+ Exact bool
+
+ // Used in development only.
+ Debug bool
+
+ // Optional context.
+ // Note that this is copied to the nested walkers using Extend.
+ // This means that walkers can pass data (down) and events (up) to
+ // the related walkers.
+ WalkContext *WalkContext[T]
+
+ // Local state.
+ // This is scoped to the current walker and not copied to the nested walkers.
+ skipPrefixes []string
+}
+
+// Extend returns a new NodeShiftTreeWalker with the same configuration as the
+// and the same WalkContext as the original.
+// Any local state is reset.
+func (r NodeShiftTreeWalker[T]) Extend() *NodeShiftTreeWalker[T] {
+ r.resetLocalState()
+ return &r
+}
+
+// SkipPrefix adds a pre