Skip to content

Commit 0927cf7

Browse files
committed
tpl/partials: Make sure a cached partial is invoked only once
This commit revises the locking strategy for `partialCached`. We have added a benchmark that may be a little artificial, but it should at least show that we're not losing any performance over this: ```bash name old time/op new time/op delta IncludeCached-10 12.2ms ± 2% 11.3ms ± 1% -7.36% (p=0.029 n=4+4) name old alloc/op new alloc/op delta IncludeCached-10 7.17MB ± 0% 5.09MB ± 0% -29.00% (p=0.029 n=4+4) name old allocs/op new allocs/op delta IncludeCached-10 128k ± 1% 70k ± 0% -45.42% (p=0.029 n=4+4) ``` This commit also revises the template metrics hints logic a little, and add a test for it, which output is currently this: ```bash cumulative average maximum cache percent cached total duration duration duration potential cached count count template ---------- -------- -------- --------- ------- ------ ----- -------- 163.334µs 163.334µs 163.334µs 0 0 0 1 index.html 23.749µs 5.937µs 19.916µs 25 50 2 4 partials/dynamic1.html 9.625µs 4.812µs 6.75µs 100 50 1 2 partials/static1.html 7.625µs 7.625µs 7.625µs 100 0 0 1 partials/static2.html ``` Some notes: * The duration now includes the cached invocations (which should be very short) * A cached template gets executed once before it gets cached, so the "percent cached" will never be 100. Fixes #4086 Fixes #9506
1 parent 26a5e89 commit 0927cf7

File tree

6 files changed

+171
-14
lines changed

6 files changed

+171
-14
lines changed

htesting/hqt/checkers.go

+4-3
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ type stringChecker struct {
6363
argNames
6464
}
6565

