summaryrefslogtreecommitdiffstats
path: root/common
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 /common
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 'common')
-rw-r--r--common/constants/constants.go21
-rw-r--r--common/hcontext/context.go46
-rw-r--r--common/herrors/error_locator.go3
-rw-r--r--common/herrors/error_locator_test.go2
-rw-r--r--common/herrors/errors.go21
-rw-r--r--common/herrors/errors_test.go3
-rw-r--r--common/herrors/file_error.go22
-rw-r--r--common/herrors/file_error_test.go6
-rw-r--r--common/hreflect/helpers.go41
-rw-r--r--common/hreflect/helpers_test.go37
-rw-r--r--common/hstrings/strings.go7
-rw-r--r--common/hstrings/strings_test.go4
-rw-r--r--common/htime/integration_test.go2
-rw-r--r--common/hugio/copy.go9
-rw-r--r--common/hugio/hasBytesWriter.go2
-rw-r--r--common/hugio/hasBytesWriter_test.go2
-rw-r--r--common/hugio/readers.go20
-rw-r--r--common/hugo/hugo.go9
-rw-r--r--common/loggers/handlerdefault.go6
-rw-r--r--common/loggers/handlersmisc.go23
-rw-r--r--common/loggers/handlerterminal.go4
-rw-r--r--common/loggers/logger.go57
-rw-r--r--common/loggers/logger_test.go2
-rw-r--r--common/loggers/loggerglobal.go2
-rw-r--r--common/maps/cache.go90
-rw-r--r--common/maps/maps.go17
-rw-r--r--common/maps/params.go10
-rw-r--r--common/paths/path.go222
-rw-r--r--common/paths/path_test.go114
-rw-r--r--common/paths/pathparser.go494
-rw-r--r--common/paths/pathparser_test.go351
-rw-r--r--common/paths/paths_integration_test.go80
-rw-r--r--common/paths/pathtype_string.go27
-rw-r--r--common/paths/url.go10
-rw-r--r--common/predicate/predicate.go72
-rw-r--r--common/predicate/predicate_test.go83
-rw-r--r--common/rungroup/rungroup.go93
-rw-r--r--common/rungroup/rungroup_test.go44
-rw-r--r--common/terminal/colors.go2
-rw-r--r--common/types/css/csstypes.go2
-rw-r--r--common/types/evictingqueue.go15
-rw-r--r--common/types/hstring/stringtypes.go2
-rw-r--r--common/types/hstring/stringtypes_test.go2
-rw-r--r--common/types/types.go13
-rw-r--r--common/urls/baseURL.go28
-rw-r--r--common/urls/baseURL_test.go28
46 files changed, 1957 insertions, 193 deletions
diff --git a/common/constants/constants.go b/common/constants/constants.go
index 6afb9e283..e4f5a63a2 100644
--- a/common/constants/constants.go
+++ b/common/constants/constants.go
@@ -20,3 +20,24 @@ const (
ErrRemoteGetJSON = "error-remote-getjson"
ErrRemoteGetCSV = "error-remote-getcsv"
)
+
+// Field/method names with special meaning.
+const (
+ FieldRelPermalink = "RelPermalink"
+ FieldPermalink = "Permalink"
+)
+
+// IsFieldRelOrPermalink returns whether the given name is a RelPermalink or Permalink.
+func IsFieldRelOrPermalink(name string) bool {
+ return name == FieldRelPermalink || name == FieldPermalink
+}
+
+// Resource transformations.
+const (
+ ResourceTransformationFingerprint = "fingerprint"
+)
+
+// IsResourceTransformationLinkChange returns whether the given name is a resource transformation that changes the permalink based on the content.
+func IsResourceTransformationPermalinkHash(name string) bool {
+ return name == ResourceTransformationFingerprint
+}
diff --git a/common/hcontext/context.go b/common/hcontext/context.go
new file mode 100644
index 000000000..9524ef284
--- /dev/null
+++ b/common/hcontext/context.go
@@ -0,0 +1,46 @@
+// 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 hcontext
+
+import "context"
+
+// ContextDispatcher is a generic interface for setting and getting values from a context.
+type ContextDispatcher[T any] interface {
+ Set(ctx context.Context, value T) context.Context
+ Get(ctx context.Context) T
+}
+
+// NewContextDispatcher creates a new ContextDispatcher with the given key.
+func NewContextDispatcher[T any, R comparable](key R) ContextDispatcher[T] {
+ return keyInContext[T, R]{
+ id: key,
+ }
+}
+
+type keyInContext[T any, R comparable] struct {
+ zero T
+ id R
+}
+
+func (f keyInContext[T, R]) Get(ctx context.Context) T {
+ v := ctx.Value(f.id)
+ if v == nil {
+ return f.zero
+ }
+ return v.(T)
+}
+
+func (f keyInContext[T, R]) Set(ctx context.Context, value T) context.Context {
+ return context.WithValue(ctx, f.id, value)
+}
diff --git a/common/herrors/error_locator.go b/common/herrors/error_locator.go
index b880fe045..1ece0cca4 100644
--- a/common/herrors/error_locator.go
+++ b/common/herrors/error_locator.go
@@ -1,4 +1,4 @@
-// Copyright 2022 The Hugo Authors. All rights reserved.
+// 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.
@@ -74,7 +74,6 @@ func ContainsMatcher(text string) func(m LineMatcher) int {
// ErrorContext contains contextual information about an error. This will
// typically be the lines surrounding some problem in a file.
type ErrorContext struct {
-
// If a match will contain the matched line and up to 2 lines before and after.
// Will be empty if no match.
Lines []string
diff --git a/common/herrors/error_locator_test.go b/common/herrors/error_locator_test.go
index 6135657d8..62f15213d 100644
--- a/common/herrors/error_locator_test.go
+++ b/common/herrors/error_locator_test.go
@@ -1,4 +1,4 @@
-// Copyright 2022 The Hugo Authors. All rights reserved.
+// 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.
diff --git a/common/herrors/errors.go b/common/herrors/errors.go
index 8e62b2c99..59739a86a 100644
--- a/common/herrors/errors.go
+++ b/common/herrors/errors.go
@@ -1,4 +1,4 @@
-// Copyright 2022 The Hugo Authors. All rights reserved.
+// 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.
@@ -21,6 +21,7 @@ import (
"os"
"runtime"
"runtime/debug"
+ "time"
)
// PrintStackTrace prints the current stacktrace to w.
@@ -47,6 +48,24 @@ func Recover(args ...any) {
}
}
+// IsTimeoutError returns true if the given error is or contains a TimeoutError.
+func IsTimeoutError(err error) bool {
+ return errors.Is(err, &TimeoutError{})
+}
+
+type TimeoutError struct {
+ Duration time.Duration
+}
+
+func (e *TimeoutError) Error() string {
+ return fmt.Sprintf("timeout after %s", e.Duration)
+}
+
+func (e *TimeoutError) Is(target error) bool {
+ _, ok := target.(*TimeoutError)
+ return ok
+}
+
// IsFeatureNotAvailableError returns true if the given error is or contains a FeatureNotAvailableError.
func IsFeatureNotAvailableError(err error) bool {
return errors.Is(err, &FeatureNotAvailableError{})
diff --git a/common/herrors/errors_test.go b/common/herrors/errors_test.go
index 223782e23..2f53a1e89 100644
--- a/common/herrors/errors_test.go
+++ b/common/herrors/errors_test.go
@@ -1,4 +1,4 @@
-// Copyright 2022 The Hugo Authors. All rights reserved.
+// 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.
@@ -42,5 +42,4 @@ func TestIsFeatureNotAvailableError(t *testing.T) {
c.Assert(IsFeatureNotAvailableError(ErrFeatureNotAvailable), qt.Equals, true)
c.Assert(IsFeatureNotAvailableError(&FeatureNotAvailableError{}), qt.Equals, true)
c.Assert(IsFeatureNotAvailableError(errors.New("asdf")), qt.Equals, false)
-
}
diff --git a/common/herrors/file_error.go b/common/herrors/file_error.go
index f8bcecd34..32a6f0081 100644
--- a/common/herrors/file_error.go
+++ b/common/herrors/file_error.go
@@ -1,4 +1,4 @@
-// Copyright 2022 The Hugo Authors. All rights reserved.
+// 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.
@@ -15,13 +15,13 @@ package herrors
import (
"encoding/json"
-
- godartsassv1 "github.com/bep/godartsass"
-
+ "errors"
"fmt"
"io"
"path/filepath"
+ godartsassv1 "github.com/bep/godartsass"
+
"github.com/bep/godartsass/v2"
"github.com/bep/golibsass/libsass/libsasserrors"
"github.com/gohugoio/hugo/common/paths"
@@ -29,8 +29,6 @@ import (
"github.com/pelletier/go-toml/v2"
"github.com/spf13/afero"
"github.com/tdewolff/parse/v2"
-
- "errors"
)
// FileError represents an error when handling a file: Parsing a config file,
@@ -48,6 +46,9 @@ type FileError interface {
// UpdateContent updates the error with a new ErrorContext from the content of the file.
UpdateContent(r io.Reader, linematcher LineMatcherFn) FileError
+
+ // SetFilename sets the filename of the error.
+ SetFilename(filename string) FileError
}
// Unwrapper can unwrap errors created with fmt.Errorf.
@@ -60,6 +61,11 @@ var (
_ Unwrapper = (*fileError)(nil)
)
+func (fe *fileError) SetFilename(filename string) FileError {
+ fe.position.Filename = filename
+ return fe
+}
+
func (fe *fileError) UpdatePosition(pos text.Position) FileError {
oldFilename := fe.Position().Filename
if pos.Filename != "" && fe.fileType == "" {
@@ -115,7 +121,6 @@ func (fe *fileError) UpdateContent(r io.Reader, linematcher LineMatcherFn) FileE
}
return fe
-
}
type fileError struct {
@@ -181,7 +186,6 @@ func NewFileErrorFromName(err error, name string) FileError {
}
return &fileError{cause: err, fileType: fileType, position: pos}
-
}
// NewFileErrorFromPos will use the filename and line number from pos to create a new FileError, wrapping err.
@@ -192,7 +196,6 @@ func NewFileErrorFromPos(err error, pos text.Position) FileError {
_, fileType = paths.FileAndExtNoDelimiter(filepath.Clean(pos.Filename))
}
return &fileError{cause: err, fileType: fileType, position: pos}
-
}
func NewFileErrorFromFileInErr(err error, fs afero.Fs, linematcher LineMatcherFn) FileError {
@@ -249,7 +252,6 @@ func openFile(filename string, fs afero.Fs) (afero.File, string, error) {
}); ok {
realFilename = s.Filename()
}
-
}
f, err2 := fs.Open(filename)
diff --git a/common/herrors/file_error_test.go b/common/herrors/file_error_test.go
index 0b260a255..7aca08405 100644
--- a/common/herrors/file_error_test.go
+++ b/common/herrors/file_error_test.go
@@ -1,4 +1,4 @@
-// Copyright 2022 The Hugo Authors. All rights reserved.
+// 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.
@@ -14,12 +14,11 @@
package herrors
import (
+ "errors"
"fmt"
"strings"
"testing"
- "errors"
-
"github.com/gohugoio/hugo/common/text"
qt "github.com/frankban/quicktest"
@@ -48,7 +47,6 @@ func TestNewFileError(t *testing.T) {
c.Assert(errorContext.Lines, qt.DeepEquals, []string{"line 30", "line 31", "line 32", "line 33", "line 34"})
c.Assert(errorContext.LinesPos, qt.Equals, 2)
c.Assert(errorContext.ChromaLexer, qt.Equals, "go-html-template")
-
}
func TestNewFileErrorExtractFromMessage(t *testing.T) {
diff --git a/common/hreflect/helpers.go b/common/hreflect/helpers.go
index 17afbf912..b5a8bacc9 100644
--- a/common/hreflect/helpers.go
+++ b/common/hreflect/helpers.go
@@ -1,4 +1,4 @@
-// Copyright 2019 The Hugo Authors. All rights reserved.
+// Copyright 2024 The Hugo Authors. All rights reserved.
// Some functions in this file (see comments) is based on the Go source code,
// copyright The Go Authors and governed by a BSD-style license.
//
@@ -23,6 +23,7 @@ import (
"time"
"github.com/gohugoio/hugo/common/htime"
+ "github.com/gohugoio/hugo/common/maps"
"github.com/gohugoio/hugo/common/types"
)
@@ -188,6 +189,20 @@ func IsTime(tp reflect.Type) bool {
return false
}
+// IsValid returns whether v is not nil and a valid value.
+func IsValid(v reflect.Value) bool {
+ if !v.IsValid() {
+ return false
+ }
+
+ switch v.Kind() {
+ case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:
+ return !v.IsNil()
+ }
+
+ return true
+}
+
// AsTime returns v as a time.Time if possible.
// The given location is only used if the value implements AsTimeProvider (e.g. go-toml local).
// A zero Time and false is returned if this isn't possible.
@@ -217,7 +232,7 @@ func CallMethodByName(cxt context.Context, name string, v reflect.Value) []refle
panic("not supported")
}
first := tp.In(0)
- if first.Implements(ContextInterface) {
+ if IsContextType(first) {
args = append(args, reflect.ValueOf(cxt))
}
}
@@ -236,4 +251,24 @@ func indirectInterface(v reflect.Value) reflect.Value {
return v.Elem()
}
-var ContextInterface = reflect.TypeOf((*context.Context)(nil)).Elem()
+var contextInterface = reflect.TypeOf((*context.Context)(nil)).Elem()
+
+var isContextCache = maps.NewCache[reflect.Type, bool]()
+
+type k string
+
+var contextTypeValue = reflect.TypeOf(context.WithValue(context.Background(), k("key"), 32))
+
+// IsContextType returns whether tp is a context.Context type.
+func IsContextType(tp reflect.Type) bool {
+ if tp == contextTypeValue {
+ return true
+ }
+ if tp == contextInterface {
+ return true
+ }
+
+ return isContextCache.GetOrCreate(tp, func() bool {
+ return tp.Implements(contextInterface)
+ })
+}
diff --git a/common/hreflect/helpers_test.go b/common/hreflect/helpers_test.go
index d16b9b9b3..27b774337 100644
--- a/common/hreflect/helpers_test.go
+++ b/common/hreflect/helpers_test.go
@@ -14,6 +14,7 @@
package hreflect
import (
+ "context"
"reflect"
"testing"
"time"
@@ -40,6 +41,42 @@ func TestGetMethodByName(t *testing.T) {
c.Assert(GetMethodIndexByName(tp, "Foo"), qt.Equals, -1)
}
+func TestIsContextType(t *testing.T) {
+ c := qt.New(t)
+ type k string
+ ctx := context.Background()
+ valueCtx := context.WithValue(ctx, k("key"), 32)
+ c.Assert(IsContextType(reflect.TypeOf(ctx)), qt.IsTrue)
+ c.Assert(IsContextType(reflect.TypeOf(valueCtx)), qt.IsTrue)
+}
+
+func BenchmarkIsContextType(b *testing.B) {
+ type k string
+ b.Run("value", func(b *testing.B) {
+ ctx := context.Background()
+ ctxs := make([]reflect.Type, b.N)
+ for i := 0; i < b.N; i++ {
+ ctxs[i] = reflect.TypeOf(context.WithValue(ctx, k("key"), i))
+ }
+
+ b.ResetTimer()
+ for i := 0; i < b.N; i++ {
+ if !IsContextType(ctxs[i]) {
+ b.Fatal("not context")
+ }
+ }
+ })
+
+ b.Run("background", func(b *testing.B) {
+ var ctxt reflect.Type = reflect.TypeOf(context.Background())
+ for i := 0; i < b.N; i++ {
+ if !IsContextType(ctxt) {
+ b.Fatal("not context")
+ }
+ }
+ })
+}
+
func BenchmarkIsTruthFul(b *testing.B) {
v := reflect.ValueOf("Hugo")
diff --git a/common/hstrings/strings.go b/common/hstrings/strings.go
index 88df97607..d9426ab5d 100644
--- a/common/hstrings/strings.go
+++ b/common/hstrings/strings.go
@@ -1,4 +1,4 @@
-// Copyright 2023 The Hugo Authors. All rights reserved.
+// 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.
@@ -122,3 +122,8 @@ func InSlicEqualFold(arr []string, el string) bool {
}
return false
}
+
+type Tuple struct {
+ First string
+ Second string
+}
diff --git a/common/hstrings/strings_test.go b/common/hstrings/strings_test.go
index 85068bdf9..d8e9e204a 100644
--- a/common/hstrings/strings_test.go
+++ b/