Debian Codegraph @

hugolib/content_map_page.go

raw
1 // Copyright 2025 The Hugo Authors. All rights reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package hugolib
15
16 import (
17 "context"
18 "fmt"
19 "io"
20 "path"
21 "sort"
22 "strconv"
23 "strings"
24 "sync/atomic"
25
26 "github.com/bep/logg"
27 "github.com/gohugoio/go-radix"
28 "github.com/gohugoio/hugo/cache/dynacache"
29 "github.com/gohugoio/hugo/common/hmaps"
30 "github.com/gohugoio/hugo/common/loggers"
31 "github.com/gohugoio/hugo/common/paths"
32 "github.com/gohugoio/hugo/common/predicate"
33 "github.com/gohugoio/hugo/common/rungroup"
34 "github.com/gohugoio/hugo/hugofs/files"
35 "github.com/gohugoio/hugo/hugofs/hglob"
36 "github.com/gohugoio/hugo/hugolib/doctree"
37 "github.com/gohugoio/hugo/hugolib/pagesfromdata"
38 "github.com/gohugoio/hugo/hugolib/sitesmatrix"
39 "github.com/gohugoio/hugo/identity"
40 "github.com/gohugoio/hugo/output"
41 "github.com/gohugoio/hugo/resources"
42
43 "github.com/gohugoio/hugo/resources/kinds"
44 "github.com/gohugoio/hugo/resources/page"
45 "github.com/gohugoio/hugo/resources/resource"
46 )
47
48 var pagePredicates = struct {
49 KindPage predicate.PR[*pageState]
50 KindSection predicate.PR[*pageState]
51 KindHome predicate.PR[*pageState]
52 KindTerm predicate.PR[*pageState]
53 ShouldListLocal predicate.PR[*pageState]
54 ShouldListGlobal predicate.PR[*pageState]
55 ShouldListAny predicate.PR[*pageState]
56 ShouldLink predicate.PR[page.Page]
57 }{
58 KindPage: func(p *pageState) predicate.Match {
59 return predicate.BoolMatch(p.Kind() == kinds.KindPage)
60 },
61 KindSection: func(p *pageState) predicate.Match {
62 return predicate.BoolMatch(p.Kind() == kinds.KindSection)
63 },
64 KindHome: func(p *pageState) predicate.Match {
65 return predicate.BoolMatch(p.Kind() == kinds.KindHome)
66 },
67 KindTerm: func(p *pageState) predicate.Match {
68 return predicate.BoolMatch(p.Kind() == kinds.KindTerm)
69 },
70 ShouldListLocal: func(p *pageState) predicate.Match {
71 return predicate.BoolMatch(p.m.shouldList(false))
72 },
73 ShouldListGlobal: func(p *pageState) predicate.Match {
74 return predicate.BoolMatch(p.m.shouldList(true))
75 },
76 ShouldListAny: func(p *pageState) predicate.Match {
77 return predicate.BoolMatch(p.m.shouldListAny())
78 },
79 ShouldLink: func(p page.Page) predicate.Match {
80 return predicate.BoolMatch(!p.(*pageState).m.noLink())
81 },
82 }
83
84 type pageMap struct {
85 i int
86 s *Site
87
88 // Main storage for all pages.
89 *pageTrees
90
91 // Used for simple page lookups by name, e.g. "mypage.md" or "mypage".
92 pageReverseIndex *contentTreeReverseIndex
93
94 cachePages1 *dynacache.Partition[string, page.Pages]
95 cachePages2 *dynacache.Partition[string, page.Pages]
96 cacheResources *dynacache.Partition[string, resource.Resources]
97 cacheGetTerms *dynacache.Partition[string, map[string]page.Pages]
98 cacheContentRendered *dynacache.Partition[string, *resources.StaleValue[contentSummary]]
99 cacheContentPlain *dynacache.Partition[string, *resources.StaleValue[contentPlainPlainWords]]
100 contentTableOfContents *dynacache.Partition[string, *resources.StaleValue[contentTableOfContents]]
101
102 contentDataFileSeenItems *hmaps.Cache[string, map[uint64]bool]
103
104 cfg contentMapConfig
105 }
106
107 // Invoked on rebuilds.
108 func (m *pageMap) Reset() {
109 m.pageReverseIndex.Reset()
110 }
111
112 // pageTrees holds pages and resources in a tree structure for all sites/languages.
113 // Each site gets its own tree set via the Shape method.
114 type pageTrees struct {
115 // This tree contains all Pages.
116 // This include regular pages, sections, taxonomies and so on.
117 // Note that all of these trees share the same key structure,
118 // so you can take a leaf Page key and do a prefix search
119 // with key + "/" to get all of its resources.
120 treePages *doctree.NodeShiftTree[contentNode]
121
122 // This tree contains Resources bundled in pages.
123 treeResources *doctree.NodeShiftTree[contentNode]
124
125 // All pages and resources.
126 treePagesResources doctree.WalkableTrees[contentNode]
127
128 // This tree contains all taxonomy entries, e.g "/tags/blue/page1"
129 treeTaxonomyEntries *doctree.TreeShiftTreeSlice[*weightedContentNode]
130
131 // Stores the state for _content.gotmpl files.
132 // Mostly releveant for rebuilds.
133 treePagesFromTemplateAdapters *doctree.TreeShiftTreeSlice[*pagesfromdata.PagesFromTemplate]
134
135 // A slice of the resource trees.
136 resourceTrees doctree.MutableTrees
137 }
138
139 // collectAndMarkStaleIdentities collects all identities from in all trees matching the given key.
140 // We currently re-read all page/resources for all languages that share the same path,
141 // so we mark all entries as stale (which will trigger cache invalidation), then
142 // return the first.
143 func (t *pageTrees) collectAndMarkStaleIdentities(p *paths.Path) []identity.Identity {
144 key := p.Base()
145 var ids []identity.Identity
146 // We need only one identity sample per dimension.
147 nCount := 0
148 cb := func(n contentNode) bool {
149 if n == nil {
150 return false
151 }
152 cnh.markStale(n)
153 if nCount > 0 {
154 return true
155 }
156 nCount++
157
158 cnh.toForEachIdentityProvider(n).ForEeachIdentity(func(id identity.Identity) bool {
159 ids = append(ids, id)
160 return false
161 })
162
163 return false
164 }
165 tree := t.treePages
166 nCount = 0
167 tree.ForEeachInAllDimensions(key, cb)
168
169 tree = t.treeResources
170 nCount = 0
171 tree.ForEeachInAllDimensions(key, cb)
172
173 if p.Component() == files.ComponentFolderContent {
174 // It may also be a bundled content resource.
175 key := p.ForType(paths.TypeContentResource).Base()
176 tree = t.treeResources
177 nCount = 0
178 tree.ForEeachInAllDimensions(key, cb)
179
180 }
181 return ids
182 }
183
184 // collectIdentitiesSurrounding collects all identities surrounding the given key.
185 func (t *pageTrees) collectIdentitiesSurrounding(key string, maxSamplesPerTree int) []identity.Identity {
186 ids := t.collectIdentitiesSurroundingIn(key, maxSamplesPerTree, t.treePages)
187 ids = append(ids, t.collectIdentitiesSurroundingIn(key, maxSamplesPerTree, t.treeResources)...)
188 return ids
189 }
190
191 func (t *pageTrees) collectIdentitiesSurroundingIn(key string, maxSamples int, tree *doctree.NodeShiftTree[contentNode]) []identity.Identity {
192 var ids []identity.Identity
193 section, ok := tree.LongestPrefixRaw(path.Dir(key))
194 if ok {
195 count := 0
196 prefix := section + "/"
197 level := strings.Count(prefix, "/")
198 tree.WalkPrefixRaw(prefix, func(s string, n contentNode) (radix.WalkFlag, contentNode, error) {
199 if level != strings.Count(s, "/") {
200 return radix.WalkContinue, nil, nil
201 }
202 cnh.toForEachIdentityProvider(n).ForEeachIdentity(func(id identity.Identity) bool {
203 ids = append(ids, id)
204 return false
205 })
206 count++
207 if count > maxSamples {
208 return radix.WalkStop, nil, nil
209 }
210 return radix.WalkContinue, nil, nil
211 })
212 }
213
214 return ids
215 }
216
217 func (t *pageTrees) DeletePageAndResourcesBelow(ss ...string) {
218 t.resourceTrees.Lock(true)
219 defer t.resourceTrees.Unlock(true)
220 t.treePages.Lock(true)
221 defer t.treePages.Unlock(true)
222 for _, s := range ss {
223 t.resourceTrees.DeletePrefix(paths.AddTrailingSlash(s))
224 t.treePages.Delete(s)
225 }
226 }
227
228 func (t pageTrees) Shape(v sitesmatrix.Vector) *pageTrees {
229 t.treePages = t.treePages.Shape(v)
230 t.treeResources = t.treeResources.Shape(v)
231 t.treeTaxonomyEntries = t.treeTaxonomyEntries.Shape(v)
232 t.treePagesFromTemplateAdapters = t.treePagesFromTemplateAdapters.Shape(v)
233 t.createMutableTrees()
234
235 return &t
236 }
237
238 func (t *pageTrees) createMutableTrees() {
239 t.treePagesResources = doctree.WalkableTrees[contentNode]{
240 t.treePages,
241 t.treeResources,
242 }
243
244 t.resourceTrees = doctree.MutableTrees{
245 t.treeResources,
246 }
247 }
248
249 var (
250 _ resource.Identifier = pageMapQueryPagesInSection{}
251 _ resource.Identifier = pageMapQueryPagesBelowPath{}
252 )
253
254 type pageMapQueryPagesInSection struct {
255 pageMapQueryPagesBelowPath
256
257 Recursive bool
258 IncludeSelf bool
259 }
260
261 func (q pageMapQueryPagesInSection) Key() string {
262 return "gagesInSection" + "/" + q.pageMapQueryPagesBelowPath.Key() + "/" + strconv.FormatBool(q.Recursive) + "/" + strconv.FormatBool(q.IncludeSelf)
263 }
264
265 // This needs to be hashable.
266 type pageMapQueryPagesBelowPath struct {
267 Path string
268
269 // Additional identifier for this query.
270 // Used as part of the cache key.
271 KeyPart string
272
273 // Page inclusion filter.
274 // May be nil.
275 Include predicate.P[*pageState]
276 }
277
278 func (q pageMapQueryPagesBelowPath) Key() string {
279 return q.Path + "/" + q.KeyPart
280 }
281
282 // Apply fn to all pages in m matching the given predicate.
283 // fn may return true to stop the walk.
284 func (m *pageMap) forEachPage(include predicate.PR[*pageState], fn func(p *pageState) (bool, error)) error {
285 if include == nil {
286 include = func(p *pageState) predicate.Match {
287 return predicate.True
288 }
289 }
290 w := &doctree.NodeShiftTreeWalker[contentNode]{
291 Tree: m.treePages,
292 LockType: doctree.LockTypeRead,
293 Handle: func(key string, n contentNode) (radix.WalkFlag, error) {
294 if p, ok := n.(*pageState); ok && include(p).OK() {
295 if terminate, err := fn(p); terminate || err != nil {
296 return radix.WalkStop, err
297 }
298 }
299 return radix.WalkContinue, nil
300 },
301 }
302
303 return w.Walk(context.Background())
304 }
305
306 func (m *pageMap) forEeachPageIncludingBundledPages(include predicate.PR[*pageState], fn func(p *pageState) (bool, error)) error {
307 if include == nil {
308 include = func(p *pageState) predicate.Match {
309 return predicate.True
310 }
311 }
312
313 if err := m.forEachPage(include, fn); err != nil {
314 return err
315 }
316
317 w := &doctree.NodeShiftTreeWalker[contentNode]{
318 Tree: m.treeResources,
319 LockType: doctree.LockTypeRead,
320 Handle: func(key string, n contentNode) (radix.WalkFlag, error) {
321 if p, ok := n.(*pageState); ok && include(p).OK() {
322 if terminate, err := fn(p); terminate || err != nil {
323 return radix.WalkStop, err
324 }
325 }
326 return radix.WalkContinue, nil
327 },
328 }
329
330 return w.Walk(context.Background())
331 }
332
333 func (m *pageMap) getOrCreatePagesFromCache(
334 cache *dynacache.Partition[string, page.Pages],
335 key string, create func(string) (page.Pages, error),
336 ) (page.Pages, error) {
337 if cache == nil {
338 cache = m.cachePages1
339 }
340 return cache.GetOrCreate(key, create)
341 }
342
343 func (m *pageMap) getPagesInSection(q pageMapQueryPagesInSection) page.Pages {
344 cacheKey := q.Key()
345
346 pages, err := m.getOrCreatePagesFromCache(nil, cacheKey, func(string) (page.Pages, error) {
347 prefix := paths.AddTrailingSlash(q.Path)
348
349 var (
350 pas page.Pages
351 otherBranch string
352 )
353
354 include := q.Include
355 if include == nil {
356 include = pagePredicates.ShouldListLocal.BoolFunc()
357 }
358
359 w := &doctree.NodeShiftTreeWalker[contentNode]{
360 Tree: m.treePages,
361 Prefix: prefix,
362 Fallback: true,
363 }
364
365 w.Handle = func(key string, n contentNode) (radix.WalkFlag, error) {
366 if q.Recursive {
367 if p, ok := n.(*pageState); ok && include(p) {
368 pas = append(pas, p)
369 }
370 return radix.WalkContinue, nil
371 }
372
373 if p, ok := n.(*pageState); ok && include(p) {
374 pas = append(pas, p)
375 }
376
377 if cnh.isBranchNode(n) {
378 currentBranch := key + "/"
379 if otherBranch == "" || otherBranch != currentBranch {
380 w.SkipPrefix(currentBranch)
381 }
382 otherBranch = currentBranch
383 }
384 return radix.WalkContinue, nil
385 }
386
387 err := w.Walk(context.Background())
388
389 if err == nil {
390 if q.IncludeSelf {
391 if n := m.treePages.GetWithFallback(q.Path); n != nil {
392 if p, ok := n.(*pageState); ok && include(p) {
393 pas = append(pas, p)
394 }
395 }
396 }
397 page.SortByDefault(pas)
398 }
399
400 return pas, err
401 })
402 if err != nil {
403 panic(err)
404 }
405
406 return pages
407 }
408
409 func (m *pageMap) getPagesWithTerm(q pageMapQueryPagesBelowPath) page.Pages {
410 key := q.Key()
411
412 v, err := m.cachePages1.GetOrCreate(key, func(string) (page.Pages, error) {
413 var pas page.Pages
414 include := q.Include
415 if include == nil {
416 include = pagePredicates.ShouldListLocal.BoolFunc()
417 }
418
419 err := m.treeTaxonomyEntries.WalkPrefix(
420 doctree.LockTypeNone,
421 paths.AddTrailingSlash(q.Path),
422 func(s string, n *weightedContentNode) (bool, error) {
423 p := n.n.(*pageState)
424 if !include(p) {
425 return false, nil
426 }
427 pas = append(pas, pageWithWeight0{n.weight, p})
428 return false, nil
429 },
430 )
431 if err != nil {
432 return nil, err
433 }
434
435 page.SortByDefault(pas)
436
437 return pas, nil
438 })
439 if err != nil {
440 panic(err)
441 }
442
443 return v
444 }
445
446 func (m *pageMap) getTermsForPageInTaxonomy(path, taxonomy string) page.Pages {
447 prefix := paths.AddLeadingSlash(taxonomy)
448
449 termPages, err := m.cacheGetTerms.GetOrCreate(prefix, func(string) (map[string]page.Pages, error) {
450 mm := make(map[string]page.Pages)
451 err := m.treeTaxonomyEntries.WalkPrefix(
452 doctree.LockTypeNone,
453 paths.AddTrailingSlash(prefix),
454 func(s string, n *weightedContentNode) (bool, error) {
455 mm[n.n.Path()] = append(mm[n.n.Path()], n.term)
456 return false, nil
457 },
458 )
459 if err != nil {
460 return nil, err
461 }
462
463 // Sort the terms.
464 for _, v := range mm {
465 page.SortByDefault(v)
466 }
467
468 return mm, nil
469 })
470 if err != nil {
471 panic(err)
472 }
473
474 return termPages[path]
475 }
476
477 func (m *pageMap) forEachResourceInPage(
478 ps *pageState,
479 lockType doctree.LockType,
480 fallback bool,
481 transform func(resourceKey string, n contentNode) (n2 contentNode, ns doctree.NodeTransformState, err error),
482 handle func(resourceKey string, n contentNode) (bool, error),
483 ) error {
484 keyPage := ps.Path()
485 if keyPage == "/" {
486 keyPage = ""
487 }
488
489 prefix := paths.AddTrailingSlash(ps.Path())
490
491 isBranch := ps.IsBranch()
492
493 rwr := &doctree.NodeShiftTreeWalker[contentNode]{
494 Tree: m.treeResources,
495 Prefix: prefix,
496 LockType: lockType,
497 Fallback: fallback,
498 }
499
500 shouldSkipOrTerminate := func(resourceKey string) (ns doctree.NodeTransformState) {
501 if !isBranch {
502 return
503 }
504
505 // A resourceKey always represents a filename with extension.
506 // A page key points to the logical path of a page, which when sourced from the filesystem
507 // may represent a directory (bundles) or a single content file (e.g. p1.md).
508 // So, to avoid any overlapping ambiguity, we start looking from the owning directory.
509 s := resourceKey
510
511 for {
512 s = path.Dir(s)
513 ownerKey, found := m.treePages.LongestPrefixRaw(s)
514
515 if !found {
516 return doctree.NodeTransformStateTerminate
517 }
518 if ownerKey == keyPage {
519 break
520 }
521
522 if s != ownerKey && strings.HasPrefix(s, ownerKey) {
523 // Keep looking
524 continue
525 }
526
527 // Stop walking downwards, someone else owns this resource.
528 rwr.SkipPrefix(ownerKey + "/")
529 return doctree.NodeTransformStateSkip
530 }
531 return
532 }
533
534 if transform != nil {
535 rwr.Transform = func(resourceKey string, n contentNode) (n2 contentNode, ns doctree.NodeTransformState, err error) {
536 if ns = shouldSkipOrTerminate(resourceKey); ns >= doctree.NodeTransformStateSkip {
537 return
538 }
539 return transform(resourceKey, n)
540 }
541 }
542
543 rwr.Handle = func(resourceKey string, n contentNode) (radix.WalkFlag, error) {
544 if transform == nil {
545 if ns := shouldSkipOrTerminate(resourceKey); ns >= doctree.NodeTransformStateSkip {
546 if ns == doctree.NodeTransformStateTerminate {
547 return radix.WalkStop, nil
548 }
549 return radix.WalkContinue, nil
550 }
551 }
552 b, err := handle(resourceKey, n)
553 if b || err != nil {
554 return radix.WalkStop, err
555 }
556 return radix.WalkContinue, nil
557 }
558
559 return rwr.Walk(context.Background())
560 }
561
562 func (m *pageMap) getResourcesForPage(ps *pageState) (resource.Resources, error) {
563 var res resource.Resources
564
565 m.forEachResourceInPage(ps, doctree.LockTypeNone, true, nil, func(resourceKey string, n contentNode) (bool, error) {
566 switch n := n.(type) {
567 case *resourceSource:
568 r := n.r
569
570 if r == nil {
571 panic(fmt.Sprintf("getResourcesForPage: resource %q for page %q has no resource, sites matrix %v/%v", resourceKey, ps.Path(), ps.siteVector(), n.sv))
572 }
573 res = append(res, r)
574 case *pageState:
575 res = append(res, n)
576 default:
577 panic(fmt.Sprintf("getResourcesForPage: unknown type %T", n))
578 }
579
580 return false, nil
581 })
582 return res, nil
583 }
584
585 func (m *pageMap) getOrCreateResourcesForPage(ps *pageState) resource.Resources {
586 keyPage := ps.Path()
587 if keyPage == "/" {
588 keyPage = ""
589 }
590 key := keyPage + "/get-resources-for-page"
591
592 v, err := m.cacheResources.GetOrCreate(key, func(string) (resource.Resources, error) {
593 res, err := m.getResourcesForPage(ps)
594 if err != nil {
595 return nil, err
596 }
597
598 if translationKey := ps.m.pageConfig.TranslationKey; translationKey != "" {
599 // This this should not be a very common case.
600 // Merge in resources from the other languages.
601 translatedPages, _ := m.s.h.translationKeyPages.Get(translationKey)
602 for _, tp := range translatedPages {
603 if tp == ps {
604 continue
605 }
606 tps := tp.(*pageState)
607 // Make sure we query from the correct language root.
608 res2, err := tps.s.pageMap.getResourcesForPage(tps)
609 if err != nil {
610 return nil, err
611 }
612 // Add if Name not already in res.
613 for _, r := range res2 {
614 var found bool
615 for _, r2 := range res {
616 if resource.NameNormalizedOrName(r2) == resource.NameNormalizedOrName(r) {
617 found = true
618 break
619 }
620 }
621 if !found {
622 res = append(res, r)
623 }
624 }
625 }
626 }
627
628 lessFunc := func(i, j int) bool {
629 ri, rj := res[i], res[j]
630 if ri.ResourceType() < rj.ResourceType() {
631 return true
632 }
633
634 p1, ok1 := ri.(page.Page)
635 p2, ok2 := rj.(page.Page)
636
637 if ok1 != ok2 {
638 // Pull pages behind other resources.
639
640 return ok2
641 }
642
643 if ok1 {
644 return page.DefaultPageSort(p1, p2)
645 }
646
647 // Make sure not to use RelPermalink or any of the other methods that
648 // trigger lazy publishing.
649 return ri.Name() < rj.Name()
650 }
651
652 sort.SliceStable(res, lessFunc)
653
654 if len(ps.m.pageConfig.ResourcesMeta) > 0 {
655 counters := make(map[string]int)
656 for i, r := range res {
657 res[i] = resources.CloneWithMetadataFromMapIfNeeded(ps.m.pageConfig.ResourcesMeta, r, counters)
658 }
659 sort.SliceStable(res, lessFunc)
660 }
661
662 return res, nil
663 })
664 if err != nil {
665 panic(err)
666 }
667
668 return v
669 }
670
671 var _ doctree.Transformer[contentNode] = (*contentNodeTransformerRaw)(nil)
672
673 type contentNodeTransformerRaw struct{}
674
675 func (t *contentNodeTransformerRaw) Append(n contentNode, ns ...contentNode) (contentNode, bool) {
676 if n == nil {
677 if len(ns) == 1 {
678 return ns[0], true
679 }
680 var ss contentNodes = ns
681 return ss, true
682 }
683
684 switch v := n.(type) {
685 case contentNodes:
686 v = append(v, ns...)
687 return v, true
688 default:
689 ss := make(contentNodes, 0, 1+len(ns))
690 ss = append(ss, v)
691 ss = append(ss, ns...)
692 return ss, true
693 }
694 }
695
696 func newPageMap(s *Site, mcache *dynacache.Cache, pageTrees *pageTrees) *pageMap {
697 var m *pageMap
698
699 vec := s.siteVector
700 languageVersionRole := fmt.Sprintf("s%d/%d&%d", vec.Language(), vec.Version(), vec.Role())
701
702 var taxonomiesConfig taxonomiesConfig = s.conf.Taxonomies
703
704 m = &pageMap{
705 pageTrees: pageTrees.Shape(vec),
706 cachePages1: dynacache.GetOrCreatePartition[string, page.Pages](mcache, fmt.Sprintf("/pag1/%s", languageVersionRole), dynacache.OptionsPartition{Weight: 10, ClearWhen: dynacache.ClearOnRebuild}),
707 cachePages2: dynacache.GetOrCreatePartition[string, page.Pages](mcache, fmt.Sprintf("/pag2/%s", languageVersionRole), dynacache.OptionsPartition{Weight: 10, ClearWhen: dynacache.ClearOnRebuild}),
708 cacheGetTerms: dynacache.GetOrCreatePartition[string, map[string]page.Pages](mcache, fmt.Sprintf("/gett/%s", languageVersionRole), dynacache.OptionsPartition{Weight: 5, ClearWhen: dynacache.ClearOnRebuild}),
709 cacheResources: dynacache.GetOrCreatePartition[string, resource.Resources](mcache, fmt.Sprintf("/ress/%s", languageVersionRole), dynacache.OptionsPartition{Weight: 60, ClearWhen: dynacache.ClearOnRebuild}),
710 cacheContentRendered: dynacache.GetOrCreatePartition[string, *resources.StaleValue[contentSummary]](mcache, fmt.Sprintf("/cont/ren/%s", languageVersionRole), dynacache.OptionsPartition{Weight: 70, ClearWhen: dynacache.ClearOnChange}),
711 cacheContentPlain: dynacache.GetOrCreatePartition[string, *resources.StaleValue[contentPlainPlainWords]](mcache, fmt.Sprintf("/cont/pla/%s", languageVersionRole), dynacache.OptionsPartition{Weight: 70, ClearWhen: dynacache.ClearOnChange}),
712 contentTableOfContents: dynacache.GetOrCreatePartition[string, *resources.StaleValue[contentTableOfContents]](mcache, fmt.Sprintf("/cont/toc/%s", languageVersionRole), dynacache.OptionsPartition{Weight: 70, ClearWhen: dynacache.ClearOnChange}),
713
714 contentDataFileSeenItems: hmaps.NewCache[string, map[uint64]bool](),
715
716 cfg: contentMapConfig{
717 lang: s.Lang(),
718 taxonomyConfig: taxonomiesConfig.Values(),
719 taxonomyDisabled: !s.conf.IsKindEnabled(kinds.KindTaxonomy),
720 taxonomyTermDisabled: !s.conf.IsKindEnabled(kinds.KindTerm),
721 pageDisabled: !s.conf.IsKindEnabled(kinds.KindPage),
722 },
723 i: s.siteVector.Language(),
724 s: s,
725 }
726
727 m.pageReverseIndex = newContentTreeTreverseIndex(func(get func(key any) (contentNode, bool), set func(key any, val contentNode)) {
728 add := func(k string, n contentNode) {
729 existing, found := get(k)
730 if found && existing != ambiguousContentNode {
731 set(k, ambiguousContentNode)
732 } else if !found {
733 set(k, n)
734 }
735 }
736
737 w := &doctree.NodeShiftTreeWalker[contentNode]{
738 Tree: m.treePages,
739 LockType: doctree.LockTypeRead,
740 Handle: func(s string, n contentNode) (radix.WalkFlag, error) {
741 p := n.(*pageState)
742 if p.PathInfo() != nil {
743 add(p.PathInfo().BaseNameNoIdentifier(), p)
744 }
745 return radix.WalkContinue, nil
746 },
747 }
748
749 if err := w.Walk(context.Background()); err != nil {
750 panic(err)
751 }
752 })
753
754 return m
755 }
756
757 func newContentTreeTreverseIndex(init func(get func(key any) (contentNode, bool), set func(key any, val contentNode))) *contentTreeReverseIndex {
758 return &contentTreeReverseIndex{
759 initFn: init,
760 mm: hmaps.NewCache[any, contentNode](),
761 }
762 }
763
764 type contentTreeReverseIndex struct {
765 initFn func(get func(key any) (contentNode, bool), set func(key any, val contentNode))
766 mm *hmaps.Cache[any, contentNode]
767 }
768
769 func (c *contentTreeReverseIndex) Reset() {
770 c.mm.Reset()
771 }
772
773 func (c *contentTreeReverseIndex) Get(key any) contentNode {
774 v, _ := c.mm.InitAndGet(key, func(get func(key any) (contentNode, bool), set func(key any, val contentNode)) error {
775 c.initFn(get, set)
776 return nil
777 })
778 return v
779 }
780
781 func (m *pageMap) debugPrint(prefix string, maxLevel int, w io.Writer) {
782 noshift := false
783
784 pageWalker := &doctree.NodeShiftTreeWalker[contentNode]{
785 NoShift: noshift,
786 Tree: m.treePages,
787 Prefix: prefix,
788 WalkContext: &doctree.WalkContext[contentNode]{},
789 }
790
791 resourceWalker := pageWalker.Extend()
792 resourceWalker.Tree = m.treeResources
793
794 pageWalker.Handle = func(keyPage string, n contentNode) (radix.WalkFlag, error) {
795 level := strings.Count(keyPage, "/")
796 if level > maxLevel {
797 return radix.WalkContinue, nil
798 }
799 const indentStr = " "
800 p := n.(*pageState)
801 lenIndent := 0
802 info := fmt.Sprintf("%s lm: %s (%s)", keyPage, p.Lastmod().Format("2006-01-02"), p.Kind())
803 fmt.Fprintln(w, info)
804 switch p.Kind() {
805 case kinds.KindTerm:
806 m.treeTaxonomyEntries.WalkPrefix(
807 doctree.LockTypeNone,
808 keyPage+"/",
809 func(s string, n *weightedContentNode) (bool, error) {
810 fmt.Fprint(w, strings.Repeat(indentStr, lenIndent+4))
811 fmt.Fprintln(w, s)
812 return false, nil
813 },
814 )
815 }
816
817 isBranch := cnh.isBranchNode(n)
818 resourceWalker.Prefix = keyPage + "/"
819
820 resourceWalker.Handle = func(ss string, n contentNode) (radix.WalkFlag, error) {
821 if isBranch {
822 ownerKey, _ := pageWalker.Tree.LongestPrefix(ss, false, nil)
823 if ownerKey != keyPage {
824 // Stop walking downwards, someone else owns this resource.
825 pageWalker.SkipPrefix(ownerKey + "/")
826 return radix.WalkContinue, nil
827 }
828 }
829 fmt.Fprint(w, strings.Repeat(indentStr, lenIndent+8))
830 fmt.Fprintln(w, ss+" (resource)")
831 return radix.WalkContinue, nil
832 }
833
834 if err := resourceWalker.Walk(context.Background()); err != nil {
835 return radix.WalkStop, err
836 }
837
838 return radix.WalkContinue, nil
839 }
840
841 err := pageWalker.Walk(context.Background())
842 if err != nil {
843 panic(err)
844 }
845 }
846
847 func (h *HugoSites) dynacacheGCFilenameIfNotWatchedAndDrainMatching(filename string) {
848 cpss := h.BaseFs.ResolvePaths(filename)
849 if len(cpss) == 0 {
850 return
851 }
852 // Compile cache busters.
853 var cacheBusters []func(string) bool
854 for _, cps := range cpss {
855 if cps.Watch {
856 continue
857 }
858 np := hglob.NormalizePath(path.Join(cps.Component, cps.Path))
859 g, err := h.ResourceSpec.BuildConfig().MatchCacheBuster(h.Log, np)
860 if err == nil && g != nil {
861 cacheBusters = append(cacheBusters, g)
862 }
863 }
864 if len(cacheBusters) == 0 {
865 return
866 }
867 cacheBusterOr := func(s string) bool {
868 for _, cb := range cacheBusters {
869 if cb(s) {
870 return true
871 }
872 }
873 return false
874 }
875
876 h.dynacacheGCCacheBuster(cacheBusterOr)
877
878 // We want to avoid that evicted items in the above is considered in the next step server change.
879 _ = h.MemCache.DrainEvictedIdentitiesMatching(func(ki dynacache.KeyIdentity) bool {
880 return cacheBusterOr(ki.Key.(string))
881 })
882 }
883
884 func (h *HugoSites) dynacacheGCCacheBuster(cachebuster func(s string) bool) {
885 if cachebuster == nil {
886 return
887 }
888 shouldDelete := func(k, v any) bool {
889 var b bool
890 if s, ok := k.(string); ok {
891 b = cachebuster(s)
892 }
893
894 return b
895 }
896
897 h.MemCache.ClearMatching(nil, shouldDelete)
898 }
899
900 func (h *HugoSites) resolveAndClearStateForIdentities(
901 ctx context.Context,
902 l logg.LevelLogger,
903 cachebuster func(s string) bool, changes []identity.Identity,
904 ) error {
905 // Drain the cache eviction stack to start fresh.
906 evictedStart := h.Deps.MemCache.DrainEvictedIdentities()
907
908 h.Log.Debug().Log(logg.StringFunc(
909 func() string {
910 var sb strings.Builder
911 for _, change := range changes {
912 var key string
913 if kp, ok := change.(resource.Identifier); ok {
914 key = " " + kp.Key()
915 }
916 sb.WriteString(fmt.Sprintf("Direct dependencies of %q (%T%s) =>\n", change.IdentifierBase(), change, key))
917 seen := map[string]bool{
918 change.IdentifierBase(): true,
919 }
920 // Print the top level dependencies.
921 identity.WalkIdentitiesDeep(change, func(level int, id identity.Identity) bool {
922 if level > 1 {
923 return true
924 }
925 if !seen[id.IdentifierBase()] {
926 sb.WriteString(fmt.Sprintf(" %s%s\n", strings.Repeat(" ", level), id.IdentifierBase()))
927 }
928 seen[id.IdentifierBase()] = true
929 return false
930 })
931 }
932 return sb.String()
933 }),
934 )
935
936 for _, id := range changes {
937 if staler, ok := id.(resource.Staler); ok {
938 var msgDetail string
939 if p, ok := id.(*pageState); ok && p.File() != nil {
940 msgDetail = fmt.Sprintf(" (%s)", p.File().Filename())
941 }
942 h.Log.Trace(logg.StringFunc(func() string { return fmt.Sprintf("Marking stale: %s (%T)%s\n", id, id, msgDetail) }))
943 staler.MarkStale()
944 }
945 }
946
947 // The order matters here:
948 // 1. Then GC the cache, which may produce changes.
949 // 2. Then reset the page outputs, which may mark some resources as stale.
950 if err := loggers.TimeTrackfn(func() (logg.LevelLogger, error) {
951 ll := l.WithField("substep", "gc dynacache")
952
953 predicate := func(k any, v any) bool {
954 if cachebuster != nil {
955 if s, ok := k.(string); ok {
956 return cachebuster(s)
957 }
958 }
959 return false
960 }
961
962 h.MemCache.ClearOnRebuild(predicate, changes...)
963 h.Log.Trace(logg.StringFunc(func() string {
964 var sb strings.Builder
965 sb.WriteString("dynacache keys:\n")
966 for _, key := range h.MemCache.Keys(nil) {
967 sb.WriteString(fmt.Sprintf(" %s\n", key))
968 }
969 return sb.String()
970 }))
971 return ll, nil
972 }); err != nil {
973 return err
974 }
975
976 // Drain the cache eviction stack.
977 evicted := h.Deps.MemCache.DrainEvictedIdentities()
978 if len(evicted) < 200 {
979 for _, c := range evicted {
980 changes = append(changes, c.Identity)
981 }
982
983 if len(evictedStart) > 0 {
984 // In low memory situations and/or very big sites, there can be a lot of unrelated evicted items,
985 // but there's a chance that some of them are related to the changes we are about to process,
986 // so check.
987 depsFinder := identity.NewFinder(identity.FinderConfig{})
988 var addends []identity.Identity
989 for _, ev := range evictedStart {
990 for _, id := range changes {
991 if cachebuster != nil && cachebuster(ev.Key.(string)) {
992 addends = append(addends, ev.Identity)
993 break
994 }
995 if r := depsFinder.Contains(id, ev.Identity, -1); r > 0 {
996 addends = append(addends, ev.Identity)
997 break
998 }
999 }
1000 }
1001 changes = append(changes, addends...)
1002 }
1003 } else {
1004 // Mass eviction, we might as well invalidate everything.
1005 changes = []identity.Identity{identity.GenghisKhan}
1006 }
1007
1008 // Remove duplicates
1009 seen := make(map[identity.Identity]bool)
1010 var n int
1011 for _, id := range changes {
1012 if !seen[id] {
1013 seen[id] = true
1014 changes[n] = id
1015 n++
1016 }
1017 }
1018 changes = changes[:n]
1019
1020 if h.pageTrees.treePagesFromTemplateAdapters.LenRaw() > 0 {
1021 if err := loggers.TimeTrackfn(func() (logg.LevelLogger, error) {
1022 ll := l.WithField("substep", "resolve content adapter change set").WithField("changes", len(changes))
1023 checkedCount := 0
1024 matchCount := 0
1025 depsFinder := identity.NewFinder(identity.FinderConfig{})
1026
1027 h.pageTrees.treePagesFromTemplateAdapters.WalkPrefixRaw(doctree.LockTypeRead, "",
1028 func(s string, n *pagesfromdata.PagesFromTemplate) (bool, error) {
1029 for _, id := range changes {
1030 checkedCount++
1031 if r := depsFinder.Contains(id, n.DependencyManager, 2); r > identity.FinderNotFound {
1032 n.MarkStale()
1033 matchCount++
1034 break
1035 }
1036 }
1037 return false, nil
1038 })
1039
1040 ll = ll.WithField("checked", checkedCount).WithField("matches", matchCount)
1041 return ll, nil
1042 }); err != nil {
1043 return err
1044 }
1045 }
1046
1047 if err := loggers.TimeTrackfn(func() (logg.LevelLogger, error) {
1048 // changesLeft: The IDs that the pages is dependent on.
1049 // changesRight: The IDs that the pages depend on.
1050 ll := l.WithField("substep", "resolve page output change set").WithField("changes", len(changes))
1051
1052 checkedCount, matchCount, err := h.resolveAndResetDependententPageOutputs(ctx, changes)
1053 ll = ll.WithField("checked", checkedCount).WithField("matches", matchCount)
1054 return ll, err
1055 }); err != nil {
1056 return err
1057 }
1058
1059 return nil
1060 }
1061
1062 // The left change set is the IDs that the pages is dependent on.
1063 // The right change set is the IDs that the pages depend on.
1064 func (h *HugoSites) resolveAndResetDependententPageOutputs(ctx context.Context, changes []identity.Identity) (int, int, error) {
1065 if changes == nil {
1066 return 0, 0, nil
1067 }
1068
1069 // This can be shared (many of the same IDs are repeated).
1070 depsFinder := identity.NewFinder(identity.FinderConfig{})
1071
1072 h.Log.Trace(logg.StringFunc(func() string {
1073 var sb strings.Builder
1074 sb.WriteString("resolve page dependencies: ")
1075 for _, id := range changes {
1076 sb.WriteString(fmt.Sprintf(" %T: %s|", id, id.IdentifierBase()))
1077 }
1078 return sb.String()
1079 }))
1080
1081 var (
1082 resetCounter atomic.Int64
1083 checkedCounter atomic.Int64
1084 )
1085
1086 resetPo := func(po *pageOutput, rebuildContent bool, r identity.FinderResult) {
1087 if rebuildContent && po.pco != nil {
1088 po.pco.Reset() // Will invalidate content cache.
1089 }
1090
1091 po.renderState = 0
1092 if r == identity.FinderFoundOneOfMany || po.f.Name == output.HTTPStatus404HTMLFormat.Name {
1093 // Will force a re-render even in fast render mode.
1094 po.renderOnce = false
1095 }
1096 resetCounter.Add(1)
1097 h.Log.Trace(logg.StringFunc(func() string {
1098 p := po.p
1099 return fmt.Sprintf("%s Resetting page output %q for %q for output %q\n", p.s.resolveDimensionNames(), p.Kind(), p.Path(), po.f.Name)
1100 }))
1101 }
1102
1103 // This can be a relativeley expensive operations, so we do it in parallel.
1104 g := rungroup.Run(ctx, rungroup.Config[*pageState]{
1105 NumWorkers: h.numWorkers,
1106 Handle: func(ctx context.Context, p *pageState) error {
1107 if !p.isRenderedAny() {
1108 // This needs no reset, so no need to check it.
1109 return nil
1110 }
1111
1112 // First check the top level dependency manager.
1113 for _, id := range changes {
1114 checkedCounter.Add(1)
1115 if r := depsFinder.Contains(id, p.dependencyManager, 2); r > identity.FinderFoundOneOfManyRepetition {
1116 for _, po := range p.pageOutputs {
1117 // Note that p.dependencyManager is used when rendering content, so reset that.
1118 resetPo(po, true, r)
1119 }
1120 // Done.
1121 return nil
1122 }
1123 }
1124 // Then do a more fine grained reset for each output format.
1125 OUTPUTS:
1126 for _, po := range p.pageOutputs {
1127 if !po.isRendered() {
1128 continue
1129 }
1130
1131 for _, id := range changes {
1132 checkedCounter.Add(1)
1133 if r := depsFinder.Contains(id, po.dependencyManagerOutput, 50); r > identity.FinderFoundOneOfManyRepetition {
1134 // Note that dependencyManagerOutput is not used when rendering content, so don't reset that.
1135 resetPo(po, false, r)
1136 continue OUTPUTS
1137 }
1138 }
1139 }
1140 return nil
1141 },
1142 })
1143
1144 h.withPage(func(s string, p *pageState) bool {
1145 var needToCheck bool
1146 for _, po := range p.pageOutputs {
1147 if po.isRendered() {
1148 needToCheck = true
1149 break
1150 }
1151 }
1152 if needToCheck {
1153 g.Enqueue(p)
1154 }
1155 return false
1156 })
1157
1158 err := g.Wait()
1159 resetCount := int(resetCounter.Load())
1160 checkedCount := int(checkedCounter.Load())
1161
1162 return checkedCount, resetCount, err
1163 }
1164
1165 func (m *pageMap) CreateSiteTaxonomies(ctx context.Context) (page.TaxonomyList, error) {
1166 taxonomies := make(page.TaxonomyList)
1167
1168 if m.cfg.taxonomyDisabled && m.cfg.taxonomyTermDisabled {
1169 return taxonomies, nil
1170 }
1171
1172 for _, viewName := range m.cfg.taxonomyConfig.views {
1173 key := viewName.pluralTreeKey
1174 taxonomies[viewName.plural] = make(page.Taxonomy)
1175 w := &doctree.NodeShiftTreeWalker[contentNode]{
1176 Tree: m.treePages,
1177 Prefix: paths.AddTrailingSlash(key),
1178 LockType: doctree.LockTypeRead,
1179 Handle: func(s string, n contentNode) (radix.WalkFlag, error) {
1180 p := n.(*pageState)
1181
1182 switch p.Kind() {
1183 case kinds.KindTerm:
1184 if !p.m.shouldList(true) {
1185 return radix.WalkContinue, nil
1186 }
1187 taxonomy := taxonomies[viewName.plural]
1188 if taxonomy == nil {
1189 return radix.WalkStop, fmt.Errorf("missing taxonomy: %s", viewName.plural)
1190 }
1191 if p.m.term == "" {
1192 panic("term is empty")
1193 }
1194 k := strings.ToLower(p.m.term)
1195
1196 err := m.treeTaxonomyEntries.WalkPrefix(
1197 doctree.LockTypeRead,
1198 paths.AddTrailingSlash(s),
1199 func(ss string, wn *weightedContentNode) (bool, error) {
1200 taxonomy[k] = append(taxonomy[k], page.NewWeightedPage(wn.weight, wn.n.(page.Page), wn.term.Page()))
1201 return false, nil
1202 },
1203 )
1204 if err != nil {
1205 return radix.WalkStop, err
1206 }
1207
1208 default:
1209 return radix.WalkContinue, nil
1210 }
1211
1212 return radix.WalkContinue, nil
1213 },
1214 }
1215
1216 if err := w.Walk(ctx); err != nil {
1217 return nil, err
1218 }
1219 }
1220
1221 for _, taxonomy := range taxonomies {
1222 for _, v := range taxonomy {
1223 v.Sort()
1224 }
1225 }
1226
1227 return taxonomies, nil
1228 }
1229
1230 type term struct {
1231 view viewName
1232 term string
1233 }
1234
1235 type viewName struct {
1236 singular string // e.g. "category"
1237 plural string // e.g. "categories"
1238 pluralTreeKey string
1239 }
1240
1241 func (v viewName) IsZero() bool {
1242 return v.singular == ""
1243 }