hugo/deps/deps.go
Bjørn Erik Pedersen 7285e74090
all: Rework page store, add a dynacache, improve partial rebuilds, and some general spring cleaning
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
2024-01-27 16:28:14 +01:00

418 lines
9 KiB
Go

package deps
import (
"context"
"fmt"
"io"
"path/filepath"
"sort"
"strings"
"sync"
"sync/atomic"
"github.com/bep/logg"
"github.com/gohugoio/hugo/cache/dynacache"
"github.com/gohugoio/hugo/cache/filecache"
"github.com/gohugoio/hugo/common/hexec"
"github.com/gohugoio/hugo/common/loggers"
"github.com/gohugoio/hugo/config"
"github.com/gohugoio/hugo/config/allconfig"
"github.com/gohugoio/hugo/config/security"
"github.com/gohugoio/hugo/helpers"
"github.com/gohugoio/hugo/hugofs"
"github.com/gohugoio/hugo/media"
"github.com/gohugoio/hugo/resources/page"
"github.com/gohugoio/hugo/resources/postpub"
"github.com/gohugoio/hugo/metrics"
"github.com/gohugoio/hugo/resources"
"github.com/gohugoio/hugo/source"
"github.com/gohugoio/hugo/tpl"
"github.com/spf13/afero"
)
// Deps holds dependencies used by many.
// There will be normally only one instance of deps in play
// at a given time, i.e. one per Site built.
type Deps struct {
// The logger to use.
Log loggers.Logger `json:"-"`
ExecHelper *hexec.Exec
// The templates to use. This will usually implement the full tpl.TemplateManager.
tmplHandlers *tpl.TemplateHandlers
// The file systems to use.
Fs *hugofs.Fs `json:"-"`
// The PathSpec to use
*helpers.PathSpec `json:"-"`
// The ContentSpec to use
*helpers.ContentSpec `json:"-"`
// The SourceSpec to use
SourceSpec *source.SourceSpec `json:"-"`
// The Resource Spec to use
ResourceSpec *resources.Spec
// The configuration to use
Conf config.AllProvider `json:"-"`
// The memory cache to use.
MemCache *dynacache.Cache
// The translation func to use
Translate func(ctx context.Context, translationID string, templateData any) string `json:"-"`
// The site building.
Site page.Site
TemplateProvider ResourceProvider
// Used in tests
OverloadedTemplateFuncs map[string]any
TranslationProvider ResourceProvider
Metrics metrics.Provider
// BuildStartListeners will be notified before a build starts.
BuildStartListeners *Listeners
// BuildEndListeners will be notified after a build finishes.
BuildEndListeners *Listeners
// Resources that gets closed when the build is done or the server shuts down.
BuildClosers *Closers
// This is common/global for all sites.
BuildState *BuildState
*globalErrHandler
}
func (d Deps) Clone(s page.Site, conf config.AllProvider) (*Deps, error) {
d.Conf = conf
d.Site = s
d.ExecHelper = nil
d.ContentSpec = nil
if err := d.Init(); err != nil {
return nil, err
}
return &d, nil
}
func (d *Deps) SetTempl(t *tpl.TemplateHandlers) {
d.tmplHandlers = t
}
func (d *Deps) Init() error {
if d.Conf == nil {
panic("conf is nil")
}
if d.Fs == nil {
// For tests.
d.Fs = hugofs.NewFrom(afero.NewMemMapFs(), d.Conf.BaseConfig())
}
if d.Log == nil {
d.Log = loggers.NewDefault()
}
if d.globalErrHandler == nil {
d.globalErrHandler = &globalErrHandler{
logger: d.Log,
}
}
if d.BuildState == nil {
d.BuildState = &BuildState{}
}
if d.BuildStartListeners == nil {
d.BuildStartListeners = &Listeners{}
}
if d.BuildEndListeners == nil {
d.BuildEndListeners = &Listeners{}
}
if d.BuildClosers == nil {
d.BuildClosers = &Closers{}
}
if d.Metrics == nil && d.Conf.TemplateMetrics() {
d.Metrics = metrics.NewProvider(d.Conf.TemplateMetricsHints())
}
if d.ExecHelper == nil {
d.ExecHelper = hexec.New(d.Conf.GetConfigSection("security").(security.Config))
}
if d.MemCache == nil {
d.MemCache = dynacache.New(dynacache.Options{Running: d.Conf.Running(), Log: d.Log})
}
if d.PathSpec == nil {
hashBytesReceiverFunc := func(name string, match bool) {
if !match {
return
}
d.BuildState.AddFilenameWithPostPrefix(name)
}
// Skip binary files.
mediaTypes := d.Conf.GetConfigSection("mediaTypes").(media.Types)
hashBytesSHouldCheck := func(name string) bool {
ext := strings.TrimPrefix(filepath.Ext(name), ".")
return mediaTypes.IsTextSuffix(ext)
}
d.Fs.PublishDir = hugofs.NewHasBytesReceiver(d.Fs.PublishDir, hashBytesSHouldCheck, hashBytesReceiverFunc, []byte(postpub.PostProcessPrefix))
pathSpec, err := helpers.NewPathSpec(d.Fs, d.Conf, d.Log)
if err != nil {
return err
}
d.PathSpec = pathSpec
} else {
var err error
d.PathSpec, err = helpers.NewPathSpecWithBaseBaseFsProvided(d.Fs, d.Conf, d.Log, d.PathSpec.BaseFs)
if err != nil {
return err
}
}
if d.ContentSpec == nil {
contentSpec, err := helpers.NewContentSpec(d.Conf, d.Log, d.Content.Fs, d.ExecHelper)
if err != nil {
return err
}
d.ContentSpec = contentSpec
}
if d.SourceSpec == nil {
d.SourceSpec = source.NewSourceSpec(d.PathSpec, nil, d.Fs.Source)
}
var common *resources.SpecCommon
if d.ResourceSpec != nil {
common = d.ResourceSpec.SpecCommon
}
fileCaches, err := filecache.NewCaches(d.PathSpec)
if err != nil {
return fmt.Errorf("failed to create file caches from configuration: %w", err)
}
resourceSpec, err := resources.NewSpec(d.PathSpec, common, fileCaches, d.MemCache, d.BuildState, d.Log, d, d.ExecHelper)
if err != nil {
return fmt.Errorf("failed to create resource spec: %w", err)
}
d.ResourceSpec = resourceSpec
return nil
}
func (d *Deps) Compile(prototype *Deps) error {
var err error
if prototype == nil {
if err = d.TemplateProvider.NewResource(d); err != nil {
return err
}
if err = d.TranslationProvider.NewResource(d); err != nil {
return err
}
return nil
}
if err = d.TemplateProvider.CloneResource(d, prototype); err != nil {
return err
}
if err = d.TranslationProvider.CloneResource(d, prototype); err != nil {
return err
}
return nil
}
type globalErrHandler struct {
logger loggers.Logger
// Channel for some "hard to get to" build errors
buildErrors chan error
// Used to signal that the build is done.
quit chan struct{}
}
// SendError sends the error on a channel to be handled later.
// This can be used in situations where returning and aborting the current
// operation isn't practical.
func (e *globalErrHandler) SendError(err error) {
if e.buildErrors != nil {
select {
case <-e.quit:
case e.buildErrors <- err:
default:
}
return
}
e.logger.Errorln(err)
}
func (e *globalErrHandler) StartErrorCollector() chan error {
e.quit = make(chan struct{})
e.buildErrors = make(chan error, 10)
return e.buildErrors
}
func (e *globalErrHandler) StopErrorCollector() {
if e.buildErrors != nil {
close(e.quit)
close(e.buildErrors)
}
}
// Listeners represents an event listener.
type Listeners struct {
sync.Mutex
// A list of funcs to be notified about an event.
listeners []func()
}
// Add adds a function to a Listeners instance.
func (b *Listeners) Add(f func()) {
if b == nil {
return
}
b.Lock()
defer b.Unlock()
b.listeners = append(b.listeners, f)
}
// Notify executes all listener functions.
func (b *Listeners) Notify() {
b.Lock()
defer b.Unlock()
for _, notify := range b.listeners {
notify()
}
}
// ResourceProvider is used to create and refresh, and clone resources needed.
type ResourceProvider interface {
NewResource(dst *Deps) error
CloneResource(dst, src *Deps) error
}
func (d *Deps) Tmpl() tpl.TemplateHandler {
return d.tmplHandlers.Tmpl
}
func (d *Deps) TextTmpl() tpl.TemplateParseFinder {
return d.tmplHandlers.TxtTmpl
}
func (d *Deps) Close() error {
if d.MemCache != nil {
d.MemCache.Stop()
}
return d.BuildClosers.Close()
}
// DepsCfg contains configuration options that can be used to configure Hugo
// on a global level, i.e. logging etc.
// Nil values will be given default values.
type DepsCfg struct {
// The logger to use. Only set in some tests.
// TODO(bep) get rid of this.
TestLogger loggers.Logger
// The logging level to use.
LogLevel logg.Level
// Where to write the logs.
// Currently we typically write everything to stdout.
LogOut io.Writer
// The file systems to use
Fs *hugofs.Fs
// The Site in use
Site page.Site
Configs *allconfig.Configs
// Template handling.
TemplateProvider ResourceProvider
// i18n handling.
TranslationProvider ResourceProvider
}
// BuildState are state used during a build.
type BuildState struct {
counter uint64
mu sync.Mutex // protects state below.
// A set of ilenames in /public that
// contains a post-processing prefix.
filenamesWithPostPrefix map[string]bool
}
func (b *BuildState) AddFilenameWithPostPrefix(filename string) {
b.mu.Lock()
defer b.mu.Unlock()
if b.filenamesWithPostPrefix == nil {
b.filenamesWithPostPrefix = make(map[string]bool)
}
b.filenamesWithPostPrefix[filename] = true
}
func (b *BuildState) GetFilenamesWithPostPrefix() []string {
b.mu.Lock()
defer b.mu.Unlock()
var filenames []string
for filename := range b.filenamesWithPostPrefix {
filenames = append(filenames, filename)
}
sort.Strings(filenames)
return filenames
}
func (b *BuildState) Incr() int {
return int(atomic.AddUint64(&b.counter, uint64(1)))
}
type Closer interface {
Close() error
}
type Closers struct {
mu sync.Mutex
cs []Closer
}
func (cs *Closers) Add(c Closer) {
cs.mu.Lock()
defer cs.mu.Unlock()
cs.cs = append(cs.cs, c)
}
func (cs *Closers) Close() error {
cs.mu.Lock()
defer cs.mu.Unlock()
for _, c := range cs.cs {
c.Close()
}
cs.cs = cs.cs[:0]
return nil
}