github.com/tiagovtristao/plz@v13.4.0+incompatible/tools/build_langserver/langserver/request_store.go (about) 1 package langserver 2 3 import ( 4 "context" 5 "fmt" 6 "sync" 7 8 "github.com/sourcegraph/jsonrpc2" 9 ) 10 11 type requestStore struct { 12 mu sync.Mutex 13 requests map[jsonrpc2.ID]request 14 } 15 16 // Perhaps later we can store more things in the request we might want to use 17 type request struct { 18 id string 19 cancel func() 20 } 21 22 // newRequestStore constructs a new requestStore with an empty requests map 23 func newRequestStore() *requestStore { 24 return &requestStore{ 25 requests: make(map[jsonrpc2.ID]request), 26 } 27 } 28 29 // IsEmpty checks if requestStore.requests is empty 30 func (rs *requestStore) IsEmpty() bool { 31 if len(rs.requests) == 0 { 32 return true 33 } 34 return false 35 } 36 37 // Store method takes a context and request object and stores the request.ID and cancellation function 38 // into requestStore.requests 39 func (rs *requestStore) Store(ctx context.Context, req *jsonrpc2.Request) context.Context { 40 ctx, cancel := context.WithCancel(ctx) 41 42 rs.mu.Lock() 43 // Cancellation function definition, 44 // calling both cancel and delete id from the requests map 45 cancelFunc := func() { 46 rs.mu.Lock() 47 cancel() 48 delete(rs.requests, req.ID) 49 rs.mu.Unlock() 50 } 51 52 rs.requests[req.ID] = request{ 53 id: req.ID.String(), 54 cancel: cancelFunc, 55 } 56 57 defer rs.mu.Unlock() 58 59 // returns the sub-context for the specific request.ID 60 return ctx 61 } 62 63 // Cancel method removes the id from the requests map and calls cancel function of the request 64 func (rs *requestStore) Cancel(id jsonrpc2.ID) { 65 if rs.requests != nil { 66 req, ok := rs.requests[id] 67 if ok { 68 req.cancel() 69 } else { 70 log.Info(fmt.Sprintf("Request id '%s' does not exist in the map, no action", id)) 71 } 72 } 73 }