66-
// Check implements Checker.Check by checking that got and args[0] represents the same normalized text (whitespace etc. trimmed).
66+
// Check implements Checker.Check by checking that got and args[0] represents the same normalized text (whitespace etc. removed).
6767
func (c *stringChecker) Check(got interface{}, args []interface{}, note func(key string, value interface{})) (err error) {
6868
s1, s2 := cast.ToString(got), cast.ToString(args[0])
6969

@@ -81,11 +81,12 @@ func (c *stringChecker) Check(got interface{}, args []interface{}, note func(key
8181
}
8282

8383
func normalizeString(s string) string {
84+
s = strings.ReplaceAll(s, "\r\n", "\n")
85+
8486
lines := strings.Split(strings.TrimSpace(s), "\n")
8587
for i, line := range lines {
86-
lines[i] = strings.TrimSpace(line)
88+
lines[i] = strings.Join(strings.Fields(strings.TrimSpace(line)), "")
8789
}
88-
8990
return strings.Join(lines, "\n")
9091
}
9192

tpl/math/math.go

+12
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ package math
1717
import (
1818
"errors"
1919
"math"
20+
"sync/atomic"
2021

2122
_math "github.com/gohugoio/hugo/common/math"
2223

@@ -162,3 +163,14 @@ func (ns *Namespace) Sqrt(a interface{}) (float64, error) {
162163
func (ns *Namespace) Sub(a, b interface{}) (interface{}, error) {
163164
return _math.DoArithmetic(a, b, '-')
164165
}
166+
167+
var counter uint64
168+
169+
// Counter increments and returns a global counter.
170+
// This was originally added to be used in tests where now.UnixNano did not
171+
// have the needed precision (especially on Windows).
172+
// Note that given the parallel nature of Hugo, you cannot use this to get sequences of numbers,
173+
// and the counter will reset on new builds.
174+
func (ns *Namespace) Counter() uint64 {
175+
return atomic.AddUint64(&counter, uint64(1))
176+
}

tpl/partials/init.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -18,14 +18,14 @@ import (
1818
"github.com/gohugoio/hugo/tpl/internal"
1919
)
2020

21-
const name = "partials"
21+
const namespaceName = "partials"
2222

2323
func init() {
2424
f := func(d *deps.Deps) *internal.TemplateFuncsNamespace {
2525
ctx := New(d)
2626

2727
ns := &internal.TemplateFuncsNamespace{
28-
Name: name,
28+
Name: namespaceName,
2929
Context: func(args ...interface{}) (interface{}, error) { return ctx, nil },
3030
}
3131

tpl/partials/init_test.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ func TestInit(t *testing.T) {
3333
BuildStartListeners: &deps.Listeners{},
3434
Log: loggers.NewErrorLogger(),
3535
})
36-
if ns.Name == name {
36+
if ns.Name == namespaceName {
3737
found = true
3838
break
3939
}

tpl/partials/integration_test.go

+131
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,14 @@
1414
package partials_test
1515

1616
import (
17+
"bytes"
18+
"fmt"
19+
"regexp"
20+
"sort"
21+
"strings"
1722
"testing"
1823

24+
"github.com/gohugoio/hugo/htesting/hqt"
1925
"github.com/gohugoio/hugo/hugolib"
2026
)
2127

@@ -68,3 +74,128 @@ partialCached: foo
6874
partialCached: foo
6975
`)
7076
}
77+
78+
func TestIncludeCacheHints(t *testing.T) {
79+
t.Parallel()
80+
81+
files := `
82+
-- config.toml --
83+
baseURL = 'http://example.com/'
84+
templateMetrics=true
85+
templateMetricsHints=true
86+
disableKinds = ["page", "section", "taxonomy", "term", "sitemap"]
87+
[outputs]
88+
home = ["HTML"]
89+
-- layouts/index.html --
90+
{{ partials.IncludeCached "static1.html" . }}
91+
{{ partials.IncludeCached "static1.html" . }}
92+
{{ partials.Include "static2.html" . }}
93+
94+
D1I: {{ partials.Include "dynamic1.html" . }}
95+
D1C: {{ partials.IncludeCached "dynamic1.html" . }}
96+
D1C: {{ partials.IncludeCached "dynamic1.html" . }}
97+
D1C: {{ partials.IncludeCached "dynamic1.html" . }}
98+
H1I: {{ partials.Include "halfdynamic1.html" . }}
99+
H1C: {{ partials.IncludeCached "halfdynamic1.html" . }}
100+
H1C: {{ partials.IncludeCached "halfdynamic1.html" . }}
101+
102+
-- layouts/partials/static1.html --
103+
P1
104+
-- layouts/partials/static2.html --
105+
P2
106+
-- layouts/partials/dynamic1.html --
107+
{{ math.Counter }}
108+
-- layouts/partials/halfdynamic1.html --
109+
D1
110+
{{ math.Counter }}
111+
112+
113+
`
114+
115+
b := hugolib.NewIntegrationTestBuilder(
116+
hugolib.IntegrationTestConfig{
117+
T: t,
118+
TxtarString: files,
119+
},
120+
).Build()
121+
122+
// fmt.Println(b.FileContent("public/index.html"))
123+
124+
var buf bytes.Buffer
125+
b.H.Metrics.WriteMetrics(&buf)
126+
127+
got := buf.String()
128+
129+
// Get rid of all the durations, they are never the same.
130+
durationRe := regexp.MustCompile(`\b[\.\d]*(ms|µs|s)\b`)
131+
132+
normalize := func(s string) string {
133+
s = durationRe.ReplaceAllString(s, "")
134+
linesIn := strings.Split(s, "\n")[3:]
135+
var lines []string
136+
for _, l := range linesIn {
137+
l = strings.TrimSpace(l)
138+
if l == "" {
139+
continue
140+
}
141+
lines = append(lines, l)
142+
}
143+
144+
sort.Strings(lines)
145+
146+
return strings.Join(lines, "\n")
147+
}
148+
149+
got = normalize(got)
150+
151+
expect := `
152+
0 0 0 1 index.html
153+
100 0 0 1 partials/static2.html
154+
100 50 1 2 partials/static1.html
155+
25 50 2 4 partials/dynamic1.html
156+
66 33 1 3 partials/halfdynamic1.html
157+
`
158+
159+
b.Assert(got, hqt.IsSameString, expect)
160+
}
161+
162+
// gobench --package ./tpl/partials
163+
func BenchmarkIncludeCached(b *testing.B) {
164+
files := `
165+
-- config.toml --
166+
baseURL = 'http://example.com/'
167+
-- layouts/index.html --
168+
-- layouts/_default/single.html --
169+
{{ partialCached "heavy.html" "foo" }}
170+
-- layouts/partials/heavy.html --
171+
{{ $result := slice }}
172+
{{ range site.RegularPages }}
173+
{{ $result = $result | append (dict "title" .Title "link" .RelPermalink "readingTime" .ReadingTime) }}
174+
{{ end }}
175+
{{ range $result }}
176+
* {{ .title }} {{ .link }} {{ .readingTime }}
177+
{{ end }}
178+
179+
180+
`
181+
182+
for i := 1; i < 100; i++ {
183+
files += fmt.Sprintf("\n-- content/p%d.md --\n---\ntitle: page\n---\n"+strings.Repeat("FOO ", i), i)
184+
}
185+
186+
cfg := hugolib.IntegrationTestConfig{
187+
T: b,
188+
TxtarString: files,
189+
}
190+
builders := make([]*hugolib.IntegrationTestBuilder, b.N)
191+
192+
for i, _ := range builders {
193+
builders[i] = hugolib.NewIntegrationTestBuilder(cfg)
194+
}
195+
196+
b.ResetTimer()
197+
198+
for i := 0; i < b.N; i++ {
199+
builders[i].Build()
200+
}
201+
}

tpl/partials/partials.go

+21-8
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ import (
2424
"reflect"
2525
"strings"
2626
"sync"
27+
"time"
2728

2829
texttemplate "github.com/gohugoio/hugo/tpl/internal/go_templates/texttemplate"
2930

@@ -44,6 +45,13 @@ type partialCacheKey struct {
4445
variant interface{}
4546
}
4647

48+
func (k partialCacheKey) templateName() string {
49+
if !strings.HasPrefix(k.name, "partials/") {
50+
return "partials/" + k.name
51+
}
52+
return k.name
53+
}
54+
4755
// partialCache represents a cache of partials protected by a mutex.
4856
type partialCache struct {
4957
sync.RWMutex
@@ -211,6 +219,7 @@ func createKey(name string, variants ...interface{}) (partialCacheKey, error) {
211219
var errUnHashable = errors.New("unhashable")
212220

213221
func (ns *Namespace) getOrCreate(key partialCacheKey, context interface{}) (result interface{}, err error) {
222+
start := time.Now()
214223
defer func() {
215224
if r := recover(); r != nil {
216225
err = r.(error)
@@ -226,24 +235,28 @@ func (ns *Namespace) getOrCreate(key partialCacheKey, context interface{}) (resu
226235
ns.cachedPartials.RUnlock()
227236

228237
if ok {
238+
if ns.deps.Metrics != nil {
239+
ns.deps.Metrics.TrackValue(key.templateName(), p, true)
240+
// The templates that gets executed is measued in Execute.
241+
// We need to track the time spent in the cache to
242+
// get the totals correct.
243+
ns.deps.Metrics.MeasureSince(key.templateName(), start)
244+
245+
}
229246
return p, nil
230247
}
231248

249+
ns.cachedPartials.Lock()
250+
defer ns.cachedPartials.Unlock()
251+
232252
var name string
233253
name, p, err = ns.include(key.name, context)
234254
if err != nil {
235255
return nil, err
236256
}
237257

238258
if ns.deps.Metrics != nil {
239-
ns.deps.Metrics.TrackValue(name, p, true)
240-
}
241-
242-
ns.cachedPartials.Lock()
243-
defer ns.cachedPartials.Unlock()
244-
// Double-check.
245-
if p2, ok := ns.cachedPartials.p[key]; ok {
246-
return p2, nil
259+
ns.deps.Metrics.TrackValue(name, p, false)
247260
}
248261
ns.cachedPartials.p[key] = p
249262

0 commit comments

Comments
 (0)