-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathjsonrpc2.go
More file actions
459 lines (406 loc) · 11.9 KB
/
jsonrpc2.go
File metadata and controls
459 lines (406 loc) · 11.9 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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
package jsonrpc2
import (
"bufio"
"crypto/rand"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"reflect"
"sync"
"sync/atomic"
)
// Error represents a JSON-RPC error response
type Error struct {
Code int `json:"code"`
Message string `json:"message"`
Data map[string]any `json:"data,omitempty"`
}
func (e *Error) Error() string {
return fmt.Sprintf("JSON-RPC Error %d: %s", e.Code, e.Message)
}
// Request represents a JSON-RPC 2.0 request
type Request struct {
JSONRPC string `json:"jsonrpc"`
ID json.RawMessage `json:"id"` // nil for notifications
Method string `json:"method"`
Params json.RawMessage `json:"params"`
}
func (r *Request) IsCall() bool {
return len(r.ID) > 0
}
// Response represents a JSON-RPC 2.0 response
type Response struct {
JSONRPC string `json:"jsonrpc"`
ID json.RawMessage `json:"id,omitempty"`
Result json.RawMessage `json:"result,omitempty"`
Error *Error `json:"error,omitempty"`
}
// NotificationHandler handles incoming notifications
type NotificationHandler func(method string, params json.RawMessage)
// RequestHandler handles incoming server requests and returns a result or error
type RequestHandler func(params json.RawMessage) (json.RawMessage, *Error)
// Client is a minimal JSON-RPC 2.0 client for stdio transport
type Client struct {
stdin io.WriteCloser
stdout io.ReadCloser
mu sync.Mutex
pendingRequests map[string]chan *Response
requestHandlers map[string]RequestHandler
running atomic.Bool
stopChan chan struct{}
wg sync.WaitGroup
processDone chan struct{} // closed when the underlying process exits
processErrorPtr *error // points to the process error
processErrorMu sync.RWMutex // protects processErrorPtr
onClose func() // called when the read loop exits unexpectedly
}
// NewClient creates a new JSON-RPC client
func NewClient(stdin io.WriteCloser, stdout io.ReadCloser) *Client {
return &Client{
stdin: stdin,
stdout: stdout,
pendingRequests: make(map[string]chan *Response),
requestHandlers: make(map[string]RequestHandler),
stopChan: make(chan struct{}),
}
}
// SetProcessDone sets a channel that will be closed when the process exits,
// and stores the error pointer that should be returned to pending/future requests.
// The error is read directly from the pointer after the channel closes, avoiding
// a race between an async goroutine and callers checking the error.
func (c *Client) SetProcessDone(done chan struct{}, errPtr *error) {
c.processDone = done
c.processErrorMu.Lock()
c.processErrorPtr = errPtr
c.processErrorMu.Unlock()
}
// getProcessError returns the process exit error if the process has exited.
// It reads directly from the stored error pointer, which is guaranteed to be
// set before the processDone channel is closed.
func (c *Client) getProcessError() error {
c.processErrorMu.RLock()
defer c.processErrorMu.RUnlock()
if c.processErrorPtr != nil {
return *c.processErrorPtr
}
return nil
}
// Start begins listening for messages in a background goroutine
func (c *Client) Start() {
c.running.Store(true)
c.wg.Add(1)
go c.readLoop()
}
// Stop stops the client and cleans up
func (c *Client) Stop() {
if !c.running.Load() {
return
}
c.running.Store(false)
close(c.stopChan)
// Close stdout to unblock the readLoop
if c.stdout != nil {
c.stdout.Close()
}
c.wg.Wait()
}
func NotificationHandlerFor[In any](handler func(params In)) RequestHandler {
return func(params json.RawMessage) (json.RawMessage, *Error) {
var in In
// If In is a pointer type, allocate the underlying value and unmarshal into it directly
var target any = &in
if t := reflect.TypeFor[In](); t.Kind() == reflect.Pointer {
in = reflect.New(t.Elem()).Interface().(In)
target = in
}
if err := json.Unmarshal(params, target); err != nil {
return nil, &Error{
Code: -32602,
Message: fmt.Sprintf("Invalid params: %v", err),
}
}
handler(in)
return nil, nil
}
}
// RequestHandlerFor creates a RequestHandler from a typed function
func RequestHandlerFor[In, Out any](handler func(params In) (Out, *Error)) RequestHandler {
return func(params json.RawMessage) (json.RawMessage, *Error) {
var in In
// If In is a pointer type, allocate the underlying value and unmarshal into it directly
var target any = &in
if t := reflect.TypeOf(in); t != nil && t.Kind() == reflect.Pointer {
in = reflect.New(t.Elem()).Interface().(In)
target = in
}
if err := json.Unmarshal(params, target); err != nil {
return nil, &Error{
Code: -32602,
Message: fmt.Sprintf("Invalid params: %v", err),
}
}
out, errj := handler(in)
if errj != nil {
return nil, errj
}
outData, err := json.Marshal(out)
if err != nil {
return nil, &Error{
Code: -32603,
Message: fmt.Sprintf("Failed to marshal response: %v", err),
}
}
return outData, nil
}
}
// SetRequestHandler registers a handler for incoming requests from the server
func (c *Client) 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 *Client) Request(method string, params any) (json.RawMessage, error) {
requestID := generateUUID()
// Create response channel
responseChan := make(chan *Response, 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()
}()
// Check if process already exited before sending
if c.processDone != nil {
select {
case <-c.processDone:
if err := c.getProcessError(); err != nil {
return nil, err
}
return nil, fmt.Errorf("process exited unexpectedly")
default:
// Process still running, continue
}
}
paramsData, err := json.Marshal(params)
if err != nil {
return nil, fmt.Errorf("failed to marshal params: %w", err)
}
// Send request
request := Request{
JSONRPC: "2.0",
ID: json.RawMessage(`"` + requestID + `"`),
Method: method,
Params: json.RawMessage(paramsData),
}
if err := c.sendMessage(request); err != nil {
return nil, fmt.Errorf("failed to send request: %w", err)
}
// Wait for response, also checking for process exit
if c.processDone != nil {
select {
case response := <-responseChan:
if response.Error != nil {
return nil, response.Error
}
return response.Result, nil
case <-c.processDone:
if err := c.getProcessError(); err != nil {
return nil, err
}
return nil, fmt.Errorf("process exited unexpectedly")
case <-c.stopChan:
return nil, fmt.Errorf("client stopped")
}
}
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 *Client) Notify(method string, params any) error {
paramsData, err := json.Marshal(params)
if err != nil {
return fmt.Errorf("failed to marshal params: %w", err)
}
notification := Request{
JSONRPC: "2.0",
Method: method,
Params: json.RawMessage(paramsData),
}
return c.sendMessage(notification)
}
// sendMessage writes a message to stdin
func (c *Client) sendMessage(message any) 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
}
// SetOnClose sets a callback invoked when the read loop exits unexpectedly
// (e.g. the underlying connection or process was lost).
func (c *Client) SetOnClose(fn func()) {
c.onClose = fn
}
// readLoop reads messages from stdout in a background goroutine
func (c *Client) readLoop() {
defer c.wg.Done()
defer func() {
// If still running, the read loop exited unexpectedly (process died or
// connection dropped). Notify the caller so it can update its state.
if c.onClose != nil && c.running.Load() {
c.onClose()
}
}()
reader := bufio.NewReader(c.stdout)
for c.running.Load() {
// 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 && !errors.Is(err, os.ErrClosed) && c.running.Load() {
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 {
// Only log unexpected errors (not EOF or closed pipe during shutdown)
if err != io.EOF && !errors.Is(err, os.ErrClosed) && c.running.Load() {
fmt.Printf("Error reading body: %v\n", err)
}
return
}
// Try to parse as request first (has both ID and Method)
var request Request
if err := json.Unmarshal(body, &request); err == nil && request.Method != "" {
c.handleRequest(&request)
continue
}
// Try to parse as response (has ID but no Method)
var response Response
if err := json.Unmarshal(body, &response); err == nil && len(response.ID) > 0 {
c.handleResponse(&response)
continue
}
}
}
// handleResponse dispatches a response to the waiting request
func (c *Client) handleResponse(response *Response) {
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:
}
}
}
func (c *Client) handleRequest(request *Request) {
c.mu.Lock()
handler := c.requestHandlers[request.Method]
c.mu.Unlock()
if handler == nil {
if request.IsCall() {
c.sendErrorResponse(request.ID, -32601, fmt.Sprintf("Method not found: %s", request.Method), nil)
}
return
}
// Notifications run synchronously, calls run in a goroutine to avoid blocking
if !request.IsCall() {
handler(request.Params)
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
}
c.sendResponse(request.ID, result)
}()
}
func (c *Client) sendResponse(id json.RawMessage, result json.RawMessage) {
response := Response{
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 *Client) sendErrorResponse(id json.RawMessage, code int, message string, data map[string]any) {
response := Response{
JSONRPC: "2.0",
ID: id,
Error: &Error{
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:])
}