From 2fdb4a9faae80cb5811a6858210ee740a3177c01 Mon Sep 17 00:00:00 2001 From: Jorropo Date: Sat, 30 Dec 2023 05:26:39 +0100 Subject: [PATCH] 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. --- gateway/assets/assets.go | 54 ++++++++++++++++++++++------------------ 1 file changed, 30 insertions(+), 24 deletions(-) diff --git a/gateway/assets/assets.go b/gateway/assets/assets.go index 4a629c366..4d9676784 100644 --- a/gateway/assets/assets.go +++ b/gateway/assets/assets.go @@ -8,6 +8,7 @@ import ( "net" "strconv" "strings" + "sync" "github.com/cespare/xxhash/v2" "github.com/ipfs/boxo/path" @@ -26,8 +27,35 @@ var ( ) func init() { - initAssetsHash() - initTemplates() + tmpls := [...]struct { + result **template.Template + sourceFile string + }{ + {&DirectoryTemplate, "directory.html"}, + {&DagTemplate, "dag.html"}, + {&ErrorTemplate, "error.html"}, + } + + var wg sync.WaitGroup + wg.Add(len(tmpls)) + + for _, tmpl := range tmpls { + tmpl := tmpl + go func() { + defer wg.Done() + var err error + *tmpl.result, err = BuildTemplate(assets, tmpl.sourceFile) + if err != nil { + panic(err) + } + }() + } + + initAssetsHash() // reuse the init thread instead of blocking on wg.Wait + + // @Jorropo: this is still waiting because I was too lazy to break the API of this public package. + // It sounds better if we would use sync.Once and maybe start goroutines in init(). + wg.Wait() } func initAssetsHash() { @@ -56,28 +84,6 @@ func initAssetsHash() { AssetHash = strconv.FormatUint(sum.Sum64(), 32) } -func initTemplates() { - var err error - - // Directory listing template - DirectoryTemplate, err = BuildTemplate(assets, "directory.html") - if err != nil { - panic(err) - } - - // DAG Index template - DagTemplate, err = BuildTemplate(assets, "dag.html") - if err != nil { - panic(err) - } - - // Error template - ErrorTemplate, err = BuildTemplate(assets, "error.html") - if err != nil { - panic(err) - } -} - type MenuItem struct { URL string Title string