| 1 | // Copyright 2018 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 jsonrpc2 |
| 6 | |
| 7 | import ( |
| 8 | "encoding/json" |
| 9 | "errors" |
| 10 | "fmt" |
| 11 | ) |
| 12 | |
| 13 | // ID is a Request identifier, which is defined by the spec to be a string, integer, or null. |
| 14 | // https://www.jsonrpc.org/specification#request_object |
| 15 | type ID struct { |
| 16 | value any |
| 17 | } |
| 18 | |
| 19 | // MakeID coerces the given Go value to an ID. The value is assumed to be the |
| 20 | // default JSON marshaling of a Request identifier -- nil, float64, or string. |
| 21 | // |
| 22 | // Returns an error if the value type was a valid Request ID type. |
| 23 | // |
| 24 | // TODO: ID can't be a json.Marshaler/Unmarshaler, because we want to omitzero. |
| 25 | // Simplify this package by making ID json serializable once we can rely on |
| 26 | // omitzero. |
| 27 | func MakeID(v any) (ID, error) { |
| 28 | switch v := v.(type) { |
| 29 | case nil: |
| 30 | return ID{}, nil |
| 31 | case float64: |
| 32 | return Int64ID(int64(v)), nil |
| 33 | case string: |
| 34 | return StringID(v), nil |
| 35 | } |
| 36 | return ID{}, fmt.Errorf("%w: invalid ID type %T", ErrParse, v) |
| 37 | } |
| 38 | |
| 39 | // Message is the interface to all jsonrpc2 message types. |
| 40 | // They share no common functionality, but are a closed set of concrete types |
| 41 | // that are allowed to implement this interface. The message types are *Request |
| 42 | // and *Response. |
| 43 | type Message interface { |
| 44 | // marshal builds the wire form from the API form. |
| 45 | // It is private, which makes the set of Message implementations closed. |
| 46 | marshal(to *wireCombined) |
| 47 | } |
| 48 | |
| 49 | // Request is a Message sent to a peer to request behavior. |
| 50 | // If it has an ID it is a call, otherwise it is a notification. |
| 51 | type Request struct { |
| 52 | // ID of this request, used to tie the Response back to the request. |
| 53 | // This will be nil for notifications. |
| 54 | ID ID |
| 55 | // Method is a string containing the method name to invoke. |
| 56 | Method string |
| 57 | // Params is either a struct or an array with the parameters of the method. |
| 58 | Params json.RawMessage |
| 59 | } |
| 60 | |
| 61 | // Response is a Message used as a reply to a call Request. |
| 62 | // It will have the same ID as the call it is a response to. |
| 63 | type Response struct { |
| 64 | // result is the content of the response. |
| 65 | Result json.RawMessage |
| 66 | // err is set only if the call failed. |
| 67 | Error error |
| 68 | // id of the request this is a response to. |
| 69 | ID ID |
| 70 | } |
| 71 | |
| 72 | // StringID creates a new string request identifier. |
| 73 | func StringID(s string) ID { return ID{value: s} } |
| 74 | |
| 75 | // Int64ID creates a new integer request identifier. |
| 76 | func Int64ID(i int64) ID { return ID{value: i} } |
| 77 | |
| 78 | // IsValid returns true if the ID is a valid identifier. |
| 79 | // The default value for ID will return false. |
| 80 | func (id ID) IsValid() bool { return id.value != nil } |
| 81 | |
| 82 | // Raw returns the underlying value of the ID. |
| 83 | func (id ID) Raw() any { return id.value } |
| 84 | |
| 85 | // NewNotification constructs a new Notification message for the supplied |
| 86 | // method and parameters. |
| 87 | func NewNotification(method string, params any) (*Request, error) { |
| 88 | p, merr := marshalToRaw(params) |
| 89 | return &Request{Method: method, Params: p}, merr |
| 90 | } |
| 91 | |
| 92 | // NewCall constructs a new Call message for the supplied ID, method and |
| 93 | // parameters. |
| 94 | func NewCall(id ID, method string, params any) (*Request, error) { |
| 95 | p, merr := marshalToRaw(params) |
| 96 | return &Request{ID: id, Method: method, Params: p}, merr |
| 97 | } |
| 98 | |
| 99 | func (msg *Request) IsCall() bool { return msg.ID.IsValid() } |
| 100 | |
| 101 | func (msg *Request) marshal(to *wireCombined) { |
| 102 | to.ID = msg.ID.value |
| 103 | to.Method = msg.Method |
| 104 | to.Params = msg.Params |
| 105 | } |
| 106 | |
| 107 | // NewResponse constructs a new Response message that is a reply to the |
| 108 | // supplied. If err is set result may be ignored. |
| 109 | func NewResponse(id ID, result any, rerr error) (*Response, error) { |
| 110 | r, merr := marshalToRaw(result) |
| 111 | return &Response{ID: id, Result: r, Error: rerr}, merr |
| 112 | } |
| 113 | |
| 114 | func (msg *Response) marshal(to *wireCombined) { |
| 115 | to.ID = msg.ID.value |
| 116 | to.Error = toWireError(msg.Error) |
| 117 | to.Result = msg.Result |
| 118 | } |
| 119 | |
| 120 | func toWireError(err error) *WireError { |
| 121 | if err == nil { |
| 122 | // no error, the response is complete |
| 123 | return nil |
| 124 | } |
| 125 | if err, ok := err.(*WireError); ok { |
| 126 | // already a wire error, just use it |
| 127 | return err |
| 128 | } |
| 129 | result := &WireError{Message: err.Error()} |
| 130 | var wrapped *WireError |
| 131 | if errors.As(err, &wrapped) { |
| 132 | // if we wrapped a wire error, keep the code from the wrapped error |
| 133 | // but the message from the outer error |
| 134 | result.Code = wrapped.Code |
| 135 | } |
| 136 | return result |
| 137 | } |
| 138 | |
| 139 | func EncodeMessage(msg Message) ([]byte, error) { |
| 140 | wire := wireCombined{VersionTag: wireVersion} |
| 141 | msg.marshal(&wire) |
| 142 | data, err := json.Marshal(&wire) |
| 143 | if err != nil { |
| 144 | return data, fmt.Errorf("marshaling jsonrpc message: %w", err) |
| 145 | } |
| 146 | return data, nil |
| 147 | } |
| 148 | |
| 149 | // EncodeIndent is like EncodeMessage, but honors indents. |
| 150 | // TODO(rfindley): refactor so that this concern is handled independently. |
| 151 | // Perhaps we should pass in a json.Encoder? |
| 152 | func EncodeIndent(msg Message, prefix, indent string) ([]byte, error) { |
| 153 | wire := wireCombined{VersionTag: wireVersion} |
| 154 | msg.marshal(&wire) |
| 155 | data, err := json.MarshalIndent(&wire, prefix, indent) |
| 156 | if err != nil { |
| 157 | return data, fmt.Errorf("marshaling jsonrpc message: %w", err) |
| 158 | } |
| 159 | return data, nil |
| 160 | } |
| 161 | |
| 162 | func DecodeMessage(data []byte) (Message, error) { |
| 163 | msg := wireCombined{} |
| 164 | if err := json.Unmarshal(data, &msg); err != nil { |
| 165 | return nil, fmt.Errorf("unmarshaling jsonrpc message: %w", err) |
| 166 | } |
| 167 | if msg.VersionTag != wireVersion { |
| 168 | return nil, fmt.Errorf("invalid message version tag %q; expected %q", msg.VersionTag, wireVersion) |
| 169 | } |
| 170 | id, err := MakeID(msg.ID) |
| 171 | if err != nil { |
| 172 | return nil, err |
| 173 | } |
| 174 | if msg.Method != "" { |
| 175 | // has a method, must be a call |
| 176 | return &Request{ |
| 177 | Method: msg.Method, |
| 178 | ID: id, |
| 179 | Params: msg.Params, |
| 180 | }, nil |
| 181 | } |
| 182 | // no method, should be a response |
| 183 | if !id.IsValid() { |
| 184 | return nil, ErrInvalidRequest |
| 185 | } |
| 186 | resp := &Response{ |
| 187 | ID: id, |
| 188 | Result: msg.Result, |
| 189 | } |
| 190 | // we have to check if msg.Error is nil to avoid a typed error |
| 191 | if msg.Error != nil { |
| 192 | resp.Error = msg.Error |
| 193 | } |
| 194 | return resp, nil |
| 195 | } |
| 196 | |
| 197 | func marshalToRaw(obj any) (json.RawMessage, error) { |
| 198 | if obj == nil { |
| 199 | return nil, nil |
| 200 | } |
| 201 | data, err := json.Marshal(obj) |
| 202 | if err != nil { |
| 203 | return nil, err |
| 204 | } |
| 205 | return json.RawMessage(data), nil |
| 206 | } |