-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
240 lines (216 loc) · 5.98 KB
/
client.go
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
package jsonrpc
import (
"errors"
"io"
"log"
"net"
"sync"
"github.com/patdz/jsonrpc/codec"
"github.com/patdz/jsonrpc/proto"
)
var debugLog = false
var ErrShutdown = errors.New("connection is shut down")
// Call represents an active RPC.
type Call struct {
Request proto.AppRequest // The argument to the function (*struct).
Reply *proto.AppResponse // The reply from the function (*struct).
Error *proto.Error
Done chan *Call // Receives *Call when Go is complete.
}
// Client represents an RPC Client.
// There may be multiple outstanding Calls associated
// with a single Client, and a Client may be used by
// multiple goroutines simultaneously.
type Client struct {
codec proto.ClientCodec
reqMutex sync.Mutex // protects following
mutex sync.Mutex // protects following
seq uint64
pending map[uint64]*Call
closing bool // user has called Close
shutdown bool // server has told us to stop
newMessageChan chan *proto.Response
errorChan chan *proto.Error
}
func (client *Client) send(call *Call) {
client.reqMutex.Lock()
defer client.reqMutex.Unlock()
// Register this call.
client.mutex.Lock()
if client.shutdown || client.closing {
client.mutex.Unlock()
call.Error = &proto.Error{Code: proto.ErrorShutdown, Message: "client shutdown"}
call.done()
return
}
seq := client.seq
client.seq++
client.pending[seq] = call
client.mutex.Unlock()
call.Request.SetSeq(seq)
// Encode and send the request.
err := client.codec.WriteRequest(call.Request)
if err != nil {
client.mutex.Lock()
call = client.pending[seq]
delete(client.pending, seq)
client.mutex.Unlock()
if call != nil {
call.Error = &proto.Error{Code: proto.ErrorShutdown, Message: err.Error()}
call.done()
}
}
}
func (client *Client) input() {
var err error
for {
response := &proto.Response{}
err = client.codec.ReadResponseHeader(response)
if err != nil {
if client.errorChan != nil {
client.errorChan <- &proto.Error{
Code: proto.ErrorCodeInvalidResponse,
Message: err.Error(),
}
}
break
}
seq := response.ID
if seq == 0 {
if client.newMessageChan != nil {
client.newMessageChan <- response
}
continue
}
var call *Call
client.mutex.Lock()
call = client.pending[seq]
delete(client.pending, seq)
client.mutex.Unlock()
switch {
case call == nil:
if client.errorChan != nil {
client.errorChan <- &proto.Error{
Code: proto.ErrorCodeInvalidResponse,
Message: "caller is null",
}
}
case response.CheckError != nil:
if call.Reply != nil {
call.Reply.Resp = response
}
call.Error = response.CheckError
call.done()
default:
if call.Reply != nil {
call.Error = client.codec.ReadResponseBody(response, call.Reply)
}
call.done()
}
}
// Terminate pending calls.
client.reqMutex.Lock()
client.mutex.Lock()
client.shutdown = true
closing := client.closing
if err == io.EOF {
if closing {
err = ErrShutdown
} else {
err = io.ErrUnexpectedEOF
}
}
for _, call := range client.pending {
call.Error = &proto.Error{
Code: proto.ErrorShutdown,
Message: "shutdown",
}
call.done()
}
client.mutex.Unlock()
client.reqMutex.Unlock()
if client.errorChan != nil {
client.errorChan <- &proto.Error{
Code: proto.ErrorShutdown,
}
}
}
func (call *Call) done() {
select {
case call.Done <- call:
// ok
default:
// We don't want to block here. It is the caller's responsibility to make
// sure the channel has enough buffer space. See comment in Go().
if debugLog {
log.Println("rpc: discarding Call reply due to insufficient Done chan capacity")
}
}
}
// NewClientWithCodec is like NewClient but uses the specified
// codec to encode requests and decode responses.
func NewClientWithCodec(notifyChan *proto.NotificationChan, codec proto.ClientCodec) *Client {
var newMessageChan chan *proto.Response
var errorChan chan *proto.Error
if notifyChan != nil {
newMessageChan = notifyChan.NewMessageChan
errorChan = notifyChan.ErrorChan
}
client := &Client{
codec: codec,
pending: make(map[uint64]*Call),
newMessageChan: newMessageChan,
errorChan: errorChan,
seq: 1,
}
go client.input()
return client
}
// Close calls the underlying codec's Close method. If the connection is already
// shutting down, ErrShutdown is returned.
func (client *Client) Close() error {
client.mutex.Lock()
if client.closing {
client.mutex.Unlock()
return ErrShutdown
}
client.closing = true
client.mutex.Unlock()
return client.codec.Close()
}
// Go invokes the function asynchronously. It returns the Call structure representing
// the invocation. The done channel will signal when the call is complete by returning
// the same Call object. If done is nil, Go will allocate a new channel.
// If non-nil, done must be buffered or Go will deliberately crash.
func (client *Client) Go(req proto.AppRequest, reply *proto.AppResponse, done chan *Call) *Call {
call := new(Call)
call.Request = req
call.Reply = reply
if done == nil {
done = make(chan *Call, 10) // buffered.
} else {
// If caller passes done != nil, it must arrange that
// done has enough buffer for the number of simultaneous
// RPCs that will be using that channel. If the channel
// is totally unbuffered, it's best not to run at all.
if cap(done) == 0 {
log.Panic("rpc: done channel is unbuffered")
}
}
call.Done = done
client.send(call)
return call
}
// Call invokes the named function, waits for it to complete, and returns its error status.
func (client *Client) Call(req proto.AppRequest, reply *proto.AppResponse) *proto.Error {
call := <-client.Go(req, reply, make(chan *Call, 1)).Done
return call.Error
}
// Dial connects to a JSON-RPC server at the specified network address.
func Dial(notifyChan *proto.NotificationChan, ob *proto.DebugObserver, network, address string) (*Client, error) {
conn, err := net.Dial(network, address)
if err != nil {
return nil, err
}
return NewClientWithCodec(notifyChan, codec.NewClientCodec(ob, conn)), err
}