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
|
package flamegraph
import (
"context"
"encoding/json"
"fmt"
"net/http"
"time"
)
// ServeLive starts the live flamegraph HTTP server and blocks until ctx is canceled.
func ServeLive(ctx context.Context, lt *LiveTrie, interval time.Duration) error {
mux := http.NewServeMux()
mux.HandleFunc("/", handleLivePage())
mux.HandleFunc("/events", handleSSE(lt, interval))
mux.HandleFunc("/reset", handleReset(lt))
mux.HandleFunc("/order", handleOrder(lt))
srv := &http.Server{Handler: mux}
listener, err := listenRandomPort()
if err != nil {
return err
}
defer listener.Close()
hostname, port := serverHostPort(listener)
fmt.Printf("Live flamegraph available at http://%s:%d/\n", hostname, port)
errCh := make(chan error, 1)
go func() {
errCh <- srv.Serve(listener)
}()
select {
case <-ctx.Done():
case serveErr := <-errCh:
if serveErr != nil && serveErr != http.ErrServerClosed {
return serveErr
}
return nil
}
shutdownCtx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
if err := srv.Shutdown(shutdownCtx); err != nil {
return fmt.Errorf("shutdown live web server: %w", err)
}
serveErr := <-errCh
if serveErr != nil && serveErr != http.ErrServerClosed {
return serveErr
}
return nil
}
func handleLivePage() http.HandlerFunc {
return func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
_, _ = w.Write([]byte(liveHTML))
}
}
func handleSSE(lt *LiveTrie, interval time.Duration) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
flusher, ok := w.(http.Flusher)
if !ok {
http.Error(w, "streaming unsupported", http.StatusInternalServerError)
return
}
if interval <= 0 {
interval = 200 * time.Millisecond
}
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
lastVersion, err := sendSnapshot(w, flusher, lt, ^uint64(0))
if err != nil {
return
}
ticker := time.NewTicker(interval)
defer ticker.Stop()
for {
select {
case <-r.Context().Done():
return
case <-ticker.C:
if lt.Version() == lastVersion {
continue
}
lastVersion, err = sendSnapshot(w, flusher, lt, lastVersion)
if err != nil {
return
}
}
}
}
}
func handleReset(lt *LiveTrie) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
w.Header().Set("Allow", http.MethodPost)
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
lt.Reset()
payload, _ := lt.SnapshotJSON()
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write(payload)
}
}
type orderRequest struct {
Fields []string `json:"fields"`
}
type orderResponse struct {
Fields []string `json:"fields"`
Snapshot json.RawMessage `json:"snapshot,omitempty"`
}
func handleOrder(lt *LiveTrie) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(orderResponse{Fields: lt.Fields()})
case http.MethodPost:
var req orderRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "invalid json body", http.StatusBadRequest)
return
}
if err := lt.Reconfigure(req.Fields); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
snap, _ := lt.SnapshotJSON()
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(orderResponse{
Fields: lt.Fields(),
Snapshot: snap,
})
default:
w.Header().Set("Allow", http.MethodGet+", "+http.MethodPost)
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
}
}
}
func sendSnapshot(w http.ResponseWriter, flusher http.Flusher, lt *LiveTrie, lastVersion uint64) (uint64, error) {
payload, version := lt.SnapshotJSON()
if version == lastVersion {
return lastVersion, nil
}
if _, err := fmt.Fprintf(w, "data: %s\n\n", payload); err != nil {
return lastVersion, err
}
flusher.Flush()
return version, nil
}
|