Skip to content
Myr

perf(recovery): optimize line reading in stack function (#4466)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Name · committed by GitHub · parent 19b877f · Browse files · 2 files+89 added−30 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Trailers

  • Co-authored-by: 1911860538 <alxps1911@gmail.com>

Diff stats

2 files+89 added−30 removed

  • other:+89 added−30 removed

2 files+89 added−30 removed

modified:recovery_test.go+50 added-15 removed
86 unmodified lines
87 // TEST88 assert.Equal(t, http.StatusBadRequest, w.Code)89}9091func TestSource(t *testing.T) {92 bs := source(nil, 0)93 assert.Equal(t, dunnoBytes, bs)9495 in := [][]byte{96 []byte("Hello world."),97 []byte("Hi, gin.."),98 }99 bs = source(in, 10)100 assert.Equal(t, dunnoBytes, bs)101102 bs = source(in, 1)103 assert.Equal(t, []byte("Hello world."), bs)104}10591func TestFunction(t *testing.T) {92 bs := function(1)93 assert.Equal(t, dunno, bs)94}
220 unmodified lines
315 }316 })317 }318}319320// TestReadNthLine tests the readNthLine function with various scenarios.321func TestReadNthLine(t *testing.T) {322 // Create a temporary test file323 testContent := "line 0 \n line 1 \nline 2 \nline 3 \nline 4"324 tempFile, err := os.CreateTemp("", "testfile*.txt")325 if err != nil {326 t.Fatal(err)327 }328 defer os.Remove(tempFile.Name())329330 // Write test content to the temporary file331 if _, err := tempFile.WriteString(testContent); err != nil {332 t.Fatal(err)333 }334 if err := tempFile.Close(); err != nil {335 t.Fatal(err)336 }337338 // Test cases339 tests := []struct {340 name string341 lineNum int342 fileName string343 want string344 wantErr bool345 }{346 {name: "Read first line", lineNum: 0, fileName: tempFile.Name(), want: "line 0", wantErr: false},347 {name: "Read middle line", lineNum: 2, fileName: tempFile.Name(), want: "line 2", wantErr: false},348 {name: "Read last line", lineNum: 4, fileName: tempFile.Name(), want: "line 4", wantErr: false},349 {name: "Line number exceeds file length", lineNum: 10, fileName: tempFile.Name(), want: "", wantErr: false},350 {name: "Negative line number", lineNum: -1, fileName: tempFile.Name(), want: "", wantErr: false},351 {name: "Non-existent file", lineNum: 1, fileName: "/non/existent/file.txt", want: "", wantErr: true},352 }353354 for _, tt := range tests {355 t.Run(tt.name, func(t *testing.T) {356 got, err := readNthLine(tt.fileName, tt.lineNum)357 assert.Equal(t, tt.wantErr, err != nil)358 assert.Equal(t, tt.want, got)359 })360 }361}362363func BenchmarkStack(b *testing.B) {364 b.ReportAllocs()365 for b.Loop() {366 _ = stack(stackSkip)367 }368}
modified:recovery.go+39 added-15 removed
3 unmodified lines
45package gin67import (8 "bufio"9 "bytes"10 "cmp"11 "errors"12 "fmt"13 "io"14 "log"
7 unmodified lines
2223 "github.com/gin-gonic/gin/internal/bytesconv"24)2524const dunno = "???"26const (27 dunno = "???"28 stackSkip = 329)3026var dunnoBytes = []byte(dunno)2731// RecoveryFunc defines the function passable to CustomRecovery.32type RecoveryFunc func(c *Context, err any)3334// Recovery returns a middleware that recovers from any panics and writes a 500 if there was one.
39 unmodified lines
74 if e, ok := err.(error); ok && errors.Is(e, http.ErrAbortHandler) {75 brokenPipe = true76 }77 if logger != nil {75 const stackSkip = 378 if brokenPipe {79 logger.Printf("%s\n%s%s", err, secureRequestDump(c.Request), reset)80 } else if IsDebugging() {81 logger.Printf("[Recovery] %s panic recovered:\n%s\n%s\n%s%s",
39 unmodified lines
121func stack(skip int) []byte {122 buf := new(bytes.Buffer) // the returned data123 // As we loop, we open files and read them. These variables record the currently124 // loaded file.123 var lines [][]byte124 var lastFile string125 var (126 nLine string127 lastFile string128 err error129 )130 for i := skip; ; i++ { // Skip the expected number of frames131 pc, file, line, ok := runtime.Caller(i)132 if !ok {133 break134 }135 // Print this much at least. If we can't find the source, it won't show.136 fmt.Fprintf(buf, "%s:%d (0x%x)\n", file, line, pc)137 if file != lastFile {133 data, err := os.ReadFile(file)138 nLine, err = readNthLine(file, line-1)139 if err != nil {140 continue141 }137 lines = bytes.Split(data, []byte{'\n'})142 lastFile = file143 }140 fmt.Fprintf(buf, "\t%s: %s\n", function(pc), source(lines, line))144 fmt.Fprintf(buf, "\t%s: %s\n", function(pc), cmp.Or(nLine, dunno))145 }146 return buf.Bytes()147}148145// source returns a space-trimmed slice of the n'th line.146func source(lines [][]byte, n int) []byte {147 n-- // in stack trace, lines are 1-indexed but our array is 0-indexed148 if n < 0 || n >= len(lines) {149 return dunnoBytes149// readNthLine reads the nth line from the file.150// It returns the trimmed content of the line if found,151// or an empty string if the line doesn't exist.152// If there's an error opening the file, it returns the error.153func readNthLine(file string, n int) (string, error) {154 if n < 0 {155 return "", nil156 }151 return bytes.TrimSpace(lines[n])157158 f, err := os.Open(file)159 if err != nil {160 return "", err161 }162 defer f.Close()163164 scanner := bufio.NewScanner(f)165 for i := 0; i < n; i++ {166 if !scanner.Scan() {167 return "", nil168 }169 }170171 if scanner.Scan() {172 return strings.TrimSpace(scanner.Text()), nil173 }174175 return "", nil176}177178// function returns, if possible, the name of the function containing the PC.179func function(pc uintptr) string {
27 unmodified lines