Debian Codegraph @

gopls/internal/protocol/context.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 protocol
6
7 import (
8 "bytes"
9 "context"
10 "sync"
11
12 "golang.org/x/tools/internal/event"
13 "golang.org/x/tools/internal/event/core"
14 "golang.org/x/tools/internal/event/export"
15 "golang.org/x/tools/internal/event/label"
16 )
17
18 type contextKey int
19
20 const (
21 clientKey = contextKey(iota)
22 )
23
24 func WithClient(ctx context.Context, client Client) context.Context {
25 return context.WithValue(ctx, clientKey, client)
26 }
27
28 func LogEvent(ctx context.Context, ev core.Event, lm label.Map, mt MessageType) context.Context {
29 client, ok := ctx.Value(clientKey).(Client)
30 if !ok {
31 return ctx
32 }
33 buf := &bytes.Buffer{}
34 p := export.Printer{}
35 p.WriteEvent(buf, ev, lm)
36 msg := &LogMessageParams{Type: mt, Message: buf.String()}
37 // Handle messages generated via event.Error, which won't have a level Label.
38 if event.IsError(ev) {
39 msg.Type = Error
40 }
41
42 // The background goroutine lives forever once started,
43 // and ensures log messages are sent in order (#61216).
44 startLogSenderOnce.Do(func() {
45 go func() {
46 for f := range logQueue {
47 f()
48 }
49 }()
50 })
51
52 // Add the log item to a queue, rather than sending a
53 // window/logMessage request to the client synchronously,
54 // which would slow down this thread.
55 ctx2 := context.WithoutCancel(ctx)
56 logQueue <- func() { client.LogMessage(ctx2, msg) }
57
58 return ctx
59 }
60
61 var (
62 startLogSenderOnce sync.Once
63 logQueue = make(chan func(), 100) // big enough for a large transient burst
64 )