diff --git a/internal/gui/api.go b/internal/gui/api.go index 576986459..3730a946d 100644 --- a/internal/gui/api.go +++ b/internal/gui/api.go @@ -1074,15 +1074,11 @@ func revalidated(next http.Handler) http.Handler { if name == "" { name = "index.html" } - b, err := fs.ReadFile(staticFS(), name) - if err != nil { + sum, page, ok := staticSum(name, r.URL.Path == "/") + if !ok { next.ServeHTTP(rw, r) return } - if r.URL.Path == "/" { - b = versionedPage(b) - } - sum := sha256.Sum256(b) rw.Header().Set("ETag", `"`+hex.EncodeToString(sum[:12])+`"`) rw.Header().Set("Cache-Control", "no-cache") // a file asked for by the address the page names it by, its @@ -1095,7 +1091,7 @@ func revalidated(next http.Handler) http.Handler { } if r.URL.Path == "/" { rw.Header().Set("Content-Type", "text/html; charset=utf-8") - http.ServeContent(rw, r, "index.html", time.Time{}, bytes.NewReader(b)) + http.ServeContent(rw, r, "index.html", time.Time{}, bytes.NewReader(page)) return } next.ServeHTTP(rw, r) @@ -1109,14 +1105,53 @@ var pageFile = lazyre.New(`(src|href)="([A-Za-z0-9_.-]+(?:/[A-Za-z0-9_.-]+)*\.(? // versionedPage is the page with each of its own scripts and stylesheets // named with its content's hash; one not among the page's files (boot.js, // which the API writes) keeps its name. +// staticSum is the sha256 of a static file, or with root of the page as +// versionedPage names its files, and that page: made once in a build, +// whose files never change (staticFixed). Each load read every file +// whole and hashed it again, the page's scripts twice, ~17 MB of a page +// load with app.js alone over a megabyte (#2278). ok is false for a file +// that can't be read, which isn't kept. +func staticSum(name string, root bool) (sum [32]byte, page []byte, ok bool) { + key := name + if root { + key = "/" + } + if staticFixed { + if v, hit := staticSums.Load(key); hit { + a := v.(staticFile) + return a.sum, a.page, true + } + } + b, err := fs.ReadFile(staticFS(), name) + if err != nil { + return sum, nil, false + } + if root { + b = versionedPage(b) + page = b + } + sum = sha256.Sum256(b) + if staticFixed { + staticSums.Store(key, staticFile{sum, page}) + } + return sum, page, true +} + +// staticSums are staticSum's answers by name ("/" for the page). +var staticSums sync.Map + +type staticFile struct { + sum [32]byte + page []byte +} + func versionedPage(page []byte) []byte { return pageFile.ReplaceAllFunc(page, func(m []byte) []byte { g := pageFile.FindSubmatch(m) - b, err := fs.ReadFile(staticFS(), string(g[2])) - if err != nil { + sum, _, ok := staticSum(string(g[2]), false) + if !ok { return m } - sum := sha256.Sum256(b) return []byte(fmt.Sprintf(`%s="%s?v=%s"`, g[1], g[2], hex.EncodeToString(sum[:6]))) }) } diff --git a/internal/gui/dev_off.go b/internal/gui/dev_off.go index 3bd00a4e2..70148001d 100644 --- a/internal/gui/dev_off.go +++ b/internal/gui/dev_off.go @@ -7,6 +7,9 @@ import ( "net/http" ) +// staticFixed: the UI's files are the binary's, the same for its life. +const staticFixed = true + // The shipped app serves the UI from the binary, in one process. func staticFS() fs.FS { f, _ := fs.Sub(assets, "assets"); return f } func devRoutes(*http.ServeMux) {} diff --git a/internal/gui/dev_on.go b/internal/gui/dev_on.go index d130880a9..3bc8a8898 100644 --- a/internal/gui/dev_on.go +++ b/internal/gui/dev_on.go @@ -41,6 +41,9 @@ func assetsDir() string { func staticFS() fs.FS { return os.DirFS(assetsDir()) } +// staticFixed: the UI's files are read from disk, and change under it. +const staticFixed = false + // stamp is the newest modification time under assets, as a string. func stamp() string { var newest time.Time diff --git a/internal/gui/web_compress_test.go b/internal/gui/web_compress_test.go index bc2815c44..c9308b0e3 100644 --- a/internal/gui/web_compress_test.go +++ b/internal/gui/web_compress_test.go @@ -10,6 +10,7 @@ import ( "net/http" "net/http/httptest" "path/filepath" + "runtime" "strings" "testing" ) @@ -140,3 +141,52 @@ func TestVersionedFilesKept(t *testing.T) { t.Errorf("the page: Cache-Control %q, want no-cache", cc) } } + +// A load asks for the page and each of its files; their ETags and the +// page's names for its files are made once, not by reading and hashing +// every file again (app.js alone is over a megabyte) at each load +// (#2278). +func TestStaticFilesHashedOnce(t *testing.T) { + if !staticFixed { + t.Skip("a dev build reads the files from disk each time") + } + app, err := fs.ReadFile(staticFS(), "app.js") + if err != nil { + t.Fatal(err) + } + h := revalidated(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})) + get := func(path string) *httptest.ResponseRecorder { + rec := httptest.NewRecorder() + h.ServeHTTP(rec, httptest.NewRequest("GET", path, nil)) + return rec + } + first, page := get("/app.js").Header().Get("ETag"), get("/").Body.String() + const loads = 20 + spent := func(load func()) uint64 { + var before, after runtime.MemStats + runtime.GC() + runtime.ReadMemStats(&before) + for range loads { + load() + } + runtime.ReadMemStats(&after) + return after.TotalAlloc - before.TotalAlloc + } + // a read of app.js at each load is loads times its size + if n := spent(func() { + if tag := get("/app.js").Header().Get("ETag"); tag != first { + t.Fatalf("app.js's ETag changed: %s, then %s", first, tag) + } + }); n > uint64(len(app)) { + t.Errorf("%d loads of app.js allocated %d bytes, app.js is %d", loads, n, len(app)) + } + // the page names app.js by its hash, read again at each load before; + // what is left is the page copied out, a few times its size a load + if n := spent(func() { + if got := get("/").Body.String(); got != page { + t.Fatal("the page changed between loads") + } + }); n > uint64(loads*len(page)*6) { + t.Errorf("%d loads of the page allocated %d bytes, the page is %d", loads, n, len(page)) + } +}