-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathjsonrpc.go
More file actions
350 lines (300 loc) · 8.98 KB
/
Copy pathjsonrpc.go
File metadata and controls
350 lines (300 loc) · 8.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
package copilot
import (
"bufio"
"crypto/rand"
"encoding/json"
"fmt"
"io"
"sync"
)
// JSONRPCError represents a JSON-RPC error response
type JSONRPCError struct {
Code int `json:"code"`
Message string `json:"message"`
Data map[string]interface{} `json:"data,omitempty"`
}
func (e *JSONRPCError) Error() string {
return fmt.Sprintf("JSON-RPC Error %d: %s", e.Code, e.Message)
}
// JSONRPCRequest represents a JSON-RPC 2.0 request
type JSONRPCRequest struct {
JSONRPC string `json:"jsonrpc"`
ID json.RawMessage `json:"id"`
Method string `json:"method"`
Params map[string]interface{} `json:"params"`
}
// JSONRPCResponse represents a JSON-RPC 2.0 response
type JSONRPCResponse struct {
JSONRPC string `json:"jsonrpc"`
ID json.RawMessage `json:"id,omitempty"`
Result map[string]interface{} `json:"result,omitempty"`
Error *JSONRPCError `json:"error,omitempty"`
}
// JSONRPCNotification represents a JSON-RPC 2.0 notification
type JSONRPCNotification struct {
JSONRPC string `json:"jsonrpc"`
Method string `json:"method"`
Params map[string]interface{} `json:"params"`
}
// NotificationHandler handles incoming notifications
type NotificationHandler func(method string, params map[string]interface{})
// RequestHandler handles incoming server requests and returns a result or error
type RequestHandler func(params map[string]interface{}) (map[string]interface{}, *JSONRPCError)
// JSONRPCClient is a minimal JSON-RPC 2.0 client for stdio transport
type JSONRPCClient struct {
stdin io.WriteCloser
stdout io.ReadCloser
mu sync.Mutex
pendingRequests map[string]chan *JSONRPCResponse
notificationHandler NotificationHandler
requestHandlers map[string]RequestHandler
running bool
stopChan chan struct{}
wg sync.WaitGroup
}
// NewJSONRPCClient creates a new JSON-RPC client
func NewJSONRPCClient(stdin io.WriteCloser, stdout io.ReadCloser) *JSONRPCClient {
return &JSONRPCClient{
stdin: stdin,
stdout: stdout,
pendingRequests: make(map[string]chan *JSONRPCResponse),
requestHandlers: make(map[string]RequestHandler),
stopChan: make(chan struct{}),
}
}
// Start begins listening for messages in a background goroutine
func (c *JSONRPCClient) Start() {
c.running = true
c.wg.Add(1)
go c.readLoop()
}
// Stop stops the client and cleans up
func (c *JSONRPCClient) Stop() {
if !c.running {
return
}
c.running = false
close(c.stopChan)
// Close stdout to unblock the readLoop
if c.stdout != nil {
c.stdout.Close()
}
c.wg.Wait()
}
// SetNotificationHandler sets the handler for incoming notifications
func (c *JSONRPCClient) SetNotificationHandler(handler NotificationHandler) {
c.mu.Lock()
defer c.mu.Unlock()
c.notificationHandler = handler
}
// SetRequestHandler registers a handler for incoming requests from the server
func (c *JSONRPCClient) SetRequestHandler(method string, handler RequestHandler) {
c.mu.Lock()
defer c.mu.Unlock()
if handler == nil {
delete(c.requestHandlers, method)
return
}
c.requestHandlers[method] = handler
}
// Request sends a JSON-RPC request and waits for the response
func (c *JSONRPCClient) Request(method string, params map[string]interface{}) (map[string]interface{}, error) {
requestID := generateUUID()
// Create response channel
responseChan := make(chan *JSONRPCResponse, 1)
c.mu.Lock()
c.pendingRequests[requestID] = responseChan
c.mu.Unlock()
// Clean up on exit
defer func() {
c.mu.Lock()
delete(c.pendingRequests, requestID)
c.mu.Unlock()
}()
// Send request
request := JSONRPCRequest{
JSONRPC: "2.0",
ID: json.RawMessage(`"` + requestID + `"`),
Method: method,
Params: params,
}
if err := c.sendMessage(request); err != nil {
return nil, fmt.Errorf("failed to send request: %w", err)
}
// Wait for response
select {
case response := <-responseChan:
if response.Error != nil {
return nil, response.Error
}
return response.Result, nil
case <-c.stopChan:
return nil, fmt.Errorf("client stopped")
}
}
// Notify sends a JSON-RPC notification (no response expected)
func (c *JSONRPCClient) Notify(method string, params map[string]interface{}) error {
notification := JSONRPCNotification{
JSONRPC: "2.0",
Method: method,
Params: params,
}
return c.sendMessage(notification)
}
// sendMessage writes a message to stdin
func (c *JSONRPCClient) sendMessage(message interface{}) error {
data, err := json.Marshal(message)
if err != nil {
return fmt.Errorf("failed to marshal message: %w", err)
}
c.mu.Lock()
defer c.mu.Unlock()
// Write Content-Length header + message
header := fmt.Sprintf("Content-Length: %d\r\n\r\n", len(data))
if _, err := c.stdin.Write([]byte(header)); err != nil {
return fmt.Errorf("failed to write header: %w", err)
}
if _, err := c.stdin.Write(data); err != nil {
return fmt.Errorf("failed to write message: %w", err)
}
return nil
}
// readLoop reads messages from stdout in a background goroutine
func (c *JSONRPCClient) readLoop() {
defer c.wg.Done()
reader := bufio.NewReader(c.stdout)
for c.running {
// Read Content-Length header
var contentLength int
for {
line, err := reader.ReadString('\n')
if err != nil {
// Only log unexpected errors (not EOF or closed pipe during shutdown)
if err != io.EOF && c.running {
fmt.Printf("Error reading header: %v\n", err)
}
return
}
// Check for blank line (end of headers)
if line == "\r\n" || line == "\n" {
break
}
// Parse Content-Length
var length int
if _, err := fmt.Sscanf(line, "Content-Length: %d", &length); err == nil {
contentLength = length
}
}
if contentLength == 0 {
continue
}
// Read message body
body := make([]byte, contentLength)
if _, err := io.ReadFull(reader, body); err != nil {
fmt.Printf("Error reading body: %v\n", err)
return
}
// Try to parse as request first (has both ID and Method)
var request JSONRPCRequest
if err := json.Unmarshal(body, &request); err == nil && request.Method != "" && len(request.ID) > 0 {
c.handleRequest(&request)
continue
}
// Try to parse as response (has ID but no Method)
var response JSONRPCResponse
if err := json.Unmarshal(body, &response); err == nil && len(response.ID) > 0 {
c.handleResponse(&response)
continue
}
// Try to parse as notification (has Method but no ID)
var notification JSONRPCNotification
if err := json.Unmarshal(body, ¬ification); err == nil && notification.Method != "" {
c.handleNotification(¬ification)
continue
}
}
}
// handleResponse dispatches a response to the waiting request
func (c *JSONRPCClient) handleResponse(response *JSONRPCResponse) {
var id string
if err := json.Unmarshal(response.ID, &id); err != nil {
return // ignore responses with non-string IDs
}
c.mu.Lock()
responseChan, ok := c.pendingRequests[id]
c.mu.Unlock()
if ok {
select {
case responseChan <- response:
default:
}
}
}
// handleNotification dispatches a notification to the handler
func (c *JSONRPCClient) handleNotification(notification *JSONRPCNotification) {
c.mu.Lock()
handler := c.notificationHandler
c.mu.Unlock()
if handler != nil {
handler(notification.Method, notification.Params)
}
}
func (c *JSONRPCClient) handleRequest(request *JSONRPCRequest) {
c.mu.Lock()
handler := c.requestHandlers[request.Method]
c.mu.Unlock()
if handler == nil {
c.sendErrorResponse(request.ID, -32601, fmt.Sprintf("Method not found: %s", request.Method), nil)
return
}
go func() {
defer func() {
if r := recover(); r != nil {
c.sendErrorResponse(request.ID, -32603, fmt.Sprintf("request handler panic: %v", r), nil)
}
}()
result, err := handler(request.Params)
if err != nil {
c.sendErrorResponse(request.ID, err.Code, err.Message, err.Data)
return
}
if result == nil {
result = make(map[string]interface{})
}
c.sendResponse(request.ID, result)
}()
}
func (c *JSONRPCClient) sendResponse(id json.RawMessage, result map[string]interface{}) {
response := JSONRPCResponse{
JSONRPC: "2.0",
ID: id,
Result: result,
}
if err := c.sendMessage(response); err != nil {
fmt.Printf("Failed to send JSON-RPC response: %v\n", err)
}
}
func (c *JSONRPCClient) sendErrorResponse(id json.RawMessage, code int, message string, data map[string]interface{}) {
response := JSONRPCResponse{
JSONRPC: "2.0",
ID: id,
Error: &JSONRPCError{
Code: code,
Message: message,
Data: data,
},
}
if err := c.sendMessage(response); err != nil {
fmt.Printf("Failed to send JSON-RPC error response: %v\n", err)
}
}
// generateUUID generates a simple UUID v4 without external dependencies
func generateUUID() string {
b := make([]byte, 16)
rand.Read(b)
b[6] = (b[6] & 0x0f) | 0x40 // Version 4
b[8] = (b[8] & 0x3f) | 0x80 // Variant is 10
return fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:])
}
func init() {
}