Debian Codegraph @

gopls/internal/server/prompt.go

raw symbols SCIP
1 // Copyright 2023 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 server
6
7 import (
8 "context"
9 "fmt"
10 "math/rand"
11 "os"
12 "path/filepath"
13 "strconv"
14 "testing"
15 "time"
16
17 "golang.org/x/telemetry"
18 "golang.org/x/telemetry/counter"
19 "golang.org/x/tools/gopls/internal/protocol"
20 "golang.org/x/tools/internal/event"
21 )
22
23 // promptTimeout is the amount of time we wait for an ongoing prompt before
24 // prompting again. This gives the user time to reply. However, at some point
25 // we must assume that the client is not displaying the prompt, the user is
26 // ignoring it, or the prompt has been disrupted in some way (e.g. by a gopls
27 // crash).
28 const promptTimeout = 24 * time.Hour
29
30 // gracePeriod is the amount of time we wait before sufficient telemetry data
31 // is accumulated in the local directory, so users can have time to review
32 // what kind of information will be collected and uploaded when prompting starts.
33 const gracePeriod = 7 * 24 * time.Hour
34
35 // samplesPerMille is the prompt probability.
36 // Token is an integer between [1, 1000] and is assigned when maybePromptForTelemetry
37 // is called first time. Only the user with a token ∈ [1, samplesPerMille]
38 // will be considered for prompting.
39 const samplesPerMille = 10 // 1% sample rate
40
41 // The following constants are used for testing telemetry integration.
42 const (
43 TelemetryPromptWorkTitle = "Checking telemetry prompt" // progress notification title, for awaiting in tests
44 GoplsConfigDirEnvvar = "GOPLS_CONFIG_DIR" // overridden for testing
45 FakeTelemetryModefileEnvvar = "GOPLS_FAKE_TELEMETRY_MODEFILE" // overridden for testing
46 FakeSamplesPerMille = "GOPLS_FAKE_SAMPLES_PER_MILLE" // overridden for testing
47 TelemetryYes = "Yes, I'd like to help."
48 TelemetryNo = "No, thanks."
49 )
50
51 // The following environment variables may be set by the client.
52 // Exported for testing telemetry integration.
53 const (
54 GoTelemetryGoplsClientStartTimeEnvvar = "GOTELEMETRY_GOPLS_CLIENT_START_TIME" // telemetry start time recorded in client
55 GoTelemetryGoplsClientTokenEnvvar = "GOTELEMETRY_GOPLS_CLIENT_TOKEN" // sampling token
56 )
57
58 // getenv returns the effective environment variable value for the provided
59 // key, looking up the key in the session environment before falling back on
60 // the process environment.
61 func (s *server) getenv(key string) string {
62 if v, ok := s.Options().Env[key]; ok {
63 return v
64 }
65 return os.Getenv(key)
66 }
67
68 // telemetryMode returns the current effective telemetry mode.
69 // By default this is x/telemetry.Mode(), but it may be overridden for tests.
70 func (s *server) telemetryMode() string {
71 if fake := s.getenv(FakeTelemetryModefileEnvvar); fake != "" {
72 if data, err := os.ReadFile(fake); err == nil {
73 return string(data)
74 }
75 return "local"
76 }
77 return telemetry.Mode()
78 }
79
80 // setTelemetryMode sets the current telemetry mode.
81 // By default this calls x/telemetry.SetMode, but it may be overridden for
82 // tests.
83 func (s *server) setTelemetryMode(mode string) error {
84 if fake := s.getenv(FakeTelemetryModefileEnvvar); fake != "" {
85 return os.WriteFile(fake, []byte(mode), 0666)
86 }
87 return telemetry.SetMode(mode)
88 }
89
90 // maybePromptForTelemetry checks for the right conditions, and then prompts
91 // the user to ask if they want to enable Go telemetry uploading. If the user
92 // responds 'Yes', the telemetry mode is set to "on".
93 //
94 // The actual conditions for prompting are defensive, erring on the side of not
95 // prompting.
96 // If enabled is false, this will not prompt the user in any condition,
97 // but will send work progress reports to help testing.
98 func (s *server) maybePromptForTelemetry(ctx context.Context, enabled bool) {
99 if s.Options().VerboseWorkDoneProgress {
100 work := s.progress.Start(ctx, TelemetryPromptWorkTitle, "Checking if gopls should prompt about telemetry...", nil, nil)
101 defer work.End(ctx, "Done.")
102 }
103
104 errorf := func(format string, args ...any) {
105 err := fmt.Errorf(format, args...)
106 event.Error(ctx, "telemetry prompt failed", err)
107 }
108
109 // Only prompt if we can read/write the prompt config file.
110 configDir := s.getenv(GoplsConfigDirEnvvar) // set for testing
111 if configDir == "" && testing.Testing() {
112 // Unless tests set GoplsConfigDirEnvvar, the prompt is a no op.
113 // We don't want tests to interact with os.UserConfigDir().
114 return
115 }
116 if configDir == "" {
117 userDir, err := os.UserConfigDir()
118 if err != nil {
119 errorf("unable to determine user config dir: %v", err)
120 return
121 }
122 configDir = filepath.Join(userDir, "gopls")
123 }
124
125 // Read the current prompt file.
126
127 var (
128 promptDir = filepath.Join(configDir, "prompt") // prompt configuration directory
129 promptFile = filepath.Join(promptDir, "telemetry") // telemetry prompt file
130 )
131
132 // prompt states, stored in the prompt file
133 const (
134 pUnknown = "" // first time
135 pNotReady = "-" // user is not asked yet (either not sampled or not past the grace period)
136 pYes = "yes" // user said yes
137 pNo = "no" // user said no
138 pPending = "pending" // current prompt is still pending
139 pFailed = "failed" // prompt was asked but failed
140 )
141 validStates := map[string]bool{
142 pNotReady: true,
143 pYes: true,
144 pNo: true,
145 pPending: true,
146 pFailed: true,
147 }
148
149 // Parse the current prompt file.
150 var (
151 state = pUnknown
152 attempts = 0 // number of times we've asked already
153
154 // the following are recorded after gopls v0.17+.
155 token = 0 // valid token is [1, 1000]
156 creationTime int64 // unix time sec
157 )
158 if content, err := os.ReadFile(promptFile); err == nil {
159 if n, _ := fmt.Sscanf(string(content), "%s %d %d %d", &state, &attempts, &creationTime, &token); (n == 2 || n == 4) && validStates[state] {
160 // successfully parsed!
161 // ~ v0.16: must have only two fields, state and attempts.
162 // v0.17 ~: must have all four fields.
163 } else {
164 state, attempts, creationTime, token = pUnknown, 0, 0, 0
165 // TODO(hyangah): why do we want to present this as an error to user?
166 errorf("malformed prompt result %q", string(content))
167 }
168 } else if !os.IsNotExist(err) {
169 errorf("reading prompt file: %v", err)
170 // Something went wrong. Since we don't know how many times we've asked the
171 // prompt, err on the side of not asking.
172 //
173 // But record this in telemetry, in case some users enable telemetry by
174 // other means.
175 counter.New("gopls/telemetryprompt/corrupted").Inc()
176 return
177 }
178
179 counter.New(fmt.Sprintf("gopls/telemetryprompt/attempts:%d", attempts)).Inc()
180
181 // Check terminal conditions.
182
183 if state == pYes {
184 // Prompt has been accepted.
185 //
186 // We record this counter for every gopls session, rather than when the
187 // prompt actually accepted below, because if we only recorded it in the
188 // counter file at the time telemetry is enabled, we'd never upload it,
189 // because we exclude any counter files that overlap with a time period
190 // that has telemetry uploading is disabled.
191 counter.New("gopls/telemetryprompt/accepted").Inc()
192 return
193 }
194 if state == pNo {
195 // Prompt has been declined. In most cases, this means we'll never see the
196 // counter below, but it's possible that the user may enable telemetry by
197 // other means later on. If we see a significant number of users that have
198 // accepted telemetry but declined the prompt, it may be an indication that
199 // the prompt is not working well.
200 counter.New("gopls/telemetryprompt/declined").Inc()
201 return
202 }
203 if attempts >= 5 { // pPending or pFailed
204 // We've tried asking enough; give up. Record that the prompt expired, in
205 // case the user decides to enable telemetry by other means later on.
206 // (see also the pNo case).
207 counter.New("gopls/telemetryprompt/expired").Inc()
208 return
209 }
210
211 // We only check enabled after (1) the work progress is started, and (2) the
212 // prompt file has been read. (1) is for testing purposes, and (2) is so that
213 // we record the "gopls/telemetryprompt/accepted" counter for every session.
214 if !enabled {
215 return // prompt is disabled
216 }
217
218 if s.telemetryMode() == "on" || s.telemetryMode() == "off" {
219 // Telemetry is already on or explicitly off -- nothing to ask about.
220 return
221 }
222
223 // Transition: pUnknown -> pNotReady
224 if state == pUnknown {
225 // First time; we need to make the prompt dir.
226 if err := os.MkdirAll(promptDir, 0777); err != nil {
227 errorf("creating prompt dir: %v", err)
228 return
229 }
230 state = pNotReady
231 }
232
233 // Correct missing values.
234 if creationTime == 0 {
235 creationTime = time.Now().Unix()
236 if v := s.getenv(GoTelemetryGoplsClientStartTimeEnvvar); v != "" {
237 if sec, err := strconv.ParseInt(v, 10, 64); err == nil && sec > 0 {
238 creationTime = sec
239 }
240 }
241 }
242 if token == 0 {
243 token = rand.Intn(1000) + 1
244 if v := s.getenv(GoTelemetryGoplsClientTokenEnvvar); v != "" {
245 if tok, err := strconv.Atoi(v); err == nil && 1 <= tok && tok <= 1000 {
246 token = tok
247 }
248 }
249 }
250
251 // Transition: pNotReady -> pPending if sampled
252 if state == pNotReady {
253 threshold := samplesPerMille
254 if v := s.getenv(FakeSamplesPerMille); v != "" {
255 if t, err := strconv.Atoi(v); err == nil {
256 threshold = t
257 }
258 }
259 if token <= threshold && time.Now().Unix()-creationTime > gracePeriod.Milliseconds()/1000 {
260 state = pPending
261 }
262 }
263
264 // Acquire the lock and write the updated state to the prompt file before actually
265 // prompting.
266 //
267 // This ensures that the prompt file is writeable, and that we increment the
268 // attempt counter before we prompt, so that we don't end up in a failure
269 // mode where we keep prompting and then failing to record the response.
270
271 release, ok, err := acquireLockFile(promptFile)
272 if err != nil {
273 errorf("acquiring prompt: %v", err)
274 return
275 }
276 if !ok {
277 // Another process is making decision.
278 return
279 }
280 defer release()
281
282 if state != pNotReady { // pPending or pFailed
283 attempts++
284 }
285
286 pendingContent := fmt.Appendf(nil, "%s %d %d %d", state, attempts, creationTime, token)
287 if err := os.WriteFile(promptFile, pendingContent, 0666); err != nil {
288 errorf("writing pending state: %v", err)
289 return
290 }
291
292 if state == pNotReady {
293 return
294 }
295
296 var prompt = `Go telemetry helps us improve Go by periodically sending anonymous metrics and crash reports to the Go team. Learn more at https://go.dev/doc/telemetry.
297
298 Would you like to enable Go telemetry?
299 `
300 if s.Options().LinkifyShowMessage {
301 prompt = `Go telemetry helps us improve Go by periodically sending anonymous metrics and crash reports to the Go team. Learn more at [go.dev/doc/telemetry](https://go.dev/doc/telemetry).
302
303 Would you like to enable Go telemetry?
304 `
305 }
306 // TODO(rfindley): investigate a "tell me more" action in combination with ShowDocument.
307 action, err := showMessageRequest(ctx, s.client, protocol.Info, prompt, TelemetryYes, TelemetryNo)
308 if err != nil {
309 errorf("ShowMessageRequest failed: %v", err)
310 }
311
312 message := func(typ protocol.MessageType, msg string) {
313 if !showMessage(ctx, s.client, typ, msg) {
314 // Make sure we record that "telemetry prompt failed".
315 errorf("showMessage failed: %v", err)
316 }
317 }
318
319 result := pFailed
320 if action == "" {
321 // e.g. dialog was dismissed
322 errorf("no response")
323 } else {
324 // Response matches MessageActionItem.Title.
325 switch action {
326 case TelemetryYes:
327 result = pYes
328 if err := s.setTelemetryMode("on"); err == nil {
329 message(protocol.Info, telemetryOnMessage(s.Options().LinkifyShowMessage))
330 } else {
331 errorf("enabling telemetry failed: %v", err)
332 msg := fmt.Sprintf("Failed to enable Go telemetry: %v\nTo enable telemetry manually, please run `go run golang.org/x/telemetry/cmd/gotelemetry@latest on`", err)
333 message(protocol.Error, msg)
334 }
335
336 case TelemetryNo:
337 result = pNo
338 default:
339 errorf("unrecognized response %q", action)
340 message(protocol.Error, fmt.Sprintf("Unrecognized response %q", action))
341 }
342 }
343 resultContent := fmt.Appendf(nil, "%s %d %d %d", result, attempts, creationTime, token)
344 if err := os.WriteFile(promptFile, resultContent, 0666); err != nil {
345 errorf("error writing result state to prompt file: %v", err)
346 }
347 }
348
349 // showMessageRequest causes the client to show a plain-text prompt that the user can respond to.
350 // It returns the title of the action the user selected, or "" if the user dismissed the prompt.
351 func showMessageRequest(ctx context.Context, cli protocol.Client, typ protocol.MessageType, message string, actions ...string) (string, error) {
352 var actionItems []protocol.MessageActionItem
353 for _, action := range actions {
354 actionItems = append(actionItems, protocol.MessageActionItem{Title: action})
355 }
356 params := &protocol.ShowMessageRequestParams{
357 Type: typ,
358 Message: message,
359 Actions: actionItems,
360 }
361 // Timeout used to wait for the user to respond to a message request.
362 const timeout = 15 * time.Second
363 ctx, cancel := context.WithTimeout(ctx, timeout)
364 defer cancel()
365
366 result, err := cli.ShowMessageRequest(ctx, params)
367
368 if err != nil {
369 if cause := context.Cause(ctx); cause == context.DeadlineExceeded || cause == context.Canceled {
370 return "", nil
371 }
372 return "", err
373 }
374 if result == nil {
375 return "", nil // User dismissed the notification
376 }
377 return result.Title, nil
378 }
379
380 func telemetryOnMessage(linkify bool) string {
381 format := `Thank you. Telemetry uploading is now enabled.
382
383 To disable telemetry uploading, run %s.
384 `
385 var runCmd = "`go run golang.org/x/telemetry/cmd/gotelemetry@latest local`"
386 if linkify {
387 runCmd = "[gotelemetry local](https://golang.org/x/telemetry/cmd/gotelemetry)"
388 }
389 return fmt.Sprintf(format, runCmd)
390 }
391
392 // acquireLockFile attempts to "acquire a lock" for writing to path.
393 //
394 // This is achieved by creating an exclusive lock file at <path>.lock. Lock
395 // files expire after a period, at which point acquireLockFile will remove and
396 // recreate the lock file.
397 //
398 // acquireLockFile fails if path is in a directory that doesn't exist.
399 func acquireLockFile(path string) (func(), bool, error) {
400 lockpath := path + ".lock"
401 fi, err := os.Stat(lockpath)
402 if err == nil {
403 if time.Since(fi.ModTime()) > promptTimeout {
404 _ = os.Remove(lockpath) // ignore error
405 } else {
406 return nil, false, nil
407 }
408 } else if !os.IsNotExist(err) {
409 return nil, false, fmt.Errorf("statting lockfile: %v", err)
410 }
411
412 f, err := os.OpenFile(lockpath, os.O_CREATE|os.O_EXCL, 0666)
413 if err != nil {
414 if os.IsExist(err) {
415 return nil, false, nil
416 }
417 return nil, false, fmt.Errorf("creating lockfile: %v", err)
418 }
419 fi, err = f.Stat()
420 if err != nil {
421 return nil, false, err
422 }
423 release := func() {
424 _ = f.Close() // ignore error
425 fi2, err := os.Stat(lockpath)
426 if err == nil && os.SameFile(fi, fi2) {
427 // Only clean up the lockfile if it's the same file we created.
428 // Otherwise, our lock has expired and something else has the lock.
429 //
430 // There's a race here, in that the file could have changed since the
431 // stat above; but given that we've already waited 24h this is extremely
432 // unlikely, and acceptable.
433 _ = os.Remove(lockpath)
434 }
435 }
436 return release, true, nil
437 }