Skip to content

Commit 40bbb8c

Browse files
committed
gateway/assets: process each template and ETag hash in parallel
From: ``` init github.com/ipfs/boxo/gateway/assets @26 ms, 18 ms clock, 9887320 bytes, 1496 allocs ``` To: ``` init github.com/ipfs/boxo/gateway/assets @10 ms, 3.3 ms clock, 3368 bytes, 11 allocs ``` This is not optimal but better solutions (like lazy loading) require breaking the API and it's a better job for future someone else.
1 parent 483bc39 commit 40bbb8c

File tree

1 file changed

+30
-24
lines changed

1 file changed

+30
-24
lines changed

gateway/assets/assets.go

Lines changed: 30 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import (
88
"net"
99
"strconv"
1010
"strings"
11+
"sync"
1112

1213
"github.com/cespare/xxhash/v2"
1314
"github.com/ipfs/boxo/path"
@@ -26,8 +27,35 @@ var (
2627
)
2728

2829
func init() {
29-
initAssetsHash()
30-
initTemplates()
30+
tmpls := [...]struct {
31+
result **template.Template
32+
sourceFile string
33+
}{
34+
{&DirectoryTemplate, "directory.html"},
35+
{&DagTemplate, "dag.html"},
36+
{&ErrorTemplate, "error.html"},
37+
}
38+
39+
var wg sync.WaitGroup
40+
wg.Add(len(tmpls))
41+
42+
for _, tmpl := range tmpls {
43+
tmpl := tmpl
44+
go func() {
45+
defer wg.Done()
46+
var err error
47+
*tmpl.result, err = BuildTemplate(assets, tmpl.sourceFile)
48+
if err != nil {
49+
panic(err)
50+
}
51+
}()
52+
}
53+
54+
initAssetsHash() // reuse the init thread instead of blocking on wg.Wait
55+
56+
// @Jorropo: this is still waiting because I was too lazy to break the API of this public package.
57+
// It sounds better if we would use sync.Once and maybe start goroutines in init().
58+
wg.Wait()
3159
}
3260

3361
func initAssetsHash() {
@@ -56,28 +84,6 @@ func initAssetsHash() {
5684
AssetHash = strconv.FormatUint(sum.Sum64(), 32)
5785
}
5886

59-
func initTemplates() {
60-
var err error
61-
62-
// Directory listing template
63-
DirectoryTemplate, err = BuildTemplate(assets, "directory.html")
64-
if err != nil {
65-
panic(err)
66-
}
67-
68-
// DAG Index template
69-
DagTemplate, err = BuildTemplate(assets, "dag.html")
70-
if err != nil {
71-
panic(err)
72-
}
73-
74-
// Error template
75-
ErrorTemplate, err = BuildTemplate(assets, "error.html")
76-
if err != nil {
77-
panic(err)
78-
}
79-
}
80-
8187
type MenuItem struct {
8288
URL string
8389
Title string

0 commit comments

Comments
 (0)