From f2bd6e2c281e51c9b076138758fb7711c72d3c22 Mon Sep 17 00:00:00 2001 From: matteo Date: Sat, 18 Apr 2026 09:00:47 +0800 Subject: [PATCH 1/8] file info --- internal/biz/batch.go | 20 +++++++--- internal/biz/fetch.go | 10 +++-- internal/biz/repo.go | 8 +++- internal/biz/usecase.go | 2 +- internal/data/file.go | 18 +++++---- internal/data/repo.go | 2 +- internal/service/handler.go | 23 ++++++----- web/template/index.html | 79 ++++++++++++++++++++++++++++--------- web/template/list.html | 76 +++++++++++++++++++++++++++-------- 9 files changed, 174 insertions(+), 64 deletions(-) diff --git a/internal/biz/batch.go b/internal/biz/batch.go index ae00d90..eb79e9f 100644 --- a/internal/biz/batch.go +++ b/internal/biz/batch.go @@ -132,25 +132,33 @@ func (b *batch) Start(ctx context.Context, fn saveFile) (res []Cse, err error) { return } -// Cse combines a string result and an error. +// Cse combines a string result, file size, and an error. type Cse struct { - S string - E error + S string + Size int64 + E error +} + +// FileResult holds path and size for a successfully fetched file. +type FileResult struct { + Path string `json:"path"` + Size int64 `json:"size"` } func (b *batch) run(ctx context.Context, task urlTask, ch chan Cse, wg *sync.WaitGroup, fn saveFile) { defer wg.Done() data, contentType, err := curlGet(ctx, task.url, task.timeout) if err != nil { - ch <- Cse{"", err} + ch <- Cse{"", 0, err} return } + size := int64(len(data)) relativePath, err := fn(task.url, contentType, data) if err != nil { - ch <- Cse{"", err} + ch <- Cse{"", 0, err} return } - ch <- Cse{relativePath, nil} + ch <- Cse{relativePath, size, nil} } func (uc *Usecase) DealRun(ctx context.Context, p BatchParams) (res []Cse, err error) { diff --git a/internal/biz/fetch.go b/internal/biz/fetch.go index 440c402..3b03aa3 100644 --- a/internal/biz/fetch.go +++ b/internal/biz/fetch.go @@ -12,12 +12,12 @@ import ( const curlTimeout = 300 // 5 minutes -func (uc *Usecase) DealRun1(ctx context.Context, uri string) (relativePath string, err error) { +func (uc *Usecase) DealRun1(ctx context.Context, uri string) (relativePath string, size int64, err error) { uri, err = url.QueryUnescape(uri) if err != nil { return } - relativePath, err = uc.curlOne(ctx, uri) + relativePath, size, err = uc.curlOne(ctx, uri) return } func validateURL(uri string, denyPrivateIP bool) error { @@ -38,7 +38,7 @@ func validateURL(uri string, denyPrivateIP bool) error { return nil } -func (uc *Usecase) curlOne(ctx context.Context, uri string) (relativePath string, err error) { +func (uc *Usecase) curlOne(ctx context.Context, uri string) (relativePath string, size int64, err error) { if err = validateURL(uri, uc.denyPrivateIP); err != nil { return } @@ -46,7 +46,9 @@ func (uc *Usecase) curlOne(ctx context.Context, uri string) (relativePath string if err != nil { return } - return uc.repo.CreateFile(uri, contentType, data) + size = int64(len(data)) + relativePath, err = uc.repo.CreateFile(uri, contentType, data) + return } func curlGet(ctx context.Context, uri string, timeout int) (data []byte, contentType string, err error) { diff --git a/internal/biz/repo.go b/internal/biz/repo.go index ec31d91..3b080a0 100644 --- a/internal/biz/repo.go +++ b/internal/biz/repo.go @@ -2,10 +2,16 @@ package biz import "github.com/go-kratos/kratos/v2/log" +// FileInfo holds name and size for a file in the storage directory. +type FileInfo struct { + Name string + Size int64 +} + type Repo interface { GetPortByDir(relPath string) (port int, err error) GetAbsDir(relPath string) string - GetFileList(date string) (list, files []string, err error) + GetFileList(date string) (list []string, files []FileInfo, err error) GetFileType(dir string) string CreateFile(url string, contentType string, data []byte) (relativePath string, err error) CreateFileByUpload(fileName string, data []byte) (relativePath string, err error) diff --git a/internal/biz/usecase.go b/internal/biz/usecase.go index ad6a96b..810aced 100644 --- a/internal/biz/usecase.go +++ b/internal/biz/usecase.go @@ -25,7 +25,7 @@ func (uc *Usecase) GetAbsDir(s string) string { return uc.repo.GetAbsDir(s) } -func (uc *Usecase) GetFileList(date string) (list, files []string, err error) { +func (uc *Usecase) GetFileList(date string) (list []string, files []FileInfo, err error) { return uc.repo.GetFileList(date) } func (uc *Usecase) GetFileType(dir string) string { diff --git a/internal/data/file.go b/internal/data/file.go index dd01364..98c4e3c 100644 --- a/internal/data/file.go +++ b/internal/data/file.go @@ -2,12 +2,14 @@ package data import ( "fmt" - "github.com/go-kratos/kratos/v2/log" - "github.com/matteo-gz/prof/pkg/filex" - "github.com/matteo-gz/prof/pkg/pproftype" "os" "path" "strings" + + "github.com/go-kratos/kratos/v2/log" + "github.com/matteo-gz/prof/internal/biz" + "github.com/matteo-gz/prof/pkg/filex" + "github.com/matteo-gz/prof/pkg/pproftype" ) type file struct { @@ -49,7 +51,7 @@ func getFileType(dir string) (fileType string) { return pproftype.ExtUnknown } } -func (f *file) getFileList(date string) (list, files []string, err error) { +func (f *file) getFileList(date string) (list []string, files []biz.FileInfo, err error) { final := f.getAbsDir(date) f1, err := os.OpenFile(final, os.O_RDONLY, os.ModeDir) if err != nil { @@ -60,11 +62,11 @@ func (f *file) getFileList(date string) (list, files []string, err error) { if err != nil { return } - for _, fileInfo := range info { - if fileInfo.IsDir() { - list = append(list, fileInfo.Name()) + for _, fi := range info { + if fi.IsDir() { + list = append(list, fi.Name()) } else { - files = append(files, fileInfo.Name()) + files = append(files, biz.FileInfo{Name: fi.Name(), Size: fi.Size()}) } } return list, files, nil diff --git a/internal/data/repo.go b/internal/data/repo.go index f4b5f79..09cea4b 100644 --- a/internal/data/repo.go +++ b/internal/data/repo.go @@ -30,7 +30,7 @@ func (rp *repo) GetAbsDir(relPath string) string { return rp.data.file.getAbsDir(relPath) } -func (rp *repo) GetFileList(date string) (list, files []string, err error) { +func (rp *repo) GetFileList(date string) (list []string, files []biz.FileInfo, err error) { return rp.data.file.getFileList(date) } func (rp *repo) GetFileType(dir string) string { diff --git a/internal/service/handler.go b/internal/service/handler.go index 095e97a..f2da223 100644 --- a/internal/service/handler.go +++ b/internal/service/handler.go @@ -199,30 +199,35 @@ func (s *Service) Run(c *gin.Context) { return } var res2 []string + var files []biz.FileResult for i := range res { if res[i].E != nil { res2 = append(res2, res[i].E.Error()) } else { res2 = append(res2, res[i].S) + files = append(files, biz.FileResult{Path: res[i].S, Size: res[i].Size}) } } c.JSON(200, gin.H{ - "id": time.Now().UnixMilli(), - "res": res2, + "id": time.Now().UnixMilli(), + "res": res2, + "files": files, }) } func (s *Service) Run1(c *gin.Context) { uri := c.PostForm("url") - relativePath, err := s.uc.DealRun1(c.Request.Context(), uri) - var res string + relativePath, size, err := s.uc.DealRun1(c.Request.Context(), uri) if err != nil { - res = err.Error() - } else { - res = relativePath + c.JSON(200, gin.H{ + "id": time.Now().UnixMilli(), + "res": []string{err.Error()}, + }) + return } c.JSON(200, gin.H{ - "id": time.Now().UnixMilli(), - "res": []string{res}, + "id": time.Now().UnixMilli(), + "res": []string{relativePath}, + "files": []biz.FileResult{{Path: relativePath, Size: size}}, }) } diff --git a/web/template/index.html b/web/template/index.html index 7ef7101..016b0b3 100644 --- a/web/template/index.html +++ b/web/template/index.html @@ -181,37 +181,80 @@ var locks = {}; var STORAGE_KEY = "prof:history"; - function fileBadge(path) { + function formatSize(bytes) { + if (!bytes || bytes <= 0) return ""; + if (bytes < 1024) return bytes + " B"; + if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + " KB"; + return (bytes / (1024 * 1024)).toFixed(1) + " MB"; + } + + function fileBadge(filePath) { var sp = document.createElement("span"); sp.className = "badge me-1"; - if (path.endsWith(".trace")) { + var name = filePath.split("/").pop(); + var base = name.replace(/\.[^.]+$/, ""); + if (filePath.endsWith(".trace")) { sp.className += " bg-info text-dark"; - sp.textContent = "Trace Viewer"; - } else if (path.endsWith(".pprof")) { - sp.className += " bg-primary"; - sp.textContent = "pprof"; - } else if (path.endsWith(".txt")) { - sp.className += " bg-secondary"; - sp.textContent = "text"; + sp.textContent = "Trace"; + } else if (filePath.endsWith(".pprof")) { + if (base === "profile") { + sp.className += " bg-danger"; + sp.textContent = "CPU Profile"; + } else if (base === "goroutine") { + sp.className += " bg-warning text-dark"; + sp.textContent = "Goroutine"; + } else if (base === "heap") { + sp.className += " bg-success"; + sp.textContent = "Heap"; + } else if (base === "allocs") { + sp.className += " bg-success"; + sp.textContent = "Allocs"; + } else if (base === "block") { + sp.className += " bg-secondary"; + sp.textContent = "Block"; + } else if (base === "mutex") { + sp.className += " bg-secondary"; + sp.textContent = "Mutex"; + } else if (base === "threadcreate") { + sp.className += " bg-secondary"; + sp.textContent = "Thread"; + } else { + sp.className += " bg-primary"; + sp.textContent = "pprof"; + } + } else if (filePath.endsWith(".txt")) { + sp.className += " bg-light text-dark border"; + sp.textContent = "Meta"; } else { return null; } return sp; } - function buildResultList(paths) { + function buildResultList(paths, files) { var ul = document.createElement("ul"); ul.className = "list-group list-group-flush mt-2"; - for (var i = 0; i < paths.length; i++) { + var useFiles = files && files.length > 0; + var count = useFiles ? files.length : paths.length; + for (var i = 0; i < count; i++) { + var filePath = useFiles ? files[i].path : paths[i]; + var fileSize = useFiles ? files[i].size : 0; var li = document.createElement("li"); - li.className = "list-group-item px-0 py-1"; - var badge = fileBadge(paths[i]); + li.className = "list-group-item px-0 py-1 d-flex align-items-center"; + var badge = fileBadge(filePath); if (badge) li.appendChild(badge); var a = document.createElement("a"); a.target = "_blank"; - a.href = "/file?dir=/" + encodeURIComponent(paths[i]); - a.textContent = paths[i]; + a.href = "/file?dir=/" + encodeURIComponent(filePath); + a.textContent = filePath; li.appendChild(a); + var sz = formatSize(fileSize); + if (sz) { + var s = document.createElement("span"); + s.className = "text-muted small ms-auto"; + s.textContent = sz; + li.appendChild(s); + } ul.appendChild(li); } return ul; @@ -272,7 +315,7 @@ locks[lockKey] = false; setButtonLoading(btn, false); resultEl.textContent = ""; - resultEl.appendChild(buildResultList(data.res)); + resultEl.appendChild(buildResultList(data.res, data.files)); store(data.id, data.res, u, actLabel); document.querySelector('input[name="' + inputName + '"]').value = ""; }) @@ -313,7 +356,7 @@ locks["upload"] = false; setButtonLoading(btn, false); resultUpload.textContent = ""; - resultUpload.appendChild(buildResultList(data.res)); + resultUpload.appendChild(buildResultList(data.res, data.files)); store(data.id, data.res, ff.name, "upload"); document.querySelector('input[name="file"]').value = ""; }) @@ -498,7 +541,7 @@ locks["run"] = false; setButtonLoading(btn, false); resultBatch.textContent = ""; - resultBatch.appendChild(buildResultList(data.res)); + resultBatch.appendChild(buildResultList(data.res, data.files)); store(data.id, data.res, u, "curl batch"); document.querySelector('input[name="url"]').value = ""; }) diff --git a/web/template/list.html b/web/template/list.html index 7c24ecd..ceba303 100644 --- a/web/template/list.html +++ b/web/template/list.html @@ -52,9 +52,10 @@
Files
@@ -63,6 +64,55 @@ From a8595d4321c170e4910f1590b7ba174f66fd335e Mon Sep 17 00:00:00 2001 From: matteo Date: Sun, 19 Apr 2026 00:16:28 +0800 Subject: [PATCH 2/8] diff --- internal/biz/proxy.go | 48 ++++++++++ internal/biz/repo.go | 9 ++ internal/biz/usecase.go | 3 + internal/data/data.go | 3 +- internal/data/file.go | 2 + internal/data/proxy.go | 2 + internal/data/repo.go | 32 +++++++ internal/data/task.go | 24 ++++- internal/server/router.go | 1 + internal/service/handler.go | 48 +++++++++- internal/service/service.go | 7 +- pkg/tool/pprof.go | 10 ++- pkg/tool/tool.go | 2 + web/template/list.html | 173 ++++++++++++++++++++++++++++++++++-- 14 files changed, 351 insertions(+), 13 deletions(-) diff --git a/internal/biz/proxy.go b/internal/biz/proxy.go index 7fca843..ecae329 100644 --- a/internal/biz/proxy.go +++ b/internal/biz/proxy.go @@ -2,6 +2,7 @@ package biz import ( "bytes" + "encoding/base64" "fmt" "io" "net/http" @@ -27,6 +28,7 @@ type replaceBody func(body string, currPath string) string type Uri struct { Path string Dir string + Base string Query string Route string ProxyBasePath string @@ -71,3 +73,49 @@ func (uc *Usecase) Proxy(u Uri, rw http.ResponseWriter, req *http.Request) (err proxy.ServeHTTP(rw, req) return nil } + +func (uc *Usecase) ProxyDiff(u Uri, rw http.ResponseWriter, req *http.Request) (err error) { + baseBytes, err := base64.StdEncoding.DecodeString(u.Base) + if err != nil { + return + } + compareBytes, err := base64.StdEncoding.DecodeString(u.Dir) + if err != nil { + return + } + usePort, err := uc.repo.GetPortByDiff(string(baseBytes), string(compareBytes)) + if err != nil { + return + } + currPath := fmt.Sprintf(u.Route, u.Base, u.Dir) + path := strings.Replace(u.Path, currPath, "", 1) + urlX := fmt.Sprintf("http://127.0.0.1:%d%s%s?%s", usePort, u.ProxyBasePath, path, u.Query) + uc.log.Debugf("call:%s", urlX) + urlT, err := url.Parse(urlX) + if err != nil { + return + } + director := func(req *http.Request) { + req.URL = urlT + req.Host = urlT.Host + } + proxy := &httputil.ReverseProxy{Director: director} + proxy.ModifyResponse = func(res *http.Response) error { + if res.StatusCode == 200 { + oldPayload, err := io.ReadAll(res.Body) + if err != nil { + return err + } + newPayLoadStr := string(oldPayload) + newPayLoadStr = u.ReBody(newPayLoadStr, currPath) + newPayLoad := []byte(newPayLoadStr) + res.Body = io.NopCloser(bytes.NewBuffer(newPayLoad)) + res.ContentLength = int64(len(newPayLoad)) + res.Header.Set("Content-Length", fmt.Sprint(len(newPayLoad))) + return nil + } + return nil + } + proxy.ServeHTTP(rw, req) + return nil +} diff --git a/internal/biz/repo.go b/internal/biz/repo.go index 3b080a0..da5cf8a 100644 --- a/internal/biz/repo.go +++ b/internal/biz/repo.go @@ -8,10 +8,19 @@ type FileInfo struct { Size int64 } +// BatchGroup holds files from one collection batch under a date directory. +type BatchGroup struct { + Label string // e.g. "23_39_42" + Dir string // relative path, e.g. "/20260415/23_39_42" + Files []FileInfo +} + type Repo interface { GetPortByDir(relPath string) (port int, err error) + GetPortByDiff(baseFile, compareFile string) (port int, err error) GetAbsDir(relPath string) string GetFileList(date string) (list []string, files []FileInfo, err error) + GetBatchGroups(date string) ([]BatchGroup, error) GetFileType(dir string) string CreateFile(url string, contentType string, data []byte) (relativePath string, err error) CreateFileByUpload(fileName string, data []byte) (relativePath string, err error) diff --git a/internal/biz/usecase.go b/internal/biz/usecase.go index 810aced..bf52fa0 100644 --- a/internal/biz/usecase.go +++ b/internal/biz/usecase.go @@ -28,6 +28,9 @@ func (uc *Usecase) GetAbsDir(s string) string { func (uc *Usecase) GetFileList(date string) (list []string, files []FileInfo, err error) { return uc.repo.GetFileList(date) } +func (uc *Usecase) GetBatchGroups(date string) ([]BatchGroup, error) { + return uc.repo.GetBatchGroups(date) +} func (uc *Usecase) GetFileType(dir string) string { return uc.repo.GetFileType(dir) } diff --git a/internal/data/data.go b/internal/data/data.go index 1e183a8..3a8ac36 100644 --- a/internal/data/data.go +++ b/internal/data/data.go @@ -48,9 +48,10 @@ func newTask(logger log.Logger) *task { go t.Timer() return t } -func newProxy(dir string, l *log.Helper) *Proxy { +func newProxy(dir string, baseFile string, l *log.Helper) *Proxy { return &Proxy{ dir: dir, + baseFile: baseFile, fileType: getFileType(dir), lifeTime: proxyLifetime, log: l, diff --git a/internal/data/file.go b/internal/data/file.go index 98c4e3c..7662763 100644 --- a/internal/data/file.go +++ b/internal/data/file.go @@ -4,6 +4,7 @@ import ( "fmt" "os" "path" + "sort" "strings" "github.com/go-kratos/kratos/v2/log" @@ -69,5 +70,6 @@ func (f *file) getFileList(date string) (list []string, files []biz.FileInfo, er files = append(files, biz.FileInfo{Name: fi.Name(), Size: fi.Size()}) } } + sort.Sort(sort.Reverse(sort.StringSlice(list))) return list, files, nil } diff --git a/internal/data/proxy.go b/internal/data/proxy.go index aa26dfd..4d67826 100644 --- a/internal/data/proxy.go +++ b/internal/data/proxy.go @@ -63,6 +63,7 @@ type Proxy struct { useTime int64 Cmd *exec.Cmd dir string + baseFile string lifeTime int64 fileType string log *log.Helper @@ -120,6 +121,7 @@ func (p *Proxy) start(port int) (err error) { tools := tool.NewTool(p.fileType) tools.Arg().SetPort(port) tools.Arg().SetFile(p.dir) + tools.Arg().SetBaseFile(p.baseFile) cmdStr := tools.Command() p.log.Debug(cmdStr) p.Cmd = process.Shell(cmdStr) diff --git a/internal/data/repo.go b/internal/data/repo.go index 09cea4b..e59db79 100644 --- a/internal/data/repo.go +++ b/internal/data/repo.go @@ -26,6 +26,38 @@ func (rp *repo) GetPortByDir(relPath string) (port int, err error) { } return rp.data.task.getPortByDir(dir) } + +func (rp *repo) GetBatchGroups(date string) (groups []biz.BatchGroup, err error) { + dirs, _, err := rp.GetFileList(date) + if err != nil { + return + } + for _, d := range dirs { + subDir := date + "/" + d + _, subFiles, err2 := rp.GetFileList(subDir) + if err2 != nil || len(subFiles) == 0 { + continue + } + groups = append(groups, biz.BatchGroup{ + Label: d, + Dir: subDir, + Files: subFiles, + }) + } + return +} + +func (rp *repo) GetPortByDiff(baseFile, compareFile string) (port int, err error) { + base := rp.data.file.getAbsDir(baseFile) + compare := rp.data.file.getAbsDir(compareFile) + if !filex.IsFileExist(base) { + return 0, errors.New("base file not exist") + } + if !filex.IsFileExist(compare) { + return 0, errors.New("compare file not exist") + } + return rp.data.task.getPortByDiff(base, compare) +} func (rp *repo) GetAbsDir(relPath string) string { return rp.data.file.getAbsDir(relPath) } diff --git a/internal/data/task.go b/internal/data/task.go index ed56706..1072109 100644 --- a/internal/data/task.go +++ b/internal/data/task.go @@ -66,7 +66,7 @@ func (t *task) GetProxy(dir string) (p *Proxy) { t.listLock.Lock() p, ok := t.list[index] if !ok { - p = newProxy(filepath.Join(filepath.Split(dir)), t.log) + p = newProxy(filepath.Join(filepath.Split(dir)), "", t.log) t.list[index] = p } t.listLock.Unlock() @@ -88,3 +88,25 @@ func (t *task) getPortByDir(dir string) (port int, err error) { port, err = p.GetCanUsePort() return } + +func (t *task) getDiffIndex(base, compare string) string { + return base + "::" + compare +} + +func (t *task) GetDiffProxy(base, compare string) *Proxy { + index := t.getDiffIndex(base, compare) + t.listLock.Lock() + p, ok := t.list[index] + if !ok { + p = newProxy(compare, base, t.log) + t.list[index] = p + } + t.listLock.Unlock() + p.UpdateUseTime() + return p +} + +func (t *task) getPortByDiff(base, compare string) (port int, err error) { + p := t.GetDiffProxy(base, compare) + return p.GetCanUsePort() +} diff --git a/internal/server/router.go b/internal/server/router.go index b80cbaf..5ecf21b 100644 --- a/internal/server/router.go +++ b/internal/server/router.go @@ -48,6 +48,7 @@ func (h *HTTPServerX) router() (r *gin.Engine, err error) { r.GET("/file", h.srv.File) r.GET(service.RoutePprofPre+"/:dir/*any", h.srv.PprofProxy) r.GET(service.RouteTracePre+"/:dir/*any", h.srv.TraceProxy) + r.GET(service.RoutePprofDiffPre+"/:base/:dir/*any", h.srv.PprofDiffProxy) r.GET("/person/curl", h.srv.PersonCurl) r.GET("/bootstrap.min.css", h.srv.Css) r.POST("/opt/upload", h.srv.Upload) diff --git a/internal/service/handler.go b/internal/service/handler.go index f2da223..21be364 100644 --- a/internal/service/handler.go +++ b/internal/service/handler.go @@ -17,10 +17,12 @@ import ( ) const ( - RoutePprofPre = "/pprof" - RouteTracePre = "/trace" - RouteTrace = RouteTracePre + "/%s/" - RoutePprof = RoutePprofPre + "/%s/" + RoutePprofPre = "/pprof" + RouteTracePre = "/trace" + RoutePprofDiffPre = "/pprof-diff" + RouteTrace = RouteTracePre + "/%s/" + RoutePprof = RoutePprofPre + "/%s/" + RoutePprofDiff = RoutePprofDiffPre + "/%s/%s/" ) func (s *Service) Index(c *gin.Context) { @@ -58,6 +60,22 @@ func (s *Service) PersonCurl(c *gin.Context) { c.String(http.StatusOK, buf.String()) } +func isDateDir(dir string) bool { + base := dir + if idx := strings.LastIndex(dir, "/"); idx >= 0 { + base = dir[idx+1:] + } + if len(base) != 8 { + return false + } + for _, c := range base { + if c < '0' || c > '9' { + return false + } + } + return true +} + func (s *Service) FileList(c *gin.Context) { dir := c.Query("dir") lists, files, _ := s.uc.GetFileList(dir) @@ -66,6 +84,12 @@ func (s *Service) FileList(c *gin.Context) { "dir": dir, "files": files, } + if isDateDir(dir) { + if groups, err := s.uc.GetBatchGroups(dir); err == nil && len(groups) > 0 { + data["groups"] = groups + data["list"] = nil + } + } c.Header("Content-Type", "text/html; charset=utf-8") var buf bytes.Buffer if err := s.tmpl.ExecuteTemplate(&buf, "list.html", data); err != nil { @@ -139,6 +163,22 @@ func (s *Service) PprofProxy(c *gin.Context) { } } +func (s *Service) PprofDiffProxy(c *gin.Context) { + u := newUri(c) + u.Base = c.Param("base") + u.Route = RoutePprofDiff + u.ProxyBasePath = "/ui/" + u.ReBody = func(body string, currPath string) string { + body = strings.ReplaceAll(body, "href=\"./", "href=\""+currPath) + return body + } + s.log.Debugf("%#v", u) + err := s.uc.ProxyDiff(u, c.Writer, c.Request) + if err != nil { + c.String(404, err.Error()) + } +} + func (s *Service) TraceProxy(c *gin.Context) { u := newUri(c) u.Route = RouteTrace diff --git a/internal/service/service.go b/internal/service/service.go index 2fb0b35..2977266 100644 --- a/internal/service/service.go +++ b/internal/service/service.go @@ -2,6 +2,7 @@ package service import ( "html/template" + "strings" "github.com/go-kratos/kratos/v2/log" "github.com/google/wire" @@ -34,7 +35,11 @@ func NewService(c *conf.Bs, uc *biz.Usecase, logger log.Logger) *Service { if traceSec <= 0 { traceSec = 5 } - tmpl := template.Must(template.ParseFS(web.TemplateFS, "template/*.html")) + tmpl := template.Must(template.New("").Funcs(template.FuncMap{ + "fmtBatchTime": func(s string) string { + return strings.ReplaceAll(s, "_", ":") + }, + }).ParseFS(web.TemplateFS, "template/*.html")) return &Service{ env: c.App.Env, port2: c.Server.Port2, diff --git a/pkg/tool/pprof.go b/pkg/tool/pprof.go index 7f10aba..3f3424f 100644 --- a/pkg/tool/pprof.go +++ b/pkg/tool/pprof.go @@ -27,6 +27,11 @@ func newPprofX() *pprofX { type ArgPprofX struct { commonArg + baseFile string +} + +func (pa *ArgPprofX) SetBaseFile(file string) { + pa.baseFile = file } func (pa ArgPprofX) build() (s []string) { @@ -34,8 +39,11 @@ func (pa ArgPprofX) build() (s []string) { pa.name, "-no_browser=true", fmt.Sprintf(HTTPTpl, pa.port), - pa.file, } + if pa.baseFile != "" { + s = append(s, "-base", pa.baseFile) + } + s = append(s, pa.file) return } func (pa ArgPprofX) AppendEnv(s []string) []string { diff --git a/pkg/tool/tool.go b/pkg/tool/tool.go index 4fbb0de..a1edb73 100644 --- a/pkg/tool/tool.go +++ b/pkg/tool/tool.go @@ -10,6 +10,7 @@ type arg interface { setName(name string) SetPort(port int) SetFile(file string) + SetBaseFile(file string) AppendEnv([]string) []string build() []string } @@ -30,6 +31,7 @@ func (ca *commonArg) SetFile(file string) { func (ca *commonArg) SetPort(port int) { ca.port = port } +func (ca *commonArg) SetBaseFile(_ string) {} const ( Sep = " " diff --git a/web/template/list.html b/web/template/list.html index ceba303..f217a83 100644 --- a/web/template/list.html +++ b/web/template/list.html @@ -47,12 +47,36 @@ {{end}} + {{if .groups}} +
+ {{range .groups}} + {{$groupDir := .Dir}} +
+
+ 🕐 + {{fmtBatchTime .Label}} + {{len .Files}} 个文件 +
+
    + {{range .Files}} +
  • + 📄 + {{.Name}} + +
  • + {{end}} +
+
+ {{end}} +
+ {{end}} + {{if .files}}
Files
    {{range $_ := .files}} -
  • +
  • 📄 {{.Name}} @@ -63,6 +87,19 @@ {{end}}
+ +
+
+ +
+ + +
+
+
+ +
+ From 3c2cb7351e3b7cb1191044b73d44c6c0aad06a23 Mon Sep 17 00:00:00 2001 From: matteo Date: Sun, 19 Apr 2026 00:51:34 +0800 Subject: [PATCH 3/8] fix --- web/template/index.html | 348 ++++++++++++++++++++++++++++++++++------ 1 file changed, 302 insertions(+), 46 deletions(-) diff --git a/web/template/index.html b/web/template/index.html index 016b0b3..23e4d4a 100644 --- a/web/template/index.html +++ b/web/template/index.html @@ -28,16 +28,39 @@
-
+
Fetch One
- - -
Fetch a single pprof endpoint
+ + +
不含类型名,末尾无斜杠
+ +
+ + +
+ +
+ +
+ +
+ @@ -45,7 +68,24 @@
-
+
+
+
+ Fetch URL + +
+
+ + +
完整 URL,含类型和参数
+ +
+
+
+
+
Upload File
@@ -59,7 +99,7 @@
-
+
Fetch Batch @@ -81,46 +121,42 @@
采集类型 -
-
- 采样: -
- - -
-
- - -
+
+ 采样: +
+ + +
+
+ +
-
-
- 快照: -
- - -
-
- - -
-
- - -
-
- - -
-
- - -
-
- - -
+
+ 快照: +
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ +
@@ -327,6 +363,43 @@ }); } + function fetchProfileFromUrl(u, endpoint, resultEl, lockKey, actLabel, btn) { + if (locks[lockKey]) { return; } + if (!u) { + showError(resultEl, "Please enter a URL"); + return; + } + locks[lockKey] = true; + resultEl.textContent = ""; + setButtonLoading(btn, true); + + var pass = 0; + var itv = setInterval(function () { + ++pass; + resultEl.textContent = "Fetching... " + pass + "s"; + }, 1000); + + var formdata = new FormData(); + formdata.append("url", encodeURIComponent(u)); + + fetch(endpoint, { method: "POST", body: formdata }) + .then(function (res) { return res.json(); }) + .then(function (data) { + window.clearInterval(itv); + locks[lockKey] = false; + setButtonLoading(btn, false); + resultEl.textContent = ""; + resultEl.appendChild(buildResultList(data.res, data.files)); + store(data.id, data.res, u, actLabel); + }) + .catch(function (error) { + window.clearInterval(itv); + locks[lockKey] = false; + setButtonLoading(btn, false); + showError(resultEl, error.message); + }); + } + function upload() { var btn = document.querySelector("#subf"); if (locks["upload"]) { return; } @@ -557,13 +630,196 @@ fetchBatch(this); }); document.querySelector("#fetchdata1").addEventListener("click", function () { - fetchProfile("url_one", "/opt/run1", resultOne, "run1", "curl one", this); + var u = buildOneUrl(); + if (!u || u.endsWith("/")) { + showError(resultOne, "Please enter a Base URL"); + return; + } + fetchProfileFromUrl(u, "/opt/run1", resultOne, "run1", "curl one", this); }); document.querySelector("#subf").addEventListener("click", upload); + // --- Fetch One: type-aware panel --- + var oneTypeParams = document.querySelector("#typeParamsOne"); + var oneUrlPreview = document.querySelector("#url_preview_one"); + var oneTypeSelect = document.querySelector("#pprofType"); + var oneBaseInput = document.querySelector('input[name="base_url_one"]'); + + var oneTypeHTML = { + goroutine: [ + '
输出模式
', + '
', + '
', + '
', + '
', + '
', + '
', + '' + ].join(""), + + heap: [ + '
采集模式
', + '
', + '
', + '
', + '
', + '
', + '', + '', + '', + '秒 — heap?seconds=N
' + ].join(""), + + allocs: [ + '
采集模式
', + '
', + '
', + '
', + '', + '', + '', + '秒 — allocs?seconds=N
' + ].join(""), + + profile: [ + '
采集时长
', + '
', + '', + '秒 → profile?seconds=N
' + ].join(""), + + trace: [ + '
采集时长
', + '
', + '', + '秒 → trace?seconds=N
', + '
提示:结果用 go tool trace 查看,不同于 pprof
' + ].join(""), + + block: [ + '
⚠️ 前置条件:目标程序需调用 runtime.SetBlockProfileRate(rate),否则采集结果为空文件
', + '
采集模式
', + '
', + '
', + '
', + '', + '', + '', + '秒 → block?seconds=N
' + ].join(""), + + mutex: [ + '
⚠️ 前置条件:目标程序需调用 runtime.SetMutexProfileFraction(rate),否则采集结果为空文件
', + '
采集模式
', + '
', + '
', + '
', + '', + '', + '', + '秒 → mutex?seconds=N
' + ].join(""), + + threadcreate: '
快照 → threadcreate(OS 线程创建调用栈,通常较小)
', + cmdline: '
无参数,直接采集命令行参数
', + symbol: '
无参数,返回符号表(通常由 pprof 自动调用)
' + }; + + function getOneParams(type) { + var radio, sec; + switch (type) { + case "goroutine": + radio = document.querySelector('input[name="goroutine_mode"]:checked'); + return radio ? radio.value : ""; + case "heap": + radio = document.querySelector('input[name="heap_mode"]:checked'); + if (!radio) return ""; + if (radio.value === "seconds=") { + sec = document.querySelector("#heapDeltaSec"); + return "seconds=" + (sec && sec.value ? sec.value : "30"); + } + return radio.value; + case "allocs": + radio = document.querySelector('input[name="allocs_mode"]:checked'); + if (!radio) return ""; + if (radio.value === "seconds=") { + sec = document.querySelector("#allocsDeltaSec"); + return "seconds=" + (sec && sec.value ? sec.value : "30"); + } + return radio.value; + case "profile": + sec = document.querySelector("#profileSec"); + return "seconds=" + (sec && sec.value ? sec.value : "30"); + case "trace": + sec = document.querySelector("#traceSec1"); + return "seconds=" + (sec && sec.value ? sec.value : "5"); + case "block": + radio = document.querySelector('input[name="block_mode"]:checked'); + if (!radio) return ""; + if (radio.value === "seconds=") { + sec = document.querySelector("#blockDeltaSec"); + return "seconds=" + (sec && sec.value ? sec.value : "30"); + } + return radio.value; + case "mutex": + radio = document.querySelector('input[name="mutex_mode"]:checked'); + if (!radio) return ""; + if (radio.value === "seconds=") { + sec = document.querySelector("#mutexDeltaSec"); + return "seconds=" + (sec && sec.value ? sec.value : "30"); + } + return radio.value; + default: + return ""; + } + } + + function buildOneUrl() { + var base = oneBaseInput.value.replace(/\/$/, ""); + var type = oneTypeSelect.value; + var params = getOneParams(type); + var full = base + "/" + type + (params ? "?" + params : ""); + oneUrlPreview.value = full; + return full; + } + + function renderOneTypeParams(type) { + oneTypeParams.innerHTML = oneTypeHTML[type] || ""; + oneTypeParams.querySelectorAll("input").forEach(function(el) { + el.addEventListener("change", buildOneUrl); + el.addEventListener("input", buildOneUrl); + }); + if (type === "goroutine") { + document.querySelectorAll('input[name="goroutine_mode"]').forEach(function(r) { + r.addEventListener("change", function() { + var w = document.querySelector("#goroutineStw"); + if (w) w.style.display = (this.value === "debug=2") ? "" : "none"; + }); + }); + } + buildOneUrl(); + } + + oneTypeSelect.addEventListener("change", function() { renderOneTypeParams(this.value); }); + oneBaseInput.addEventListener("input", buildOneUrl); + renderOneTypeParams(oneTypeSelect.value); + + var resultManual = document.querySelector("#result_manual"); + + document.querySelector("#fetchdataManual").addEventListener("click", function () { + var u = document.querySelector('input[name="url_manual"]').value; + if (!u) { showError(resultManual, "Please enter a URL"); return; } + fetchProfileFromUrl(u, "/opt/run1", resultManual, "run1_manual", "curl url", this); + }); + var demoBase = "http://127.0.0.1:{{.Port2}}/internal/debug/pprof"; document.querySelector("#tryDemoOne").addEventListener("click", function () { - document.querySelector('input[name="url_one"]').value = demoBase + "/goroutine"; + oneBaseInput.value = demoBase; + oneTypeSelect.value = "goroutine"; + renderOneTypeParams("goroutine"); + }); + document.querySelector("#tryDemoUrl").addEventListener("click", function () { + document.querySelector('input[name="url_manual"]').value = demoBase + "/goroutine"; }); document.querySelector("#tryDemoBatch").addEventListener("click", function () { document.querySelector('input[name="url"]').value = demoBase; From 1ed86658e5ca8845b59c7bcf84705b78860c1ab5 Mon Sep 17 00:00:00 2001 From: matteo Date: Sun, 19 Apr 2026 01:22:56 +0800 Subject: [PATCH 4/8] curl --- web/template/index.html | 145 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 145 insertions(+) diff --git a/web/template/index.html b/web/template/index.html index 23e4d4a..88d5875 100644 --- a/web/template/index.html +++ b/web/template/index.html @@ -64,6 +64,7 @@ +
@@ -81,6 +82,7 @@ +
@@ -206,6 +208,7 @@ +
@@ -213,6 +216,26 @@
+ + + From 99566324be023f5491d610d50ef027b1350e2b5b Mon Sep 17 00:00:00 2001 From: matteo Date: Sun, 19 Apr 2026 10:03:03 +0800 Subject: [PATCH 5/8] doc --- web/template/_keys.html | 6 ++ web/template/index.html | 134 ++++++++++++++++++++++++++++++---- web/template/list.html | 2 +- web/template/person_curl.html | 47 +++++++++++- 4 files changed, 171 insertions(+), 18 deletions(-) create mode 100644 web/template/_keys.html diff --git a/web/template/_keys.html b/web/template/_keys.html new file mode 100644 index 0000000..a7c380c --- /dev/null +++ b/web/template/_keys.html @@ -0,0 +1,6 @@ +{{define "storageKeys"}} + +{{end}} diff --git a/web/template/index.html b/web/template/index.html index 88d5875..211be2d 100644 --- a/web/template/index.html +++ b/web/template/index.html @@ -236,9 +236,28 @@
+{{template "storageKeys" .}} ` + +func injectPlugins(body string) string { + if idx := strings.Index(body, ""); idx >= 0 { + return body[:idx] + pluginLoaderTag + body[idx:] + } + return body +} + func newUri(c *gin.Context) biz.Uri { return biz.Uri{ Path: c.Request.URL.Path, @@ -154,6 +179,7 @@ func (s *Service) PprofProxy(c *gin.Context) { u.ProxyBasePath = "/ui/" u.ReBody = func(body string, currPath string) string { body = strings.ReplaceAll(body, "href=\"./", "href=\""+currPath) + body = injectPlugins(body) return body } s.log.Debugf("%#v", u) @@ -170,6 +196,7 @@ func (s *Service) PprofDiffProxy(c *gin.Context) { u.ProxyBasePath = "/ui/" u.ReBody = func(body string, currPath string) string { body = strings.ReplaceAll(body, "href=\"./", "href=\""+currPath) + body = injectPlugins(body) return body } s.log.Debugf("%#v", u) diff --git a/web/embed.go b/web/embed.go index 3dd26c0..6b3d3f1 100644 --- a/web/embed.go +++ b/web/embed.go @@ -5,5 +5,5 @@ import "embed" //go:embed template/* var TemplateFS embed.FS -//go:embed static/* +//go:embed all:static var StaticFS embed.FS diff --git a/web/static/plugins/i18n-zh.js b/web/static/plugins/i18n-zh.js new file mode 100644 index 0000000..5885c89 --- /dev/null +++ b/web/static/plugins/i18n-zh.js @@ -0,0 +1,154 @@ +(function (P) { + 'use strict'; + + var dict = { + // ===== 导航菜单 ===== + 'View': '视图', + 'Top': '排名', + 'Graph': '调用图', + 'Flame Graph': '火焰图', + 'Peek': '窥视', + 'Source': '源码', + 'Disassemble': '反汇编', + + 'Sample': '采样类型', + + // ===== Refine / Config 菜单 ===== + 'Refine': '筛选', + 'Focus': '聚焦', + 'Ignore': '忽略', + 'Hide': '隐藏', + 'Show': '显示', + 'Show from': '从此显示', + 'Reset': '重置', + + 'Config': '配置', + 'Save as ...': '另存为…', + 'Download': '下载', + + // ===== Top 表头 ===== + 'Flat': '自身', + 'Flat%': '自身%', + 'Sum%': '累计%', + 'Cum': '累计', + 'Cum%': '累计占比%', + 'Name': '函数名', + 'Inlined?': '内联?', + + // ===== 对话框 ===== + 'Save options as': '保存配置为', + 'Cancel': '取消', + 'Save': '保存', + 'Delete config': '删除配置', + 'Delete': '删除', + + // ===== Flame Graph 结构文案 ===== + 'Search regexp': '搜索正则', + 'Reset zoom': '重置缩放', + + // ===== Flame Graph action menu ===== + 'Show source code': '查看源码', + 'Show source in new tab': '在新标签页查看源码', + }; + + // Graph SVG 字幕:含动态数字,用正则 partial-match + var partialPatterns = [ + { + re: /^Showing nodes accounting for (.+?), (.+?) of (.+?) total(.*)$/, + fn: function (m) { + return '显示节点占 ' + m[1] + ',共 ' + m[3] + ' 的 ' + m[2] + m[4]; + } + }, + { + re: /^Dropped (\d+) nodes? \(cum <= (.+?)\)(.*)$/, + fn: function (m) { + return '已省略 ' + m[1] + ' 个节点(cum ≤ ' + m[2] + ')' + m[3]; + } + }, + { + re: /^Dropped (\d+) edges? \(freq <= (.+?)\)(.*)$/, + fn: function (m) { + return '已省略 ' + m[1] + ' 条边(freq ≤ ' + m[2] + ')' + m[3]; + } + }, + ]; + + function translatePartial(text) { + for (var i = 0; i < partialPatterns.length; i++) { + var m = text.match(partialPatterns[i].re); + if (m) return partialPatterns[i].fn(m); + } + return null; + } + + function translateTextNode(node) { + if (node.nodeType === 3) { + var text = node.textContent.trim(); + if (text && dict[text]) { + node.textContent = node.textContent.replace(text, dict[text]); + } + return; + } + if (node.nodeType !== 1) return; + var tag = node.tagName; + if (tag === 'SCRIPT' || tag === 'STYLE' || tag === 'CODE' || tag === 'PRE') return; + // 火焰图函数块在 #stack-holder 内,函数名不翻译 + if (node.id === 'stack-holder' || node.id === 'stack-chart') return; + + if (node.children.length === 0) { + var t = node.textContent.trim(); + if (t && dict[t]) { + node.textContent = dict[t]; + return; + } + var partial = translatePartial(t); + if (partial) { + node.textContent = partial; + } + return; + } + for (var i = 0; i < node.childNodes.length; i++) { + translateTextNode(node.childNodes[i]); + } + } + + function translateAttrs(root) { + root.querySelectorAll('[title]').forEach(function (el) { + var t = el.getAttribute('title').trim(); + if (dict[t]) el.setAttribute('title', dict[t]); + }); + root.querySelectorAll('[placeholder]').forEach(function (el) { + var p = el.getAttribute('placeholder').trim(); + if (dict[p]) el.setAttribute('placeholder', dict[p]); + }); + } + + function translatePage() { + translateTextNode(document.body); + translateAttrs(document); + } + + P.register({ + name: 'i18n-zh', + version: '1.3.0', + views: ['*'], + + init: function () { + translatePage(); + }, + + onViewChange: function () { + translatePage(); + }, + + onMutation: function (nodes) { + for (var i = 0; i < nodes.length; i++) { + // 火焰图函数块在 #stack-holder 内,跳过 + var n = nodes[i]; + if (n.closest && n.closest('#stack-holder')) continue; + translateTextNode(n); + } + } + }); + +})(window.ProfPlugin); diff --git a/web/static/plugins/loader.js b/web/static/plugins/loader.js new file mode 100644 index 0000000..05ce2da --- /dev/null +++ b/web/static/plugins/loader.js @@ -0,0 +1,173 @@ +(function () { + 'use strict'; + + var MANIFEST = [ + '/static/plugins/i18n-zh.js', + ]; + + var runtime = { + plugins: [], + shared: {}, + _loaded: 0, + + register: function (plugin) { + if (!plugin.name) return; + plugin.views = plugin.views || ['*']; + this.plugins.push(plugin); + }, + + _currentView: function () { + var path = window.location.pathname; + if (path.indexOf('/flamegraph') !== -1) return 'flamegraph'; + if (path.indexOf('/top') !== -1) return 'top'; + if (path.indexOf('/peek') !== -1) return 'peek'; + if (path.indexOf('/source') !== -1) return 'source'; + if (path.indexOf('/disasm') !== -1) return 'disasm'; + return 'graph'; + }, + + _shouldRun: function (plugin, view) { + if (!plugin.views) return true; + if (plugin.views.indexOf('*') !== -1) return true; + return plugin.views.indexOf(view) !== -1; + }, + + _initAll: function () { + var view = this._currentView(); + for (var i = 0; i < this.plugins.length; i++) { + var p = this.plugins[i]; + if (p.init && this._shouldRun(p, view)) { + try { p.init(); } catch (e) { + console.error('[ProfPlugin] init error in ' + p.name + ':', e); + } + } + } + }, + + _notifyViewChange: function (view) { + for (var i = 0; i < this.plugins.length; i++) { + var p = this.plugins[i]; + if (p.onViewChange && this._shouldRun(p, view)) { + try { p.onViewChange(view); } catch (e) { + console.error('[ProfPlugin] onViewChange error in ' + p.name + ':', e); + } + } + } + }, + + _notifyMutation: function (nodes) { + var view = this._currentView(); + for (var i = 0; i < this.plugins.length; i++) { + var p = this.plugins[i]; + if (p.onMutation && this._shouldRun(p, view)) { + try { p.onMutation(nodes); } catch (e) { + console.error('[ProfPlugin] onMutation error in ' + p.name + ':', e); + } + } + } + }, + + _notifyCharacterData: function (target) { + var view = this._currentView(); + for (var i = 0; i < this.plugins.length; i++) { + var p = this.plugins[i]; + if (p.onCharacterData && this._shouldRun(p, view)) { + try { p.onCharacterData(target); } catch (e) { + console.error('[ProfPlugin] onCharacterData error in ' + p.name + ':', e); + } + } + } + } + }; + + window.ProfPlugin = runtime; + + function loadScripts() { + if (MANIFEST.length === 0) { + onAllLoaded(); + return; + } + var loaded = 0; + for (var i = 0; i < MANIFEST.length; i++) { + var s = document.createElement('script'); + s.src = MANIFEST[i]; + s.async = false; + s.onload = s.onerror = function () { + loaded++; + if (loaded >= MANIFEST.length) { + onAllLoaded(); + } + }; + document.head.appendChild(s); + } + } + + function onAllLoaded() { + runtime._initAll(); + startMutationObserver(); + startCharacterDataObservers(); + startViewMonitor(); + } + + function startCharacterDataObservers() { + if (typeof MutationObserver === 'undefined') return; + var selectors = []; + for (var i = 0; i < runtime.plugins.length; i++) { + var p = runtime.plugins[i]; + if (p.characterDataSelectors) { + selectors = selectors.concat(p.characterDataSelectors); + } + } + var seen = {}; + for (var j = 0; j < selectors.length; j++) { + var sel = selectors[j]; + if (seen[sel]) continue; + seen[sel] = true; + var el = document.querySelector(sel); + if (!el) continue; + (function (target) { + var obs = new MutationObserver(function () { + runtime._notifyCharacterData(target); + }); + obs.observe(target, { characterData: true, subtree: true }); + })(el); + } + } + + function startMutationObserver() { + if (typeof MutationObserver === 'undefined') return; + var observer = new MutationObserver(function (mutations) { + var nodes = []; + for (var i = 0; i < mutations.length; i++) { + for (var j = 0; j < mutations[i].addedNodes.length; j++) { + var n = mutations[i].addedNodes[j]; + if (n.nodeType === 1) nodes.push(n); + } + } + if (nodes.length > 0) { + runtime._notifyMutation(nodes); + } + }); + observer.observe(document.body, { childList: true, subtree: true }); + } + + function startViewMonitor() { + var lastView = runtime._currentView(); + function check() { + var view = runtime._currentView(); + if (view !== lastView) { + lastView = view; + runtime._notifyViewChange(view); + } + } + window.addEventListener('popstate', check); + window.addEventListener('hashchange', check); + setInterval(check, 500); + } + + if (document.readyState === 'loading') { + document.addEventListener('DOMContentLoaded', loadScripts); + } else { + loadScripts(); + } +})(); From 63f592e9a28aeff80ca0b90b068e89d14d4c80e9 Mon Sep 17 00:00:00 2001 From: matteo Date: Sun, 19 Apr 2026 23:35:37 +0800 Subject: [PATCH 7/8] plug --- internal/conf/type.go | 14 +- internal/server/router.go | 4 + internal/service/handler.go | 33 ++ internal/service/service.go | 6 + web/static/plugins/graph-explain.js | 550 ++++++++++++++++++++++++++++ web/static/plugins/loader.js | 98 ++++- web/static/plugins/peek-fold.js | 309 ++++++++++++++++ web/static/plugins/settings.js | 294 +++++++++++++++ web/static/plugins/source-fold.js | 195 ++++++++++ web/template/index.html | 1 + web/template/list.html | 1 + 11 files changed, 1484 insertions(+), 21 deletions(-) create mode 100644 web/static/plugins/graph-explain.js create mode 100644 web/static/plugins/peek-fold.js create mode 100644 web/static/plugins/settings.js create mode 100644 web/static/plugins/source-fold.js diff --git a/internal/conf/type.go b/internal/conf/type.go index b0ba896..cecd16d 100644 --- a/internal/conf/type.go +++ b/internal/conf/type.go @@ -17,8 +17,16 @@ type App struct { DeltaSeconds int `yaml:"DeltaSeconds"` TraceSeconds int `yaml:"TraceSeconds"` } +type PluginsConfig struct { + I18nZh bool `yaml:"i18n_zh"` + SourceFold bool `yaml:"source_fold"` + PeekFold bool `yaml:"peek_fold"` + GraphExplain bool `yaml:"graph_explain"` +} + type Bs struct { - Server *Server `yaml:"Server"` - Data *Data `yaml:"Data"` - App *App `yaml:"App"` + Server *Server `yaml:"Server"` + Data *Data `yaml:"Data"` + App *App `yaml:"App"` + Plugins *PluginsConfig `yaml:"Plugins"` } diff --git a/internal/server/router.go b/internal/server/router.go index 9a6f303..f7a6906 100644 --- a/internal/server/router.go +++ b/internal/server/router.go @@ -55,6 +55,10 @@ func (h *HTTPServerX) router() (r *gin.Engine, err error) { r.POST("/opt/upload", h.srv.Upload) r.POST("/opt/run", h.srv.Run) r.POST("/opt/run1", h.srv.Run1) + api := r.Group("/api") + { + api.GET("/plugins", h.srv.APIPlugins) + } return } diff --git a/internal/service/handler.go b/internal/service/handler.go index 92f6e0a..e85f2a9 100644 --- a/internal/service/handler.go +++ b/internal/service/handler.go @@ -282,6 +282,39 @@ func (s *Service) Run(c *gin.Context) { }) } +type PluginInfo struct { + Name string `json:"name"` + Enabled bool `json:"enabled"` + Description string `json:"description"` +} + +func (s *Service) APIPlugins(c *gin.Context) { + c.JSON(http.StatusOK, gin.H{ + "plugins": []PluginInfo{ + { + Name: "i18n-zh", + Enabled: s.pluginsConfig.I18nZh, + Description: "界面中文汉化", + }, + { + Name: "source-fold", + Enabled: s.pluginsConfig.SourceFold, + Description: "Source 视图函数折叠", + }, + { + Name: "peek-fold", + Enabled: s.pluginsConfig.PeekFold, + Description: "Peek 视图分组折叠", + }, + { + Name: "graph-explain", + Enabled: s.pluginsConfig.GraphExplain, + Description: "Graph 节点点击解释", + }, + }, + }) +} + func (s *Service) Run1(c *gin.Context) { uri := c.PostForm("url") relativePath, size, err := s.uc.DealRun1(c.Request.Context(), uri) diff --git a/internal/service/service.go b/internal/service/service.go index 2977266..767ed9e 100644 --- a/internal/service/service.go +++ b/internal/service/service.go @@ -20,6 +20,7 @@ type Service struct { deltaSeconds int traceSeconds int tmpl *template.Template + pluginsConfig conf.PluginsConfig } func NewService(c *conf.Bs, uc *biz.Usecase, logger log.Logger) *Service { @@ -40,6 +41,10 @@ func NewService(c *conf.Bs, uc *biz.Usecase, logger log.Logger) *Service { return strings.ReplaceAll(s, "_", ":") }, }).ParseFS(web.TemplateFS, "template/*.html")) + var pluginsCfg conf.PluginsConfig + if c.Plugins != nil { + pluginsCfg = *c.Plugins + } return &Service{ env: c.App.Env, port2: c.Server.Port2, @@ -49,6 +54,7 @@ func NewService(c *conf.Bs, uc *biz.Usecase, logger log.Logger) *Service { uc: uc, log: log.NewHelper(logger), tmpl: tmpl, + pluginsConfig: pluginsCfg, } } diff --git a/web/static/plugins/graph-explain.js b/web/static/plugins/graph-explain.js new file mode 100644 index 0000000..637d28e --- /dev/null +++ b/web/static/plugins/graph-explain.js @@ -0,0 +1,550 @@ +(function (P) { + 'use strict'; + + var panel = null; // 全局唯一面板 + + // 从 URL ?si= 读取 profile 类型,返回 { key, label, desc } + var SI_LABELS = { + 'alloc_space': { label: 'alloc_space', desc: '历史累计分配字节数' }, + 'alloc_objects': { label: 'alloc_objects', desc: '历史累计分配对象数' }, + 'inuse_space': { label: 'inuse_space', desc: '当前使用中字节数' }, + 'inuse_objects': { label: 'inuse_objects', desc: '当前使用中对象数' }, + 'cpu': { label: 'cpu', desc: 'CPU 占用时间' }, + 'contentions': { label: 'contentions', desc: '锁竞争次数' }, + 'delay': { label: 'delay', desc: '锁等待时间' }, + }; + function getProfileType() { + try { + var si = new URLSearchParams(window.location.search).get('si') || ''; + return SI_LABELS[si] || (si ? { label: si, desc: '' } : null); + } catch (e) { return null; } + } + + // SVG id "node3" → DOT id "N3" + function toDotId(svgId) { + return 'N' + svgId.replace('node', ''); + } + + // dotId "N3" → 从节点 取函数名 + function dotIdToFunc(graph0, id) { + var svgId = 'node' + id.replace('N', ''); + var g = graph0.querySelector('#' + svgId); + if (!g) return id; + var a = g.querySelector('a'); + var t = a ? (a.getAttribute('xlink:title') || '') : ''; + var m = t.match(/^(.+?)\s*\(/); + return m ? m[1].trim() : id; + } + + // 从当前节点向上追溯,沿 cum 最大的父节点走,最多 maxHops 步 + // 返回 [{dotId, func}, ...] 从 root 到 current + function buildCallChain(graph0, dotId, maxHops) { + maxHops = maxHops || 6; + + function findCallerIds(id) { + var result = []; + graph0.querySelectorAll('g.edge').forEach(function (e) { + var titleEl = e.querySelector('title'); + if (!titleEl) return; + var txt = titleEl.textContent.trim(); + if (/NN\d+/.test(txt)) return; + var parts = txt.split('->'); + if (parts.length !== 2) return; + if (parts[1].trim() === id) result.push(parts[0].trim()); + }); + return result; + } + + function getNodeCum(id) { + var svgId = 'node' + id.replace('N', ''); + var g = graph0.querySelector('#' + svgId); + if (!g) return 0; + var a = g.querySelector('a'); + var t = a ? (a.getAttribute('xlink:title') || '') : ''; + var m = t.match(/([\d.]+)(kB|MB|B)/i); + return m ? parseBytes(m[1] + m[2]) : 0; + } + + var chain = [{ dotId: dotId, func: dotIdToFunc(graph0, dotId) }]; + var current = dotId; + var visited = {}; visited[dotId] = true; + + for (var i = 0; i < maxHops; i++) { + var callers = findCallerIds(current).filter(function (c) { return !visited[c]; }); + if (callers.length === 0) break; + // 选 cum 最大的父节点(热路径) + var best = callers[0], bestCum = getNodeCum(callers[0]); + callers.forEach(function (c) { + var v = getNodeCum(c); + if (v > bestCum) { bestCum = v; best = c; } + }); + visited[best] = true; + chain.unshift({ dotId: best, func: dotIdToFunc(graph0, best) }); + current = best; + } + return chain; + } + + // 构造 pprof Source 视图 URL + function buildSourceUrl(funcName) { + try { + var base = window.location.pathname.replace(/\/[^/]+$/, ''); + var si = new URLSearchParams(window.location.search).get('si') || ''; + var esc = funcName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + return base + '/source?f=' + encodeURIComponent(esc) + (si ? '&si=' + si : ''); + } catch (e) { return ''; } + } + + // 在图中按 cum 排名(仅统计 node* 节点,不含 nodelet) + function getNodeRanking(graph0, dotId) { + var nodes = []; + graph0.querySelectorAll('g.node').forEach(function (g) { + if (!g.id || !/^node\d+$/.test(g.id)) return; + var a = g.querySelector('a'); + var t = a ? (a.getAttribute('xlink:title') || '') : ''; + var m = t.match(/([\d.]+)(kB|MB|B)/i); + if (!m) return; + nodes.push({ id: g.id, cum: parseBytes(m[1] + m[2]) }); + }); + nodes.sort(function (a, b) { return b.cum - a.cum; }); + var myId = 'node' + dotId.replace('N', ''); + for (var i = 0; i < nodes.length; i++) { + if (nodes[i].id === myId) return { rank: i + 1, total: nodes.length }; + } + return null; + } + + // 从函数全名提取包路径并归类:标准库 / 业务代码 / 第三方库 + function getPackageInfo(funcName) { + // 去掉方法名部分,提取包路径 + var pkg = funcName.replace(/\.\([^)]*\).*$/, '').replace(/\.[^./]+$/, ''); + var firstSeg = pkg.split('/')[0]; + if (!firstSeg.includes('.')) { + return { pkg: pkg, badge: '标准库', color: '#1b5e20', bg: '#e8f5e9' }; + } + if (pkg.indexOf('/internal/') !== -1 || pkg.indexOf('/cmd/') !== -1) { + return { pkg: pkg, badge: '业务代码', color: '#bf360c', bg: '#fbe9e7' }; + } + return { pkg: pkg, badge: '第三方库', color: '#4a148c', bg: '#f3e5f5' }; + } + + // 从 提取函数名和 cum + function parseNodeTitle(g) { + var a = g.querySelector('a'); + var t = a ? (a.getAttribute('xlink:title') || '') : ''; + // "biz.(*Usecase).Proxy.func2 (5926.07kB)" + var m = t.match(/^(.+?)\s*\(([^)]+)\)$/); + return { + name: m ? m[1].trim() : t.trim(), + cum: m ? m[2] : '', + }; + } + + // 从 元素提取 flat(自身占比行)和 cum("of ..." 行带百分比) + function parseNodeTexts(g) { + var flat = '', cum = ''; + g.querySelectorAll('text').forEach(function (tx) { + var s = tx.textContent.trim(); + // flat 行:包含 (X%) 且不以 "of " 开头 + if (!flat && /\([\d.]+%\)/.test(s) && s.indexOf('of ') !== 0) { + flat = s; + } + // cum 行:以 "of " 开头且包含 (X%) + if (!cum && s.indexOf('of ') === 0 && /\([\d.]+%\)/.test(s)) { + cum = s; + } + }); + return { flat: flat, cum: cum }; + } + + // 用 DOT ID 在 graph0 内查找进出边 + function findEdges(graph0, dotId) { + var ins = [], outs = [], inlines = []; + graph0.querySelectorAll('g.edge').forEach(function (e) { + var titleEl = e.querySelector('title'); + if (!titleEl) return; + var titleText = titleEl.textContent.trim(); // "N1->N7" 或 "N3->NN3_0" + + // nodelet 出边(N3->NN3_0):收集为内联分配,仅处理属于本节点的 + var nodeletM = titleText.match(/^(.+)->NN(\d+_\d+)$/); + if (nodeletM) { + if (nodeletM[1] === dotId) { + var a = e.querySelector('a'); + var weight = a ? (a.getAttribute('xlink:title') || '') : ''; + // 从 nodelet 节点的 取尺寸标签(如 "64kB..72kB") + var nodeletId = 'NN' + nodeletM[2]; + var nodeletG = graph0.querySelector('#' + nodeletId); + var sizeLabel = ''; + if (nodeletG) { + var tx = nodeletG.querySelector('text'); + if (tx) sizeLabel = tx.textContent.trim(); + } + inlines.push({ label: sizeLabel || nodeletId, weight: weight }); + } + return; + } + + // 跳过其他含 NN 的边(防御) + if (/NN\d+/.test(titleText)) return; + + // 精确匹配:split('->'),避免 N3 误匹配 N31/N32 等 + var parts = titleText.split('->'); + if (parts.length !== 2) return; + var src = parts[0].trim(); + var dst = parts[1].trim(); + var isOut = src === dotId; + var isIn = dst === dotId; + if (!isOut && !isIn) return; + // xlink:title 格式:"srcFunc -> destFunc (weight)" 或 "srcFunc ... destFunc (weight)" + var a = e.querySelector('a'); + var xl = a ? (a.getAttribute('xlink:title') || '') : ''; + var m = xl.match(/^(.+?)\s*(?:->|\.\.\.)\s*(.+?)\s*\(([^)]+)\)$/); + if (!m) return; + if (isOut) outs.push({ func: m[2].trim(), weight: m[3] }); + if (isIn) ins.push({ func: m[1].trim(), weight: m[3] }); + }); + return { ins: ins, outs: outs, inlines: inlines }; + } + + // 根据 Flat/Cum 百分比比值生成诊断文字 + function diagnoseFlatCum(flatText, cumText) { + var fm = (flatText || '').match(/([\d.]+)%/); + var cm = (cumText || '').match(/([\d.]+)%/); + if (!cm) return ''; + var flatPct = fm ? parseFloat(fm[1]) : 0; + var cumPct = parseFloat(cm[1]); + var ratio = cumPct > 0 ? flatPct / cumPct : 0; + if (flatPct === 0) { + return 'Flat = 0,纯调用入口,自身不分配,热点在下游子节点'; + } + if (ratio > 0.8) { + return 'Flat/Cum 比值高(' + Math.round(ratio * 100) + '%),直接分配热点,优化此函数本身'; + } + if (ratio > 0.3) { + return 'Flat/Cum 比值中等(' + Math.round(ratio * 100) + '%),自身和子调用均有贡献'; + } + return 'Flat/Cum 比值低(' + Math.round(ratio * 100) + '%),主要是调用入口,热点在下游'; + } + + // 只显示最后两段(包名.函数名),避免过长 + function shortenFunc(name) { + var parts = name.split('.'); + if (parts.length > 2) return '\u2026' + parts.slice(-2).join('.'); + return name; + } + + function escHtml(s) { + return String(s) + .replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"'); + } + + // ── 面板渲染 ──────────────────────────────────────────────────────────────── + + function createPanel() { + panel = document.createElement('div'); + panel.id = 'prof-graph-explain'; + panel.setAttribute('data-prof-plugin', 'graph-explain'); + panel.style.cssText = [ + 'position:fixed', 'top:60px', 'right:12px', + 'background:#fff', 'border:1px solid #ddd', + 'border-radius:4px', 'padding:12px 14px', + 'min-width:280px', 'max-width:400px', + 'max-height:70vh', 'overflow-y:auto', + 'z-index:9998', 'font-size:13px', + 'font-family:sans-serif', 'line-height:1.5', + 'box-shadow:0 2px 8px rgba(0,0,0,0.12)', + 'display:none', + ].join(';'); + document.body.appendChild(panel); + } + + // 从权重字符串中提取数值(支持 kB / MB / B) + function parseBytes(s) { + var m = String(s).match(/([\d.]+)\s*(kB|MB|B)?/i); + if (!m) return 0; + var v = parseFloat(m[1]); + var u = (m[2] || '').toLowerCase(); + if (u === 'mb') return v * 1024; + if (u === 'b') return v / 1024; + return v; // kB default + } + + // 计算某权重占 cum 的百分比,返回字符串如 "26.7%" + function pctOfCum(weightStr, cumStr) { + var w = parseBytes(weightStr); + var c = parseBytes(cumStr); + if (!c || !w) return ''; + return (w / c * 100).toFixed(1) + '%'; + } + + // 渲染一行树节点,prefix 是 "├── " / "└── " / "│ ├── " 等 + function treeRow(prefix, name, weight, pct, opts) { + opts = opts || {}; + var nameColor = opts.nameColor || '#333'; + var weightColor = opts.weightColor || '#1565c0'; + var html = '
'; + html += '' + escHtml(prefix) + ''; + html += '' + escHtml(name) + ''; + if (weight) { + html += '' + escHtml(weight) + ''; + } + if (pct) { + html += '\u2191' + escHtml(pct) + ''; + } + html += '
'; + return html; + } + + // extra = { graph0, dotId } + function renderPanel(info, edges, extra) { + var graph0 = extra && extra.graph0; + var dotId = extra && extra.dotId; + var diag = diagnoseFlatCum(info.flat, info.cum); + var hasOuts = edges.outs.length > 0; + var hasInlines = edges.inlines && edges.inlines.length > 0; + var pt = getProfileType(); + var pkgInfo = getPackageInfo(info.name); + var ranking = graph0 && dotId ? getNodeRanking(graph0, dotId) : null; + var srcUrl = buildSourceUrl(info.name); + var chain = graph0 && dotId ? buildCallChain(graph0, dotId) : []; + var html = '', md = ''; + + // ── 标题行:函数名 + Source链接 + 复制 + 关闭 ─────────────────────────── + html += '
'; + html += '' + escHtml(info.name) + ''; + html += ''; + if (srcUrl) { + html += 'Source\u2197'; + } + html += '\uD83D\uDCCB'; + html += '\u2715'; + html += '
'; + + // ── 徽标行:包类型 + Profile 类型 + 排名 ──────────────────────────────── + html += '
'; + if (pkgInfo) { + html += '' + + escHtml(pkgInfo.badge) + ''; + } + if (pt) { + html += '' + escHtml(pt.label) + ''; + if (pt.desc) { + html += '' + escHtml(pt.desc) + ''; + } + } + if (ranking) { + html += 'cum \u7b2c ' + + ranking.rank + ' / ' + ranking.total + ''; + } + html += '
'; + + // ── md:与面板所见保持一致,无主观框架 ──────────────────────────────────── + md += '\u51fd\u6570\uff1a' + info.name + '\n'; + if (pkgInfo) md += '\u5305\u7c7b\u578b\uff1a' + pkgInfo.badge + '\n'; + if (pt) md += 'Profile\uff1a' + pt.label + (pt.desc ? '\uff08' + pt.desc + '\uff09' : '') + '\n'; + if (ranking) md += 'cum \u6392\u540d\uff1a\u7b2c ' + ranking.rank + ' / ' + ranking.total + '\n'; + + // ── Flat / Cum ────────────────────────────────────────────────────────── + html += '
'; + html += '
'; + html += '
\u81ea\u8eab ' + escHtml(info.flat || '0') + '' + + '\u76f4\u63a5\u5206\u914d
'; + html += '
\u7d2f\u8ba1 ' + escHtml(info.cum || '\u2014') + '' + + '\u542b\u5b50\u8c03\u7528
'; + html += '
'; + md += '\n\u81ea\u8eab\uff08flat\uff09\uff1a' + (info.flat || '0') + '\u3000\u76f4\u63a5\u5206\u914d\n'; + md += '\u7d2f\u8ba1\uff08cum\uff09\uff1a' + (info.cum || '\u2014') + '\u3000\u542b\u5168\u90e8\u5b50\u8c03\u7528\n'; + + // ── 完整调用路径 ──────────────────────────────────────────────────────── + if (chain.length > 1) { + html += '
' + + '\uD83D\uDDFA\uFE0F \u8c03\u7528\u8def\u5f84
'; + html += '
'; + html += chain.map(function (n, i) { + var isLast = i === chain.length - 1; + var name = shortenFunc(n.func); + return isLast + ? '' + escHtml(name) + '' + : escHtml(name); + }).join(' \u2192 '); + html += '
'; + md += '\n\uD83D\uDDFA\uFE0F \u8c03\u7528\u8def\u5f84\n'; + md += chain.map(function (n) { return n.func; }).join(' \u2192 ') + '\n'; + } + + // ── 调用者 tree ───────────────────────────────────────────────────────── + if (edges.ins.length > 0) { + html += '
\uD83D\uDCE5 \u8c03\u7528\u8005
'; + md += '\n\uD83D\uDCE5 \u8c03\u7528\u8005\n'; + edges.ins.forEach(function (e, i) { + var isLast = i === edges.ins.length - 1; + var pre = isLast ? '\u2514\u2500\u2500 ' : '\u251C\u2500\u2500 '; + html += treeRow(pre, e.func, e.weight, '', { weightColor: '#c62828' }); + md += pre + e.func + ' ' + e.weight + '\n'; + }); + } + + // ── 被调用 tree ───────────────────────────────────────────────────────── + if (hasOuts || hasInlines) { + html += '
' + + '\uD83D\uDCE4 \u88ab\u8c03\u7528' + + '\u6574\u4f53 ' + + escHtml(info.cum || '') + '
'; + md += '\n\uD83D\uDCE4 \u88ab\u8c03\u7528\uff08\u6574\u4f53 ' + (info.cum || '') + '\uff09\n'; + + var topItems = edges.outs.slice(); + if (hasInlines) topItems.push({ isInlineGroup: true }); + + topItems.forEach(function (item, i) { + var isLast = i === topItems.length - 1; + var pre = isLast ? '\u2514\u2500\u2500 ' : '\u251C\u2500\u2500 '; + var contPre = isLast ? ' ' : '\u2502 '; + + if (item.isInlineGroup) { + var flatPct = pctOfCum(info.flat, info.cum); + html += treeRow(pre, '\u81ea\u8eab\u76f4\u63a5\u5206\u914d\uff08flat\uff09', info.flat, flatPct, { nameColor: '#666' }); + md += pre + '\u81ea\u8eab\u76f4\u63a5\u5206\u914d\uff08flat\uff09 ' + (info.flat || '') + (flatPct ? ' \u2191' + flatPct : '') + '\n'; + edges.inlines.forEach(function (e, j) { + var subLast = j === edges.inlines.length - 1; + var subPre = contPre + (subLast ? '\u2514\u2500\u2500 ' : '\u251C\u2500\u2500 '); + var pct = pctOfCum(e.weight, info.cum); + var label = e.label.replace(/\.\./g, '~') + ' \u5c3a\u5bf8'; + html += treeRow(subPre, label, e.weight, pct, { nameColor: '#888' }); + md += subPre + label + ' ' + e.weight + (pct ? ' \u2191' + pct : '') + '\n'; + }); + } else { + var pct = pctOfCum(item.weight, info.cum); + html += treeRow(pre, item.func, item.weight, pct); + md += pre + item.func + ' ' + item.weight + (pct ? ' \u2191' + pct : '') + '\n'; + } + }); + } + + // ── 诊断 ──────────────────────────────────────────────────────────────── + if (diag) { + html += '
'; + html += '
\uD83D\uDCA1 ' + escHtml(diag) + '
'; + md += '\n\uD83D\uDCA1 ' + diag + '\n'; + } + + panel.innerHTML = html; + panel._copyText = md; + + var closeBtn = panel.querySelector('#prof-explain-close'); + if (closeBtn) { + closeBtn.addEventListener('click', function () { panel.style.display = 'none'; }); + } + var copyBtn = panel.querySelector('#prof-explain-copy'); + if (copyBtn) { + copyBtn.addEventListener('click', function () { + var t = panel._copyText || ''; + if (navigator.clipboard && navigator.clipboard.writeText) { + navigator.clipboard.writeText(t).then(function () { + copyBtn.textContent = '\u2713'; + setTimeout(function () { copyBtn.textContent = '\uD83D\uDCCB'; }, 1500); + }).catch(function () { fallbackCopy(t, copyBtn); }); + } else { + fallbackCopy(t, copyBtn); + } + }); + } + } + + function fallbackCopy(text, btn) { + var ta = document.createElement('textarea'); + ta.value = text; + ta.style.cssText = 'position:fixed;top:-9999px;left:-9999px'; + document.body.appendChild(ta); + ta.select(); + try { + document.execCommand('copy'); + if (btn) { btn.textContent = '\u2713'; setTimeout(function () { btn.textContent = '\uD83D\uDCCB'; }, 1500); } + } catch (e) { /* ignore */ } + document.body.removeChild(ta); + } + + function showPanel(info, edges, extra) { + if (!panel) createPanel(); + renderPanel(info, edges, extra); + panel.style.display = 'block'; + } + + // ── 事件绑定 ──────────────────────────────────────────────────────────────── + + var _bound = false; + + function init() { + var graph0 = document.getElementById('graph0'); + if (!graph0) return; + // graph0 是 ,其父元素是 + var svg = graph0.parentElement; + if (!svg) return; + // 避免重复绑定 + if (svg._graphExplainBound) return; + svg._graphExplainBound = true; + + svg.addEventListener('click', function (e) { + // 向上找到 graph0 的直接子元素(节点 ) + var el = e.target; + while (el && el.parentElement !== graph0) { + el = el.parentElement; + } + if (!el || !el.id || el.id.indexOf('node') !== 0) { + // 以下情况保持面板可见,不关闭: + // 1. edge 元素(边路径) + // 2. nodelet 节点(id = NN3_0 格式,是 inline 函数小方块) + // 3. 边 label 元素(id 含 "edge",如 a_edge41-label) + var isEdge = el && el.classList && el.classList.contains('edge'); + var isNodelet = el && el.id && /^NN\d+/.test(el.id); + var isEdgeElem = el && el.id && el.id.indexOf('edge') !== -1; + if (!isEdge && !isNodelet && !isEdgeElem && panel) { + panel.style.display = 'none'; + } + return; + } + + var titleInfo = parseNodeTitle(el); + var textInfo = parseNodeTexts(el); + var funcName = titleInfo.name || ''; + if (!funcName) return; + + var info = { + name: funcName, + flat: textInfo.flat, + cum: textInfo.cum || ('(' + titleInfo.cum + ')'), + }; + + var dotId = toDotId(el.id); + var edges = findEdges(graph0, dotId); + showPanel(info, edges, { graph0: graph0, dotId: dotId }); + + // 阻止事件冒泡,避免 pprof 原生点击逻辑关闭面板 + e.stopPropagation(); + }); + } + + // ── 注册 ───────────────────────────────────────────────────────────────────── + + P.register({ + name: 'graph-explain', + version: '1.0.0', + views: ['graph'], + init: function () { init(); }, + onViewChange: function (view) { + if (view === 'graph') { + init(); + } else if (panel) { + panel.style.display = 'none'; + } + }, + }); + +})(window.ProfPlugin); diff --git a/web/static/plugins/loader.js b/web/static/plugins/loader.js index 05ce2da..e8141ee 100644 --- a/web/static/plugins/loader.js +++ b/web/static/plugins/loader.js @@ -1,8 +1,12 @@ (function () { 'use strict'; + // MANIFEST: plugin name → static src path; all default-off via /api/plugins var MANIFEST = [ - '/static/plugins/i18n-zh.js', + { name: 'i18n-zh', src: '/static/plugins/i18n-zh.js' }, + { name: 'source-fold', src: '/static/plugins/source-fold.js' }, + { name: 'peek-fold', src: '/static/plugins/peek-fold.js' }, + { name: 'graph-explain', src: '/static/plugins/graph-explain.js' }, ]; var runtime = { @@ -82,23 +86,64 @@ window.ProfPlugin = runtime; - function loadScripts() { - if (MANIFEST.length === 0) { - onAllLoaded(); - return; - } + // ── Fetch server-side plugin defaults ────────────────────────────────────── + function fetchPluginConfig(callback) { + var xhr = new XMLHttpRequest(); + xhr.open('GET', '/api/plugins'); + xhr.onload = function () { + var config = {}; + if (xhr.status === 200) { + try { + var data = JSON.parse(xhr.responseText); + (data.plugins || []).forEach(function (p) { + config[p.name] = p.enabled; + }); + } catch (e) { + console.warn('[ProfPlugin] failed to parse /api/plugins:', e); + } + } + callback(config); + }; + xhr.onerror = function () { callback({}); }; + xhr.send(); + } + + // ── Merge localStorage overrides (highest priority) ──────────────────────── + function resolveEnabled(serverConfig) { + var result = {}; + Object.keys(serverConfig).forEach(function (name) { + var lsKey = 'prof-plugin-' + name; + var lsVal = localStorage.getItem(lsKey); + if (lsVal !== null) { + result[name] = lsVal === 'true'; + } else { + result[name] = serverConfig[name]; + } + }); + return result; + } + + // ── Load a single script, invoke cb when done ────────────────────────────── + function loadScript(src, cb) { + var s = document.createElement('script'); + s.src = src; + s.async = false; + s.onload = s.onerror = function () { cb(); }; + document.head.appendChild(s); + } + + // ── Load enabled plugins from MANIFEST sequentially ─────────────────────── + function loadEnabledPlugins(enabledMap, cb) { + var toLoad = MANIFEST.filter(function (item) { + return enabledMap[item.name] === true; + }); + if (toLoad.length === 0) { cb(); return; } var loaded = 0; - for (var i = 0; i < MANIFEST.length; i++) { - var s = document.createElement('script'); - s.src = MANIFEST[i]; - s.async = false; - s.onload = s.onerror = function () { + for (var i = 0; i < toLoad.length; i++) { + loadScript(toLoad[i].src, function () { loaded++; - if (loaded >= MANIFEST.length) { - onAllLoaded(); - } - }; - document.head.appendChild(s); + if (loaded >= toLoad.length) { cb(); } + }); } } @@ -109,6 +154,23 @@ startViewMonitor(); } + // ── Boot sequence ────────────────────────────────────────────────────────── + // 1. Load settings.js always (settings panel is not governed by MANIFEST) + // 2. Fetch /api/plugins for server defaults + // 3. Merge localStorage overrides + // 4. Load only the enabled plugins + // 5. Run onAllLoaded + function boot() { + loadScript('/static/plugins/settings.js', function () { + fetchPluginConfig(function (serverConfig) { + var enabled = resolveEnabled(serverConfig); + loadEnabledPlugins(enabled, function () { + onAllLoaded(); + }); + }); + }); + } + function startCharacterDataObservers() { if (typeof MutationObserver === 'undefined') return; var selectors = []; @@ -166,8 +228,8 @@ } if (document.readyState === 'loading') { - document.addEventListener('DOMContentLoaded', loadScripts); + document.addEventListener('DOMContentLoaded', boot); } else { - loadScripts(); + boot(); } })(); diff --git a/web/static/plugins/peek-fold.js b/web/static/plugins/peek-fold.js new file mode 100644 index 0000000..21509bb --- /dev/null +++ b/web/static/plugins/peek-fold.js @@ -0,0 +1,309 @@ +(function (P) { + 'use strict'; + + var SEPARATOR_RE = /^[-]{20,}\+[-]+/; + + // 从 localStorage 读取配置 + function loadConfig() { + var defaults = { collapseStd: true, collapseMod: false, collapseAll: false, shortenPaths: true }; + try { + var raw = localStorage.getItem('prof-peek-fold-config'); + if (raw) return Object.assign(defaults, JSON.parse(raw)); + } catch (e) {} + return defaults; + } + + // 判断是否是主节点行(| 后1个空格,不是3个空格) + function isNodeLine(line) { + return /\| \S/.test(line) && !/\|\s{3}/.test(line.replace('| ', '|X')); + } + + // 从主节点行提取函数名 + function extractNodeName(line) { + var m = line.match(/\|\s(.+)$/); + return m ? m[1].trim() : line.trim(); + } + + // 根据 block 的 bodyLines 中的文件路径分类 + function classifyBlock(block, roots) { + for (var i = 0; i < block.bodyLines.length; i++) { + var m = block.bodyLines[i].match(/(\/[^\s]+\.go:\d+)/); + if (!m) continue; + var fp = m[1]; + if (roots.mod && fp.indexOf(roots.mod) === 0) return 'thirdparty'; + if (roots.std && fp.indexOf(roots.std) === 0) return 'stdlib'; + if (fp.indexOf('/pkg/mod/') !== -1) return 'thirdparty'; + return 'local'; + } + // 兜底:包名无域名 → stdlib + var pkg = extractPkg(block.nodeFunc); + return (pkg && pkg.split('/')[0].indexOf('.') === -1) ? 'stdlib' : 'local'; + } + + // 判断是否默认折叠 + function shouldFold(block, roots, config) { + if (config.collapseAll) return true; + var category = classifyBlock(block, roots); + if (config.collapseStd && category === 'stdlib') return true; + if (config.collapseMod && category === 'thirdparty') return true; + return false; + } + + // ── 路径缩写模块 ────────────────────────────────────────────────────────── + + // "runtime.semasleep" → "runtime" + // "github.com/gin-gonic/gin.(*C).Next" → "github.com/gin-gonic/gin" + function extractPkg(funcName) { + return funcName + .replace(/\(\*?[^)]+\)\.[^.]+$/, '') // 去掉 (*Type).Method + .replace(/\.[^./]+$/, ''); // 去掉最后 .FuncName + } + + // 扫描所有行,发现 std/mod 路径根 + // peek 行格式:" ... | funcname /abs/path/file.go:N",行首是空格+数字,不能用 ^ + function discoverRoots(lines) { + var roots = { std: null, mod: null }; + for (var i = 0; i < lines.length; i++) { + var m = lines[i].match(/\|\s+(\S+)\s+(\/[^\s]+\.go:\d+)/); + if (!m) continue; + var funcName = m[1]; + var filePath = m[2]; + var modIdx = filePath.indexOf('/pkg/mod/'); + if (modIdx !== -1 && !roots.mod) { + roots.mod = filePath.slice(0, modIdx + '/pkg/mod/'.length); + } + if (!roots.std && modIdx === -1) { + var pkg = extractPkg(funcName); + if (pkg && pkg.indexOf('.') === -1) { + var pkgIdx = filePath.indexOf('/' + pkg + '/'); + if (pkgIdx !== -1) { + roots.std = filePath.slice(0, pkgIdx + 1); + } + } + } + if (roots.std && roots.mod) break; + } + return roots; + } + + function shortenPath(filePath, roots) { + if (roots.mod && filePath.indexOf(roots.mod) === 0) { + return 'mod/' + filePath.slice(roots.mod.length); + } + if (roots.std && filePath.indexOf(roots.std) === 0) { + return 'std/' + filePath.slice(roots.std.length); + } + return filePath; + } + + // 对单行做路径缩写替换(只替换 /abs/path/file.go:N 形式) + function shortenLine(line, roots) { + return line.replace(/(\/[^\s]+\.go:\d+)/g, function (path) { + return shortenPath(path, roots); + }); + } + + // 解析 pre 文本,返回 { header, blocks: [{nodeFunc, bodyLines}], roots } + function parseBlocks(text) { + var lines = text.split('\n'); + var blocks = []; + var current = null; + var headerLines = []; + var inHeader = true; + + for (var i = 0; i < lines.length; i++) { + var line = lines[i]; + if (SEPARATOR_RE.test(line)) { + if (current !== null) { + blocks.push(current); + current = null; + } + // legend 行之前的 separator:头部 + if (inHeader && i + 1 < lines.length && lines[i + 1].indexOf('flat') !== -1) { + inHeader = false; + headerLines.push(line); + continue; + } + if (inHeader) { + headerLines.push(line); + continue; + } + // 开始新块 + current = { nodeFunc: '', bodyLines: [] }; + continue; + } + if (inHeader) { + headerLines.push(line); + continue; + } + if (current === null) continue; + + if (isNodeLine(line)) { + current.nodeFunc = extractNodeName(line); + } + current.bodyLines.push(line); + } + + var roots = discoverRoots(lines); + return { header: headerLines.join('\n'), blocks: blocks, roots: roots }; + } + + // 构建折叠块 DOM(保持等宽字体格式) + function buildBlock(nodeFunc, bodyLines, folded, roots, config) { + var wrapper = document.createElement('div'); + wrapper.setAttribute('data-prof-plugin', 'peek-fold'); + wrapper.style.cssText = 'margin:2px 0;font-family:monospace;font-size:13px;'; + + var title = document.createElement('div'); + title.setAttribute('data-prof-plugin', 'peek-fold'); + title.setAttribute('data-folded', folded ? 'true' : 'false'); + title.style.cssText = [ + 'cursor:pointer', + 'padding:1px 4px', + 'background:#f5f5f5', + 'border-left:3px solid #ccc', + 'white-space:pre', + 'overflow:hidden', + 'text-overflow:ellipsis', + ].join(';'); + + var indicator = document.createElement('span'); + indicator.className = 'prof-peek-indicator'; + indicator.style.cssText = 'margin-right:6px;color:#888;font-style:normal;'; + indicator.textContent = folded ? '▶' : '▼'; + + var funcLabel = document.createElement('span'); + var enableShorten = config.shortenPaths !== false && roots; + var displayFunc = enableShorten ? shortenLine(nodeFunc || '', roots) : (nodeFunc || ''); + funcLabel.textContent = displayFunc || '(unknown)'; + + title.appendChild(indicator); + title.appendChild(funcLabel); + + var body = document.createElement('pre'); + body.setAttribute('data-prof-plugin', 'peek-fold'); + body.style.cssText = [ + 'margin:0', + 'padding:2px 4px 2px 16px', + 'border-left:3px solid #eee', + 'background:#fafafa', + 'display:' + (folded ? 'none' : 'block'), + 'font-family:monospace', + 'font-size:13px', + ].join(';'); + var displayLines = enableShorten + ? bodyLines.map(function (l) { return shortenLine(l, roots); }) + : bodyLines; + body.textContent = displayLines.join('\n'); + + title.addEventListener('click', function () { + var isFolded = title.getAttribute('data-folded') === 'true'; + var next = !isFolded; + title.setAttribute('data-folded', next ? 'true' : 'false'); + body.style.display = next ? 'none' : 'block'; + indicator.textContent = next ? '▶' : '▼'; + }); + + wrapper.appendChild(title); + wrapper.appendChild(body); + return wrapper; + } + + // 注入工具栏(全部折叠 / 全部展开) + function injectToolbar(container, titleNodes) { + var toolbar = document.createElement('div'); + toolbar.setAttribute('data-prof-plugin', 'peek-fold'); + toolbar.style.cssText = 'padding:4px 0 8px 0;display:flex;gap:8px;'; + + function makeBtn(text, action) { + var btn = document.createElement('button'); + btn.textContent = text; + btn.setAttribute('data-prof-plugin', 'peek-fold'); + btn.style.cssText = [ + 'padding:2px 10px', + 'font-size:12px', + 'cursor:pointer', + 'border:1px solid #ccc', + 'border-radius:3px', + 'background:#f5f5f5', + ].join(';'); + btn.addEventListener('click', action); + return btn; + } + + toolbar.appendChild(makeBtn('全部折叠', function () { + titleNodes.forEach(function (t) { + t.setAttribute('data-folded', 'true'); + t.querySelector('.prof-peek-indicator').textContent = '▶'; + t.nextElementSibling.style.display = 'none'; + }); + })); + toolbar.appendChild(makeBtn('全部展开', function () { + titleNodes.forEach(function (t) { + t.setAttribute('data-folded', 'false'); + t.querySelector('.prof-peek-indicator').textContent = '▼'; + t.nextElementSibling.style.display = 'block'; + }); + })); + container.insertBefore(toolbar, container.firstChild); + return toolbar; + } + + // 清理上次注入 + function cleanup(content) { + content.querySelectorAll('[data-prof-plugin="peek-fold"]').forEach(function (el) { + el.parentNode && el.parentNode.removeChild(el); + }); + var pre = content.querySelector('pre'); + if (pre) pre.style.display = ''; + } + + function run() { + var content = document.getElementById('content'); + if (!content) return; + var pre = content.querySelector('pre'); + if (!pre) return; + // 只在 peek 视图运行 + if (window.location.pathname.indexOf('/peek') === -1) return; + + cleanup(content); + + var text = pre.textContent; + var parsed = parseBlocks(text); + if (parsed.blocks.length === 0) return; + + var config = loadConfig(); + pre.style.display = 'none'; + + // 头部元信息 + var headerPre = document.createElement('pre'); + headerPre.setAttribute('data-prof-plugin', 'peek-fold'); + headerPre.style.cssText = 'margin:0;padding:4px;font-size:13px;font-family:monospace;color:#555;'; + headerPre.textContent = parsed.header; + content.insertBefore(headerPre, pre); + + // 各函数块 + var titleNodes = []; + parsed.blocks.forEach(function (block) { + var folded = shouldFold(block, parsed.roots, config); + var wrapper = buildBlock(block.nodeFunc, block.bodyLines, folded, parsed.roots, config); + content.insertBefore(wrapper, pre); + var titleEl = wrapper.querySelector('[data-folded]'); + if (titleEl) titleNodes.push(titleEl); + }); + + injectToolbar(content, titleNodes); + } + + P.register({ + name: 'peek-fold', + version: '1.0.0', + views: ['peek'], + + init: function () { run(); }, + onViewChange: function (view) { + if (view === 'peek') run(); + }, + }); + +})(window.ProfPlugin); diff --git a/web/static/plugins/settings.js b/web/static/plugins/settings.js new file mode 100644 index 0000000..aad05e7 --- /dev/null +++ b/web/static/plugins/settings.js @@ -0,0 +1,294 @@ +(function () { + 'use strict'; + + // Returns { container, mode } where mode is 'pprof' or 'navbar' + function findHeader() { + var pprofHeader = document.querySelector('.header'); + if (pprofHeader) return { container: pprofHeader, mode: 'pprof' }; + var navbarNav = document.querySelector('.navbar-nav'); + if (navbarNav) return { container: navbarNav, mode: 'navbar' }; + return null; + } + + function init() { + var found = findHeader(); + if (!found) return; + + var container = found.container; + var mode = found.mode; + + // ── Settings button ────────────────────────────────────────────────────── + var btn, btnInner; + if (mode === 'navbar') { + // Bootstrap navbar: inject as a
{{template "storageKeys" .}} + + From 1b0b4a0d7c5badf1e0721b81f2d21c6e0c49503d Mon Sep 17 00:00:00 2001 From: matteo Date: Mon, 20 Apr 2026 00:05:50 +0800 Subject: [PATCH 8/8] plug --- web/static/i18n/en.json | 97 ++++++++++++++++++++++ web/static/i18n/zh.json | 97 ++++++++++++++++++++++ web/static/plugins/settings.js | 37 ++++++--- web/static/prof-i18n.js | 79 ++++++++++++++++++ web/template/index.html | 147 +++++++++++++++++---------------- web/template/list.html | 25 +++--- 6 files changed, 386 insertions(+), 96 deletions(-) create mode 100644 web/static/i18n/en.json create mode 100644 web/static/i18n/zh.json create mode 100644 web/static/prof-i18n.js diff --git a/web/static/i18n/en.json b/web/static/i18n/en.json new file mode 100644 index 0000000..a2b9117 --- /dev/null +++ b/web/static/i18n/en.json @@ -0,0 +1,97 @@ +{ + "nav.home": "Home", + "nav.files": "Files", + "nav.history": "History", + + "card.fetchOne": "Fetch One", + "card.fetchUrl": "Fetch URL", + "card.upload": "Upload File", + "card.fetchBatch": "Fetch Batch", + + "label.baseUrl": "Base URL", + "label.url": "URL", + "label.file": "File", + "label.type": "Type", + "label.seconds": "Seconds", + + "hint.baseUrl": "No type suffix, no trailing slash", + "hint.fullUrl": "Full URL including type and params", + "hint.uploadFile": "Upload a .pprof or .trace file", + "hint.urlPreview": "URL Preview", + + "btn.tryDemo": "Try Demo", + "btn.submit": "Submit", + "btn.getCurl": "Get curl", + "btn.loading": "Loading...", + "btn.copy": "Copy", + "btn.close": "Close", + + "scene.label": "Scene Templates", + "scene.cpu": "CPU Analysis", + "scene.mem": "Memory Analysis", + "scene.concurrency": "Concurrency Analysis", + "scene.all": "Collect All", + + "type.label": "Profile Types", + "type.sampling": "Sampling:", + "type.snapshot": "Snapshot:", + + "modal.curlScript": "Curl Script", + + "err.enterUrl": "Please enter a URL", + "fetching": "Fetching... ", + + "diff.compare": "Diff", + "diff.clear": "Clear", + "diff.selectSecond": "— Select a second .pprof file", + "diff.selected": "✓ Selected", + "diff.addCompare": "+ Compare", + "diff.vs": "vs", + + "list.directories": "Directories", + "list.files": "Files", + + "goroutine.modeLabel": "Output Mode", + "goroutine.modePprof": "pprof format", + "goroutine.modeText": "Text summary", + "goroutine.modeFull": "Full dump", + "goroutine.stwWarn": "⚠ Triggers Stop-The-World, use with caution for large goroutine counts", + + "heap.modeLabel": "Collection Mode", + "heap.snapshot": "Snapshot", + "heap.gcSnapshot": "GC + Snapshot", + "heap.delta": "Delta", + + "allocs.modeLabel": "Collection Mode", + "allocs.snapshot": "Snapshot", + "allocs.delta": "Delta", + + "profile.durationLabel": "Duration", + "trace.durationLabel": "Duration", + "trace.hint": "Note: view result with go tool trace, not pprof", + + "block.prereqWarn": "⚠️ Prerequisite: target must call runtime.SetBlockProfileRate(rate), otherwise empty result", + "mutex.prereqWarn": "⚠️ Prerequisite: target must call runtime.SetMutexProfileFraction(rate), otherwise empty result", + + "threadcreate.hint": "Snapshot → threadcreate (OS thread creation stacks, usually small)", + "cmdline.hint": "No params, returns command-line arguments", + "symbol.hint": "No params, returns symbol table (usually called automatically by pprof)", + + "settings.title": "Prof Plugins", + "settings.reload": "Click to reload", + "settings.noPlugins": "No plugins", + + "plugin.i18n-zh": "Chinese UI Localization", + "plugin.source-fold": "Source View Fold", + "plugin.peek-fold": "Peek View Fold", + "plugin.graph-explain": "Graph Node Explainer", + + "source-fold.collapseStdlib": "Collapse std (stdlib)", + "source-fold.collapseThirdParty": "Collapse mod (third-party)", + "source-fold.collapseAll": "Collapse all", + + "peek-fold.collapseStd": "Collapse std (stdlib)", + "peek-fold.collapseMod": "Collapse mod (third-party)", + "peek-fold.collapseAll": "Collapse all", + "peek-fold.shortenPaths": "Shorten paths (std/ mod/)" +} diff --git a/web/static/i18n/zh.json b/web/static/i18n/zh.json new file mode 100644 index 0000000..6681f12 --- /dev/null +++ b/web/static/i18n/zh.json @@ -0,0 +1,97 @@ +{ + "nav.home": "主页", + "nav.files": "文件", + "nav.history": "历史", + + "card.fetchOne": "单次采集", + "card.fetchUrl": "手动 URL", + "card.upload": "上传文件", + "card.fetchBatch": "批量采集", + + "label.baseUrl": "Base URL", + "label.url": "URL", + "label.file": "文件", + "label.type": "类型", + "label.seconds": "Seconds", + + "hint.baseUrl": "不含类型名,末尾无斜杠", + "hint.fullUrl": "完整 URL,含类型和参数", + "hint.uploadFile": "上传 .pprof 或 .trace 文件", + "hint.urlPreview": "URL 预览", + + "btn.tryDemo": "试一试", + "btn.submit": "提交", + "btn.getCurl": "获取 curl", + "btn.loading": "加载中...", + "btn.copy": "复制", + "btn.close": "关闭", + + "scene.label": "场景模板", + "scene.cpu": "CPU 分析", + "scene.mem": "内存分析", + "scene.concurrency": "并发分析", + "scene.all": "全量采集", + + "type.label": "采集类型", + "type.sampling": "采样:", + "type.snapshot": "快照:", + + "modal.curlScript": "Curl 脚本", + + "err.enterUrl": "请输入 URL", + "fetching": "采集中... ", + + "diff.compare": "Diff 对比", + "diff.clear": "清除", + "diff.selectSecond": "— 再去选第二个 .pprof 文件", + "diff.selected": "✓ 已选", + "diff.addCompare": "+ 对比", + "diff.vs": "vs", + + "list.directories": "目录", + "list.files": "文件", + + "goroutine.modeLabel": "输出模式", + "goroutine.modePprof": "pprof 格式", + "goroutine.modeText": "文本摘要", + "goroutine.modeFull": "完整 dump", + "goroutine.stwWarn": "⚠ 会触发 Stop-The-World,goroutine 数量大时请谨慎", + + "heap.modeLabel": "采集模式", + "heap.snapshot": "快照", + "heap.gcSnapshot": "GC 后快照", + "heap.delta": "Delta", + + "allocs.modeLabel": "采集模式", + "allocs.snapshot": "快照", + "allocs.delta": "Delta", + + "profile.durationLabel": "采集时长", + "trace.durationLabel": "采集时长", + "trace.hint": "提示:结果用 go tool trace 查看,不同于 pprof", + + "block.prereqWarn": "⚠️ 前置条件:目标程序需调用 runtime.SetBlockProfileRate(rate),否则采集结果为空文件", + "mutex.prereqWarn": "⚠️ 前置条件:目标程序需调用 runtime.SetMutexProfileFraction(rate),否则采集结果为空文件", + + "threadcreate.hint": "快照 → threadcreate(OS 线程创建调用栈,通常较小)", + "cmdline.hint": "无参数,直接采集命令行参数", + "symbol.hint": "无参数,返回符号表(通常由 pprof 自动调用)", + + "settings.title": "Prof 插件", + "settings.reload": "点击刷新生效", + "settings.noPlugins": "暂无插件", + + "plugin.i18n-zh": "界面中文汉化", + "plugin.source-fold": "Source 视图函数折叠", + "plugin.peek-fold": "Peek 视图分组折叠", + "plugin.graph-explain": "Graph 节点点击解释", + + "source-fold.collapseStdlib": "折叠 std(标准库)", + "source-fold.collapseThirdParty": "折叠 mod(第三方)", + "source-fold.collapseAll": "折叠全部", + + "peek-fold.collapseStd": "折叠 std(标准库)", + "peek-fold.collapseMod": "折叠 mod(第三方)", + "peek-fold.collapseAll": "折叠全部", + "peek-fold.shortenPaths": "缩短路径显示(std/ mod/)" +} diff --git a/web/static/plugins/settings.js b/web/static/plugins/settings.js index aad05e7..58aee36 100644 --- a/web/static/plugins/settings.js +++ b/web/static/plugins/settings.js @@ -1,6 +1,21 @@ (function () { 'use strict'; + var _settingsI18n = {}; + (function () { + var lang = localStorage.getItem('prof-lang') || 'zh'; + var xhr = new XMLHttpRequest(); + xhr.open('GET', '/static/i18n/' + lang + '.json', false); // async=false intentional: local tool + try { + xhr.send(); + if (xhr.status === 200) _settingsI18n = JSON.parse(xhr.responseText); + } catch (e) {} + })(); + + function st(key, fallback) { + return _settingsI18n[key] !== undefined ? _settingsI18n[key] : fallback; + } + // Returns { container, mode } where mode is 'pprof' or 'navbar' function findHeader() { var pprofHeader = document.querySelector('.header'); @@ -97,12 +112,12 @@ } function renderPanel(panel, plugins) { - panel.innerHTML = '
Prof 插件
'; + panel.innerHTML = '
' + st('settings.title', 'Prof 插件') + '
'; if (plugins.length === 0) { var empty = document.createElement('div'); empty.style.cssText = 'color:#999;font-size:12px;'; - empty.textContent = '暂无插件'; + empty.textContent = st('settings.noPlugins', '暂无插件'); panel.appendChild(empty); return; } @@ -116,7 +131,7 @@ row.style.cssText = 'display:flex;justify-content:space-between;align-items:center;margin:6px 0;gap:12px;'; var label = document.createElement('span'); - label.textContent = p.description || p.name; + label.textContent = st('plugin.' + p.name, p.description || p.name); label.style.cssText = 'flex:1;'; var toggle = document.createElement('input'); @@ -195,15 +210,15 @@ localStorage.setItem(configKey, JSON.stringify(cfg)); } - container.appendChild(makeSubRow('折叠 std(标准库)', cfg.collapseStdlib, function (v) { + container.appendChild(makeSubRow(st('source-fold.collapseStdlib', '折叠 std(标准库)'), cfg.collapseStdlib, function (v) { cfg.collapseStdlib = v; saveConfig(); })); - container.appendChild(makeSubRow('折叠 mod(第三方)', cfg.collapseThirdParty, function (v) { + container.appendChild(makeSubRow(st('source-fold.collapseThirdParty', '折叠 mod(第三方)'), cfg.collapseThirdParty, function (v) { cfg.collapseThirdParty = v; saveConfig(); })); - container.appendChild(makeSubRow('折叠全部', cfg.collapseAll, function (v) { + container.appendChild(makeSubRow(st('source-fold.collapseAll', '折叠全部'), cfg.collapseAll, function (v) { cfg.collapseAll = v; saveConfig(); })); @@ -248,19 +263,19 @@ localStorage.setItem(configKey, JSON.stringify(cfg)); } - container.appendChild(makeSubRow('折叠 std(标准库)', cfg.collapseStd, function (v) { + container.appendChild(makeSubRow(st('peek-fold.collapseStd', '折叠 std(标准库)'), cfg.collapseStd, function (v) { cfg.collapseStd = v; saveConfig(); })); - container.appendChild(makeSubRow('折叠 mod(第三方)', cfg.collapseMod, function (v) { + container.appendChild(makeSubRow(st('peek-fold.collapseMod', '折叠 mod(第三方)'), cfg.collapseMod, function (v) { cfg.collapseMod = v; saveConfig(); })); - container.appendChild(makeSubRow('折叠全部', cfg.collapseAll, function (v) { + container.appendChild(makeSubRow(st('peek-fold.collapseAll', '折叠全部'), cfg.collapseAll, function (v) { cfg.collapseAll = v; saveConfig(); })); - container.appendChild(makeSubRow('缩短路径显示(std/ mod/)', cfg.shortenPaths, function (v) { + container.appendChild(makeSubRow(st('peek-fold.shortenPaths', '缩短路径显示(std/ mod/)'), cfg.shortenPaths, function (v) { cfg.shortenPaths = v; saveConfig(); })); @@ -281,7 +296,7 @@ 'cursor:pointer', 'text-align:center', ].join(';'); - hint.textContent = '点击刷新生效'; + hint.textContent = st('settings.reload', '点击刷新生效'); hint.addEventListener('click', function () { location.reload(); }); panel.appendChild(hint); } diff --git a/web/static/prof-i18n.js b/web/static/prof-i18n.js new file mode 100644 index 0000000..e8ad91d --- /dev/null +++ b/web/static/prof-i18n.js @@ -0,0 +1,79 @@ +(function () { + 'use strict'; + + var DEFAULT_LANG = 'zh'; + var LANG_KEY = 'prof-lang'; + + var lang = localStorage.getItem(LANG_KEY) || DEFAULT_LANG; + var translations = {}; + + function loadTranslations(l) { + var xhr = new XMLHttpRequest(); + xhr.open('GET', '/static/i18n/' + l + '.json', false); // async=false intentional: local tool + try { + xhr.send(); + if (xhr.status === 200) return JSON.parse(xhr.responseText); + } catch (e) {} + return {}; + } + + translations = loadTranslations(lang); + + window.t = function (key) { + return translations[key] !== undefined ? translations[key] : key; + }; + + window.ProfI18n = { + lang: lang, + t: window.t, + setLang: function (newLang) { + localStorage.setItem(LANG_KEY, newLang); + location.reload(); + }, + getLang: function () { return lang; }, + }; + + function applyTranslations() { + document.querySelectorAll('[data-i18n]').forEach(function (el) { + var key = el.getAttribute('data-i18n'); + if (translations[key] !== undefined) el.textContent = translations[key]; + }); + document.querySelectorAll('[data-i18n-placeholder]').forEach(function (el) { + var key = el.getAttribute('data-i18n-placeholder'); + if (translations[key] !== undefined) el.placeholder = translations[key]; + }); + } + + function injectSwitcher() { + var nav = document.querySelector('.navbar-nav'); + if (!nav) return; + if (document.getElementById('prof-lang-switcher')) return; + + var li = document.createElement('li'); + li.className = 'nav-item'; + li.id = 'prof-lang-switcher'; + li.style.cssText = 'cursor:pointer;'; + + var a = document.createElement('a'); + a.className = 'nav-link'; + a.style.cssText = 'user-select:none;'; + a.textContent = lang === 'zh' ? 'EN' : '中'; + a.title = lang === 'zh' ? 'Switch to English' : '切换为中文'; + a.addEventListener('click', function () { + ProfI18n.setLang(lang === 'zh' ? 'en' : 'zh'); + }); + + li.appendChild(a); + nav.appendChild(li); + } + + if (document.readyState === 'loading') { + document.addEventListener('DOMContentLoaded', function () { + applyTranslations(); + injectSwitcher(); + }); + } else { + applyTranslations(); + injectSwitcher(); + } +})(); diff --git a/web/template/index.html b/web/template/index.html index 4f9addf..f361a39 100644 --- a/web/template/index.html +++ b/web/template/index.html @@ -5,6 +5,7 @@ Prof +