/
main.go
383 lines (344 loc) · 9.12 KB
/
main.go
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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
package trace
import (
_ "embed"
"encoding/json"
"errors"
"fmt"
"html"
"io"
"net/http"
"os"
"os/exec"
"runtime"
"runtime/debug"
"strconv"
"strings"
"syscall"
"time"
"github.com/xhd2015/xgo/support/cmd"
)
func Main(args []string) {
if len(args) == 0 {
fmt.Fprintf(os.Stderr, "requires file\n")
os.Exit(1)
}
file := args[0]
serveFile(file)
}
func serveFile(file string) {
server := http.NewServeMux()
server.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
defer func() {
if e := recover(); e != nil {
stack := debug.Stack()
io.WriteString(w, fmt.Sprintf("<pre>panic: %v\n%s</pre>", e, stack))
}
}()
record, err := parseRecord(file)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
io.WriteString(w, fmt.Sprintf("%v", err))
return
}
w.Header().Set("Content-Type", "text/html")
renderRecordHTML(record, file, w)
})
server.HandleFunc("/openVscodeFile", func(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
file := q.Get("file")
if file == "" {
w.WriteHeader(http.StatusBadRequest)
io.WriteString(w, "no file\n")
return
}
_, err := os.Stat(file)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
io.WriteString(w, err.Error())
return
}
line := q.Get("line")
fileLine := file
if line != "" {
fileLine = file + ":" + line
}
output, err := exec.Command("code", "--goto", fileLine).Output()
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
if exitErr, ok := err.(*exec.ExitError); ok {
w.Write(exitErr.Stderr)
} else {
io.WriteString(w, err.Error())
}
return
}
w.Write(output)
})
var autoIncrPort bool
var port int
portStr := os.Getenv("PORT")
if portStr == "" {
port = 7070
portStr = strconv.Itoa(port)
autoIncrPort = true
}
for {
portErr := make(chan struct{})
go func() {
select {
case <-time.After(500 * time.Millisecond):
case <-portErr:
return
}
url := fmt.Sprintf("http://localhost:%s", portStr)
fmt.Printf("Server listen at %s\n", url)
openCmd := "open"
if runtime.GOOS == "windows" {
openCmd = "explorer"
}
cmd.Run(openCmd, url)
}()
err := http.ListenAndServe(fmt.Sprintf(":%s", portStr), server)
if err == nil {
break
}
close(portErr)
var syscallErr syscall.Errno
if autoIncrPort && errors.As(err, &syscallErr) && syscallErr == syscall.EADDRINUSE {
port++
portStr = strconv.Itoa(port)
continue
}
panic(err)
}
}
//go:embed style.css
var styles string
//go:embed script.js
var script string
//go:embed vscode.svg
var vscodeIconSVG string
func parseRecord(file string) (*RootExport, error) {
data, err := os.ReadFile(file)
if err != nil {
return nil, err
}
var root *RootExport
err = json.Unmarshal(data, &root)
if err != nil {
return nil, err
}
return root, nil
}
func renderRecordHTML(root *RootExport, file string, w io.Writer) {
h := func(s string) {
_, err := io.WriteString(w, s)
if err != nil {
panic(err)
}
_, err = io.WriteString(w, "\n")
if err != nil {
panic(err)
}
}
h(`<!DOCTYPE html>
<html lang="en" style="height: 100%;">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Trace of ` + file + `</title>
</head>
<body style="height: 100%;">
`,
)
h(`<div style="height: 100%;">`)
h(`<style>`)
h(styles)
h(`</style>`)
top := &StackExport{
FuncInfo: &FuncInfoExport{
IdentityName: "<root>",
},
Children: root.Children,
}
h("<script>")
h("window.onload = function(){")
h(" const traces = {}")
h(" const ids = []")
traceIDMapping := make(map[*StackExport]int64)
nextID := int64(1)
var walk func(stack *StackExport)
walk = func(stack *StackExport) {
id := nextID
nextID++
traceIDMapping[stack] = id
stackData, err := marshalStackWithoutChildren(stack)
if err != nil {
stackData = []byte(fmt.Sprintf(`{"error":%q}`, err.Error()))
}
h(fmt.Sprintf(` traces["%d"] = %s`, id, stackData))
h(fmt.Sprintf(` ids.push("%d")`, id))
for _, child := range stack.Children {
walk(child)
}
}
walk(top)
h(script)
h("}")
h("</script>")
h(`<div class="root">`)
h(`<div class="trace-list-root">`)
h(`<div>`)
renderToolbar(h)
h(`</div>`)
// h(fmt.Sprintf(`<ul id="%s" class="trace-list">`, getTraceListID(traceIDMapping[top])))
h(`<ul class="trace-list">`)
add(h, top, traceIDMapping)
h("</ul>")
h(`</div>`)
vscode := vscodeIconSVG
vscode = strings.Replace(vscode, `width="100"`, `width="14"`, 1)
vscode = strings.Replace(vscode, `height="100"`, `height="14"`, 1)
vscode = `<div id="vscode-icon" class="vscode-icon" onclick="onClickVscodeIcon(arguments[0])">` + vscode + `</div>`
h(`<div class="detail">`)
h(`<div id="detail-info">
<div class="label-value"> <label>Pkg:</label> <div id="detail-info-pkg"> </div> </div>
<div class="label-value"> <label>Func:</label> <div id="detail-info-func"> </div> ` + vscode + `</div>
</div>`)
h(`<label>Request</label>`)
h(`<textarea id="detail-request" placeholder="request..."></textarea>`)
h(`<label>Response</label>`)
h(`<textarea id="detail-response" placeholder="response..."></textarea>`)
h("</div>")
h("</div>")
h("</div>")
h(`</body>
</html>`)
}
func renderToolbar(h func(s string)) {
h(fmt.Sprintf(`<div id="toolbar" class="toggle-all-on" onClick="onClickExpandAll(arguments[0])">%s</div>`, svgExpand))
}
func getTraceListID(id int64) string {
return fmt.Sprintf("trace_list_%d", id)
}
const svgIconDown = `<svg stroke="currentColor" fill="currentColor" stroke-width="0" viewBox="0 0 16 16" height="1em" width="1em" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" d="M1.646 4.646a.5.5 0 0 1 .708 0L8 10.293l5.646-5.647a.5.5 0 0 1 .708.708l-6 6a.5.5 0 0 1-.708 0l-6-6a.5.5 0 0 1 0-.708z"></path></svg>`
const svgIconRight = `<svg stroke="currentColor" fill="currentColor" stroke-width="0" viewBox="0 0 16 16" height="1em" width="1em" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" d="M4.646 1.646a.5.5 0 0 1 .708 0l6 6a.5.5 0 0 1 0 .708l-6 6a.5.5 0 0 1-.708-.708L10.293 8 4.646 2.354a.5.5 0 0 1 0-.708z"></path></svg>`
const svgExpand = `<svg stroke="currentColor" fill="currentColor" stroke-width="0" viewBox="0 0 16 16" height="1em" width="1em" xmlns="http://www.w3.org/2000/svg"><path d="M9 9H4v1h5V9z"></path><path fill-rule="evenodd" clip-rule="evenodd" d="M5 3l1-1h7l1 1v7l-1 1h-2v2l-1 1H3l-1-1V6l1-1h2V3zm1 2h4l1 1v4h2V3H6v2zm4 1H3v7h7V6z"></path></svg>`
func makeSvg(svg string, extra string) string {
if extra == "" {
return svg
}
mark := "<svg "
idx := strings.Index(svg, "<svg ")
if idx < 0 {
panic(fmt.Errorf("<svg not found"))
}
return svg[:idx+len(mark)] + extra + " " + svg[idx+len(mark):]
}
func marshalStackWithoutChildren(stack *StackExport) ([]byte, error) {
s := stack.Children
stack.Children = nil
defer func() {
stack.Children = s
}()
return json.Marshal(stack)
}
const allowPkgName = false
func add(h func(string), stack *StackExport, traceIDMapping map[*StackExport]int64) {
var name string
if stack.FuncInfo != nil {
name = stack.FuncInfo.IdentityName
if stack.FuncInfo.Pkg != "" && allowPkgName {
name = lastPart(stack.FuncInfo.Pkg) + "." + name
}
}
if name == "" {
name = "<unknown>"
}
id := traceIDMapping[stack]
var indicator string
if len(stack.Children) > 0 {
// NOTE: onclick on svg does not work, must wrap it with div
makeIcon := func(status string, down string, right string) string {
svgDown := makeSvg(down, `class="toggle-icon-down"`)
svgRight := makeSvg(right, `class="toggle-icon-right"`)
toggleID := fmt.Sprintf("toggle_%d", id)
return fmt.Sprintf(`<div id="%s" class="toggle %s" onclick="onClickToggle(arguments[0],'%d')">%s%s</div>`, toggleID, status, id, svgDown, svgRight)
}
indicator = makeIcon("down", svgIconDown, svgIconRight)
}
headClass := "head-block"
if stack.Panic {
headClass = headClass + " panic"
}
if stack.Error != "" {
headClass = headClass + " error"
}
h(fmt.Sprintf(`<div class="head">
%s
<div class="head-info" id="head_%d" onclick="onClickHead('%d')">
<div class="%s"></div>
<span class="head-name">%s</span>
<span class="head-cost">%s</span>
</div>
</div>
`,
indicator,
id, id,
headClass,
html.EscapeString(name),
formatCost(stack.Begin, stack.End),
))
if len(stack.Children) == 0 {
return
}
h(fmt.Sprintf(`<ul id="%s" class="trace-sub-list">`, getTraceListID(id)))
for _, child := range stack.Children {
h("<li>")
add(h, child, traceIDMapping)
h("</li>")
}
h("</ul>")
}
func lastPart(pkg string) string {
idx := strings.LastIndex(pkg, "/")
if idx < 0 {
return pkg
}
return pkg[idx+1:]
}
func formatCost(begin int64, end int64) string {
if end == 0 && begin == 0 {
return ""
}
cost := end - begin
var sign string
if cost < 0 {
sign = "-"
cost = -cost
}
type unit struct {
name string
scaleLast int
}
var units = []unit{
{"ns", 1},
{"μs", 1000},
{"ms", 1000},
{"s", 1000},
{"m", 60},
{"h", 60},
{"d", 24},
}
unitName := units[0].name
f := float64(cost)
for i := 1; i < len(units); i++ {
x := float64(units[i].scaleLast)
if f < x {
break
}
f = f / x
unitName = units[i].name
}
return fmt.Sprintf("%s%d%s", sign, int(f), unitName)
}