gui: each embedded file is hashed once, not on every load

revalidated read each embedded file again on every request to make its
ETag, and the page "/" read and hashed every file it names to version
their URLs. A release's files never change, so each one's sum (and the
versioned page) is now kept in a sync.Map after its first read. A dev
build (-tags dev) reads from disk and keeps nothing.

Measured: TestStaticFilesHashedOnce, 20 loads each, on mote:
  with the memo   green (app.js under 1x its size, page under 6x its)
  memo off by hand  app.js 26,516,856 B; page 165,916,424 B (~8 MB a
                    page load) - red
Run on mote: go vet ./internal/gui and -tags dev; go test -run
"StaticFilesHashedOnce|VersionedFilesKept|WebCompresses|PageFilesRevalidate|Revalidat"
./internal/gui ok.
Not tried: the full GUI suite (no change to what is served).
This commit is contained in:
yetone
2026-11-13 05:31:22 +08:00
parent a8b0e80f65
commit 5f5307ab6d
4 changed files with 101 additions and 10 deletions
+45 -10
View File
@@ -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])))
})
}
+3
View File
@@ -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) {}
+3
View File
@@ -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
+50
View File
@@ -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))
}
}