-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.go
More file actions
279 lines (236 loc) · 5.51 KB
/
stack.go
File metadata and controls
279 lines (236 loc) · 5.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
package errdef
import (
"bufio"
"encoding/json"
"errors"
"fmt"
"iter"
"log/slog"
"os"
"runtime"
"slices"
"strconv"
"strings"
"sync"
)
type (
// Stack represents a stack trace captured when an error was created.
Stack interface {
// Frames returns the stack trace as structured frame information.
Frames() []Frame
// HeadFrame returns the top frame of the stack trace.
HeadFrame() (Frame, bool)
// FramesAndSource returns an iterator that yields frames and their source code snippets.
// Source code will be empty string if not available or if the frame exceeds the configured depth.
FramesAndSource() iter.Seq2[Frame, string]
// Len returns the number of frames in the stack trace.
Len() int
// IsZero returns true if the stack trace is empty.
IsZero() bool
}
// Frame represents a single frame in a stack trace.
Frame struct {
Func string `json:"func"`
File string `json:"file"`
Line int `json:"line"`
}
stack struct {
pcs []uintptr
sourceLines int
sourceDepth int
}
)
const (
callersDepth = 32
// callersSkip is the number of skip frames when using the Definition methods.
// 4 frames: runtime.Callers, newStack, newError, and the Definition methods.
callersSkip = 4
)
var (
_ Stack = (*stack)(nil)
_ StackTracer = (*stack)(nil)
_ json.Marshaler = (*stack)(nil)
_ slog.LogValuer = (*stack)(nil)
_ slog.LogValuer = Frame{}
)
var (
sourceAvailable *bool
sourceAvailableMu sync.Mutex
sourceFileCache = make(map[string][]string)
sourceFileCacheMu sync.RWMutex
)
func newStack(depth int, skip int, sourceLines int, sourceDepth int) *stack {
pcs := make([]uintptr, depth)
n := runtime.Callers(skip, pcs)
return &stack{
pcs: pcs[:n],
sourceLines: sourceLines,
sourceDepth: sourceDepth,
}
}
func (s *stack) Frames() []Frame {
if s == nil || len(s.pcs) == 0 {
return nil
}
fs := runtime.CallersFrames(s.pcs)
frames := make([]Frame, 0, len(s.pcs))
for {
f, more := fs.Next()
frames = append(frames, Frame{
Func: f.Function,
File: f.File,
Line: f.Line,
})
if !more {
break
}
}
return frames
}
func (s *stack) HeadFrame() (Frame, bool) {
if s == nil || len(s.pcs) == 0 {
return Frame{}, false
}
fs := runtime.CallersFrames(s.pcs)
f, _ := fs.Next()
frame := Frame{
Func: f.Function,
File: f.File,
Line: f.Line,
}
return frame, true
}
func (s *stack) FramesAndSource() iter.Seq2[Frame, string] {
return func(yield func(Frame, string) bool) {
if s == nil || len(s.pcs) == 0 {
return
}
frames := s.Frames()
for i, frame := range frames {
var source string
if s.sourceLines > 0 && frame.File != "" {
if s.sourceDepth == -1 || (s.sourceDepth > 0 && i < s.sourceDepth) {
source = s.frameSource(frame.File, frame.Line)
}
}
if !yield(frame, source) {
return
}
}
}
}
func (s *stack) Len() int {
if s == nil {
return 0
}
return len(s.pcs)
}
func (s *stack) IsZero() bool {
return s == nil || len(s.pcs) == 0
}
func (s *stack) StackTrace() []uintptr {
if s == nil {
return nil
}
return slices.Clone(s.pcs)
}
func (s *stack) MarshalJSON() ([]byte, error) {
return json.Marshal(s.Frames())
}
func (s *stack) LogValue() slog.Value {
return slog.AnyValue(s.Frames())
}
func (s *stack) frameSource(file string, line int) string {
lines := getSourceLines(file, line, s.sourceLines)
if len(lines) == 0 {
return ""
}
start := max(1, line-s.sourceLines)
end := start + len(lines) - 1
width := len(strconv.Itoa(end))
var buf strings.Builder
for i, l := range lines {
lineNum := start + i
prefix := " "
if lineNum == line {
prefix = "> "
}
fmt.Fprintf(&buf, "%s%*d: %s", prefix, width, lineNum, l)
if i < len(lines)-1 {
buf.WriteString("\n")
}
}
return buf.String()
}
func (f Frame) LogValue() slog.Value {
return slog.GroupValue(
slog.String("func", f.Func),
slog.String("file", f.File),
slog.Int("line", f.Line),
)
}
func getSourceLines(file string, line, around int) []string {
lines, err := readSourceFile(file)
if err != nil {
return nil
}
if line < 1 || line > len(lines) {
return nil
}
start := max(0, line-around-1)
end := min(len(lines), line+around)
return lines[start:end]
}
func readSourceFile(path string) ([]string, error) {
if !checkSourceAvailable() {
return nil, os.ErrNotExist
}
if lines, ok := getCachedSourceFile(path); ok {
return lines, nil
}
file, err := os.Open(path)
if err != nil {
if isSourcePermanentError(err) {
markSourceAvailable(false)
}
return nil, err
}
defer func() { _ = file.Close() }()
markSourceAvailable(true)
var lines []string
scanner := bufio.NewScanner(file)
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
if err := scanner.Err(); err != nil {
return nil, err
}
cacheSourceFile(path, lines)
return lines, nil
}
func checkSourceAvailable() bool {
sourceAvailableMu.Lock()
defer sourceAvailableMu.Unlock()
return sourceAvailable == nil || *sourceAvailable
}
func getCachedSourceFile(path string) ([]string, bool) {
sourceFileCacheMu.RLock()
defer sourceFileCacheMu.RUnlock()
lines, ok := sourceFileCache[path]
return lines, ok
}
func markSourceAvailable(available bool) {
sourceAvailableMu.Lock()
defer sourceAvailableMu.Unlock()
if sourceAvailable == nil {
sourceAvailable = &available
}
}
func cacheSourceFile(path string, lines []string) {
sourceFileCacheMu.Lock()
defer sourceFileCacheMu.Unlock()
sourceFileCache[path] = lines
}
func isSourcePermanentError(err error) bool {
return errors.Is(err, os.ErrNotExist) || errors.Is(err, os.ErrPermission)
}