| 🛟 Updated. 28d5985 k33g 4h ago | 1 | package jsonrpc |
| 2 | |
| 3 | import ( |
| 4 | "encoding/json" |
| 5 | "sync" |
| 6 | ) |
| 7 | |
| 8 | // Request is a request the peer sent, waiting for an answer. |
| 9 | // |
| 10 | // It exists so that an answer can be given later than the moment the request |
| 11 | // arrived. A language server's questions can all be answered on the spot; an |
| 12 | // agent asking permission to run a command cannot be, because the answer comes |
| 13 | // from a dialog somebody has to look at, and opening one belongs to the |
| 14 | // goroutine that draws. |
| 15 | // |
| 16 | // func (a *App) onRequest(req *jsonrpc.Request) { |
| 17 | // if req.Method != "session/request_permission" { |
| 18 | // req.Reply(nil, &jsonrpc.ResponseError{Code: jsonrpc.CodeMethodNotFound, Message: req.Method}) |
| 19 | // return |
| 20 | // } |
| 21 | // a.pendingPermission = req // the event loop opens the dialog and replies |
| 22 | // } |
| 23 | type Request struct { |
| 24 | // Method is what the peer asked for. |
| 25 | Method string |
| 26 | // Params are its parameters, still encoded. Decode them into whatever the |
| 27 | // method's parameters are. |
| 28 | Params json.RawMessage |
| 29 | |
| 30 | conn *Conn |
| 31 | id json.RawMessage |
| 32 | once sync.Once |
| 33 | } |
| 34 | |
| 35 | // Reply answers the request, with result when err is nil and with err |
| 36 | // otherwise. |
| 37 | // |
| 38 | // It may be called from any goroutine and at any time after the request |
| 39 | // arrived. Only the first call has any effect: a permission dialog that is |
| 40 | // answered and then torn down by the window closing would otherwise write two |
| 41 | // responses carrying one id. |
| 42 | // |
| 43 | // A failure to write the answer is not reported. The only reason it can fail |
| 44 | // is that the peer has gone, which the read loop sees for itself, and there is |
| 45 | // nothing a caller could usefully do about it. |
| 46 | // |
| 47 | // req.Reply(map[string]any{"outcome": outcome}, nil) |
| 48 | // req.Reply(nil, errors.New("no such file")) |
| 49 | func (r *Request) Reply(result any, err error) { |
| 50 | r.once.Do(func() { r.reply(result, err) }) |
| 51 | } |
| 52 | |
| 53 | // reply encodes one answer and writes it. |
| 54 | func (r *Request) reply(result any, err error) { |
| 55 | answer := message{JSONRPC: Version, ID: r.id} |
| 56 | |
| 57 | switch { |
| 58 | case err != nil: |
| 59 | answer.Error = asResponseError(err) |
| 60 | default: |
| 61 | encoded, marshalErr := json.Marshal(result) |
| 62 | if marshalErr != nil { |
| 63 | answer.Error = &ResponseError{Code: CodeInternalError, Message: marshalErr.Error()} |
| 64 | } else { |
| 65 | answer.Result = encoded |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | _ = r.conn.write(&answer) |
| 70 | } |