Debian Codegraph @

gopls/internal/progress/progress.go

raw symbols SCIP
1 // Copyright 2020 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 // The progress package defines utilities for reporting the progress
6 // of long-running operations using features of the LSP client
7 // interface such as Progress and ShowMessage.
8 package progress
9
10 import (
11 "context"
12 "fmt"
13 "io"
14 "math/rand"
15 "strconv"
16 "strings"
17 "sync"
18
19 "golang.org/x/tools/gopls/internal/label"
20 "golang.org/x/tools/gopls/internal/protocol"
21 "golang.org/x/tools/internal/event"
22 )
23
24 // NewTracker returns a new Tracker that reports progress to the
25 // specified client.
26 func NewTracker(client protocol.Client) *Tracker {
27 return &Tracker{
28 client: client,
29 inProgress: make(map[protocol.ProgressToken]*WorkDone),
30 }
31 }
32
33 // A Tracker reports the progress of a long-running operation to an LSP client.
34 type Tracker struct {
35 client protocol.Client
36 supportsWorkDoneProgress bool
37
38 mu sync.Mutex
39 inProgress map[protocol.ProgressToken]*WorkDone
40 }
41
42 // SetSupportsWorkDoneProgress sets whether the client supports "work done"
43 // progress reporting. It must be set before using the tracker.
44 //
45 // TODO(rfindley): fix this broken initialization pattern.
46 // Also: do we actually need the fall-back progress behavior using ShowMessage?
47 // Surely ShowMessage notifications are too noisy to be worthwhile.
48 func (t *Tracker) SetSupportsWorkDoneProgress(b bool) {
49 t.supportsWorkDoneProgress = b
50 }
51
52 // SupportsWorkDoneProgress reports whether the tracker supports work done
53 // progress reporting.
54 func (t *Tracker) SupportsWorkDoneProgress() bool {
55 return t.supportsWorkDoneProgress
56 }
57
58 // Start notifies the client of work being done on the server. It uses either
59 // ShowMessage RPCs or $/progress messages, depending on the capabilities of
60 // the client. The returned WorkDone handle may be used to report incremental
61 // progress, and to report work completion. In particular, it is an error to
62 // call start and not call end(...) on the returned WorkDone handle.
63 //
64 // If token is empty, a token will be randomly generated.
65 //
66 // The progress item is considered cancellable if the given cancel func is
67 // non-nil. In this case, cancel is called when the work done
68 //
69 // Example:
70 //
71 // func Generate(ctx) (err error) {
72 // ctx, cancel := context.WithCancel(ctx)
73 // defer cancel()
74 // work := s.progress.start(ctx, "generate", "running go generate", cancel)
75 // defer func() {
76 // if err != nil {
77 // work.end(ctx, fmt.Sprintf("generate failed: %v", err))
78 // } else {
79 // work.end(ctx, "done")
80 // }
81 // }()
82 // // Do the work...
83 // }
84 func (t *Tracker) Start(ctx context.Context, title, message string, token protocol.ProgressToken, cancel func()) *WorkDone {
85 ctx = context.WithoutCancel(ctx) // progress messages should not be cancelled
86 wd := &WorkDone{
87 client: t.client,
88 token: token,
89 cancel: cancel,
90 }
91 if !t.supportsWorkDoneProgress {
92 // Previous iterations of this fallback attempted to retain cancellation
93 // support by using ShowMessageCommand with a 'Cancel' button, but this is
94 // not ideal as the 'Cancel' dialog stays open even after the command
95 // completes.
96 //
97 // Just show a simple message. Clients can implement workDone progress
98 // reporting to get cancellation support.
99 if err := wd.client.ShowMessage(ctx, &protocol.ShowMessageParams{
100 Type: protocol.Log,
101 Message: message,
102 }); err != nil {
103 event.Error(ctx, "showing start message for "+title, err)
104 }
105 return wd
106 }
107 if wd.token == nil {
108 token = strconv.FormatInt(rand.Int63(), 10)
109 err := wd.client.WorkDoneProgressCreate(ctx, &protocol.WorkDoneProgressCreateParams{
110 Token: token,
111 })
112 if err != nil {
113 wd.err = err
114 event.Error(ctx, "starting work for "+title, err)
115 return wd
116 }
117 wd.token = token
118 }
119 // At this point we have a token that the client knows about. Store the token
120 // before starting work.
121 t.mu.Lock()
122 t.inProgress[wd.token] = wd
123 t.mu.Unlock()
124 wd.cleanup = func() {
125 t.mu.Lock()
126 delete(t.inProgress, token)
127 t.mu.Unlock()
128 }
129 err := wd.client.Progress(ctx, &protocol.ProgressParams{
130 Token: wd.token,
131 Value: &protocol.WorkDoneProgressBegin{
132 Kind: "begin",
133 Cancellable: wd.cancel != nil,
134 Message: message,
135 Title: title,
136 },
137 })
138 if err != nil {
139 event.Error(ctx, "progress begin", err)
140 }
141 return wd
142 }
143
144 func (t *Tracker) Cancel(token protocol.ProgressToken) error {
145 t.mu.Lock()
146 defer t.mu.Unlock()
147 wd, ok := t.inProgress[token]
148 if !ok {
149 return fmt.Errorf("token %q not found in progress", token)
150 }
151 if wd.cancel == nil {
152 return fmt.Errorf("work %q is not cancellable", token)
153 }
154 wd.doCancel()
155 return nil
156 }
157
158 // WorkDone represents a unit of work that is reported to the client via the
159 // progress API.
160 type WorkDone struct {
161 client protocol.Client
162 // If token is nil, this workDone object uses the ShowMessage API, rather
163 // than $/progress.
164 token protocol.ProgressToken
165 // err is set if progress reporting is broken for some reason (for example,
166 // if there was an initial error creating a token).
167 err error
168
169 cancelMu sync.Mutex
170 cancelled bool
171 cancel func()
172
173 cleanup func()
174 }
175
176 func (wd *WorkDone) Token() protocol.ProgressToken {
177 return wd.token
178 }
179
180 func (wd *WorkDone) doCancel() {
181 wd.cancelMu.Lock()
182 defer wd.cancelMu.Unlock()
183 if !wd.cancelled {
184 wd.cancel()
185 }
186 }
187
188 // Report reports an update on WorkDone report back to the client.
189 func (wd *WorkDone) Report(ctx context.Context, message string, fraction float64) {
190 ctx = context.WithoutCancel(ctx) // progress messages should not be cancelled
191 if wd == nil {
192 return
193 }
194 wd.cancelMu.Lock()
195 cancelled := wd.cancelled
196 wd.cancelMu.Unlock()
197 if cancelled {
198 return
199 }
200 if wd.err != nil || wd.token == nil {
201 // Not using the workDone API, so we do nothing. It would be far too spammy
202 // to send incremental messages.
203 return
204 }
205 message = strings.TrimSuffix(message, "\n")
206 percentage := uint32(100 * fraction)
207 err := wd.client.Progress(ctx, &protocol.ProgressParams{
208 Token: wd.token,
209 Value: &protocol.WorkDoneProgressReport{
210 Kind: "report",
211 // Note that in the LSP spec, the value of Cancellable may be changed to
212 // control whether the cancel button in the UI is enabled. Since we don't
213 // yet use this feature, the value is kept constant here.
214 Cancellable: wd.cancel != nil,
215 Message: message,
216 Percentage: &percentage,
217 },
218 })
219 if err != nil {
220 event.Error(ctx, "reporting progress", err)
221 }
222 }
223
224 // End reports a workdone completion back to the client.
225 func (wd *WorkDone) End(ctx context.Context, message string) {
226 ctx = context.WithoutCancel(ctx) // progress messages should not be cancelled
227 if wd == nil {
228 return
229 }
230 var err error
231 switch {
232 case wd.err != nil:
233 // There is a prior error.
234 case wd.token == nil:
235 // We're falling back to message-based reporting.
236 err = wd.client.ShowMessage(ctx, &protocol.ShowMessageParams{
237 Type: protocol.Info,
238 Message: message,
239 })
240 default:
241 err = wd.client.Progress(ctx, &protocol.ProgressParams{
242 Token: wd.token,
243 Value: &protocol.WorkDoneProgressEnd{
244 Kind: "end",
245 Message: message,
246 },
247 })
248 }
249 if err != nil {
250 event.Error(ctx, "ending work", err)
251 }
252 if wd.cleanup != nil {
253 wd.cleanup()
254 }
255 }
256
257 // NewEventWriter returns an [io.Writer] that calls the context's
258 // event printer for each data payload, wrapping it with the
259 // operation=generate tag to distinguish its logs from others.
260 func NewEventWriter(ctx context.Context, operation string) io.Writer {
261 return &eventWriter{ctx: ctx, operation: operation}
262 }
263
264 type eventWriter struct {
265 ctx context.Context
266 operation string
267 }
268
269 func (ew *eventWriter) Write(p []byte) (n int, err error) {
270 event.Log(ew.ctx, string(p), label.Operation.Of(ew.operation))
271 return len(p), nil
272 }
273
274 // NewWorkDoneWriter wraps a WorkDone handle to provide a Writer interface,
275 // so that workDone reporting can more easily be hooked into commands.
276 func NewWorkDoneWriter(ctx context.Context, wd *WorkDone) io.Writer {
277 return &workDoneWriter{ctx: ctx, wd: wd}
278 }
279
280 // workDoneWriter wraps a workDone handle to provide a Writer interface,
281 // so that workDone reporting can more easily be hooked into commands.
282 type workDoneWriter struct {
283 // In order to implement the io.Writer interface, we must close over ctx.
284 ctx context.Context
285 wd *WorkDone
286 }
287
288 func (wdw *workDoneWriter) Write(p []byte) (n int, err error) {
289 wdw.wd.Report(wdw.ctx, string(p), 0)
290 // Don't fail just because of a failure to report progress.
291 return len(p), nil
292 }