Debian Codegraph @

gopls/internal/debug/rpc.go

raw symbols SCIP
1 // Copyright 2019 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package debug
6
7 import (
8 "context"
9 "fmt"
10 "html/template"
11 "net/http"
12 "sort"
13 "sync"
14 "time"
15
16 "golang.org/x/tools/internal/event"
17 "golang.org/x/tools/internal/event/core"
18 "golang.org/x/tools/internal/event/export"
19 "golang.org/x/tools/internal/event/label"
20 "golang.org/x/tools/internal/jsonrpc2"
21 )
22
23 var RPCTmpl = template.Must(template.Must(BaseTemplate.Clone()).Parse(`
24 {{define "title"}}RPC Information{{end}}
25 {{define "body"}}
26 <H2>Inbound</H2>
27 {{template "rpcSection" .Inbound}}
28 <H2>Outbound</H2>
29 {{template "rpcSection" .Outbound}}
30 {{end}}
31 {{define "rpcSection"}}
32 {{range .}}<P>
33 <b>{{.Method}}</b> {{.Started}} <a href="/trace/{{.Method}}">traces</a> ({{.InProgress}} in progress)
34 <br>
35 <i>Latency</i> {{with .Latency}}{{.Mean}} ({{.Min}}<{{.Max}}){{end}}
36 <i>By bucket</i> 0s {{range .Latency.Values}}{{if gt .Count 0}}<b>{{.Count}}</b> {{.Limit}} {{end}}{{end}}
37 <br>
38 <i>Received</i> {{.Received}} (avg. {{.ReceivedMean}})
39 <i>Sent</i> {{.Sent}} (avg. {{.SentMean}})
40 <br>
41 <i>Result codes</i> {{range .Codes}}{{.Key}}={{.Count}} {{end}}
42 </P>
43 {{end}}
44 {{end}}
45 `))
46
47 type Rpcs struct { // exported for testing
48 mu sync.Mutex
49 Inbound []*rpcStats // stats for incoming lsp rpcs sorted by method name
50 Outbound []*rpcStats // stats for outgoing lsp rpcs sorted by method name
51 }
52
53 type rpcStats struct {
54 Method string
55 Started int64
56 Completed int64
57
58 Latency rpcTimeHistogram
59 Received byteUnits
60 Sent byteUnits
61 Codes []*rpcCodeBucket
62 }
63
64 type rpcTimeHistogram struct {
65 Sum time.Duration
66 Count int64
67 Min time.Duration
68 Max time.Duration
69 Values []rpcTimeBucket
70 }
71
72 type rpcTimeBucket struct {
73 Limit time.Duration
74 Count int64
75 }
76
77 type rpcCodeBucket struct {
78 Key string
79 Count int64
80 }
81
82 func (r *Rpcs) ProcessEvent(ctx context.Context, ev core.Event, lm label.Map) context.Context {
83 r.mu.Lock()
84 defer r.mu.Unlock()
85 switch {
86 case event.IsStart(ev):
87 if _, stats := r.getRPCSpan(ctx); stats != nil {
88 stats.Started++
89 }
90 case event.IsEnd(ev):
91 span, stats := r.getRPCSpan(ctx)
92 if stats != nil {
93 endRPC(span, stats)
94 }
95 case event.IsMetric(ev):
96 sent := byteUnits(jsonrpc2.SentBytes.Get(lm))
97 rec := byteUnits(jsonrpc2.ReceivedBytes.Get(lm))
98 if sent != 0 || rec != 0 {
99 if _, stats := r.getRPCSpan(ctx); stats != nil {
100 stats.Sent += sent
101 stats.Received += rec
102 }
103 }
104 }
105 return ctx
106 }
107
108 func endRPC(span *export.Span, stats *rpcStats) {
109 // update the basic counts
110 stats.Completed++
111
112 // get and record the status code
113 if status := getStatusCode(span); status != "" {
114 var b *rpcCodeBucket
115 for c, entry := range stats.Codes {
116 if entry.Key == status {
117 b = stats.Codes[c]
118 break
119 }
120 }
121 if b == nil {
122 b = &rpcCodeBucket{Key: status}
123 stats.Codes = append(stats.Codes, b)
124 sort.Slice(stats.Codes, func(i int, j int) bool {
125 return stats.Codes[i].Key < stats.Codes[j].Key
126 })
127 }
128 b.Count++
129 }
130
131 // calculate latency if this was an rpc span
132 elapsedTime := span.Finish().At().Sub(span.Start().At())
133 if stats.Latency.Count == 0 {
134 stats.Latency.Min = elapsedTime
135 stats.Latency.Max = elapsedTime
136 } else {
137 stats.Latency.Min = min(stats.Latency.Min, elapsedTime)
138 stats.Latency.Max = max(stats.Latency.Max, elapsedTime)
139 }
140 stats.Latency.Count++
141 stats.Latency.Sum += elapsedTime
142 for i := range stats.Latency.Values {
143 if stats.Latency.Values[i].Limit > elapsedTime {
144 stats.Latency.Values[i].Count++
145 break
146 }
147 }
148 }
149
150 func (r *Rpcs) getRPCSpan(ctx context.Context) (*export.Span, *rpcStats) {
151 // get the span
152 span := export.GetSpan(ctx)
153 if span == nil {
154 return nil, nil
155 }
156 // use the span start event look up the correct stats block
157 // we do this because it prevents us matching a sub span
158 return span, r.getRPCStats(span.Start())
159 }
160
161 func (r *Rpcs) getRPCStats(lm label.Map) *rpcStats {
162 method := jsonrpc2.Method.Get(lm)
163 if method == "" {
164 return nil
165 }
166 set := &r.Inbound
167 if jsonrpc2.RPCDirection.Get(lm) != jsonrpc2.Inbound {
168 set = &r.Outbound
169 }
170 // get the record for this method
171 index := sort.Search(len(*set), func(i int) bool {
172 return (*set)[i].Method >= method
173 })
174
175 if index < len(*set) && (*set)[index].Method == method {
176 return (*set)[index]
177 }
178
179 old := *set
180 *set = make([]*rpcStats, len(old)+1)
181 copy(*set, old[:index])
182 copy((*set)[index+1:], old[index:])
183 stats := &rpcStats{Method: method}
184 stats.Latency.Values = make([]rpcTimeBucket, len(secondsDistribution))
185 for i, m := range secondsDistribution {
186 stats.Latency.Values[i].Limit = time.Duration(m * float64(time.Second))
187 }
188 (*set)[index] = stats
189 return stats
190 }
191
192 func (s *rpcStats) InProgress() int64 { return s.Started - s.Completed }
193 func (s *rpcStats) SentMean() byteUnits { return s.Sent / byteUnits(s.Started) }
194 func (s *rpcStats) ReceivedMean() byteUnits { return s.Received / byteUnits(s.Started) }
195
196 func (h *rpcTimeHistogram) Mean() time.Duration { return h.Sum / time.Duration(h.Count) }
197
198 func getStatusCode(span *export.Span) string {
199 for _, ev := range span.Events() {
200 if status := jsonrpc2.StatusCode.Get(ev); status != "" {
201 return status
202 }
203 }
204 return ""
205 }
206
207 func (r *Rpcs) getData(req *http.Request) any {
208 return r
209 }
210
211 func units(v float64, suffixes []string) string {
212 s := ""
213 for _, s = range suffixes {
214 n := v / 1000
215 if n < 1 {
216 break
217 }
218 v = n
219 }
220 return fmt.Sprintf("%.2f%s", v, s)
221 }
222
223 type byteUnits float64
224
225 func (v byteUnits) String() string {
226 return units(float64(v), []string{"B", "KB", "MB", "GB", "TB"})
227 }