Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 11 additions & 6 deletions conn.go
Original file line number Diff line number Diff line change
Expand Up @@ -180,24 +180,29 @@ func (c *Conn) SendResponse(ctx context.Context, resp *Response) error {

func (c *Conn) close(cause error) error {
c.mu.Lock()
defer c.mu.Unlock()

if c.closed {
c.mu.Unlock()
return ErrClosed
}
c.closed = true

for _, call := range c.pending {
close(call.done)
}

close(c.disconnect)
c.mu.Unlock()

c.cancelCtx()
err := c.stream.Close()

// The logger may call back into c, so invoke it only after shutdown is
// complete and c.mu is unlocked.
if cause != nil && cause != io.EOF && cause != io.ErrUnexpectedEOF {
c.logger.Printf("jsonrpc2: protocol error: %v\n", cause)
}

close(c.disconnect)
c.cancelCtx()
c.closed = true
return c.stream.Close()
return err
}

func (c *Conn) readMessages(ctx context.Context) {
Expand Down
32 changes: 32 additions & 0 deletions conn_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,38 @@ func TestConn_DisconnectNotify(t *testing.T) {
connA.Write([]byte("invalid json"))
assertDisconnect(t, c, connB)
})

t.Run("protocol error logger uses connection", func(t *testing.T) {
connA, connB := net.Pipe()
logResult := make(chan error, 1)
var c *jsonrpc2.Conn
c = jsonrpc2.NewConn(
context.Background(),
jsonrpc2.NewPlainObjectStream(connB),
noopHandler{},
jsonrpc2.SetLogger(connNotifyLogger{conn: &c, result: logResult}),
)
connA.Write([]byte("invalid json"))
assertDisconnect(t, c, connB)

select {
case err := <-logResult:
if err != jsonrpc2.ErrClosed {
t.Errorf("logger Notify: got %v, want %v", err, jsonrpc2.ErrClosed)
}
case <-time.After(200 * time.Millisecond):
t.Error("logger blocked using connection")
}
})
}

type connNotifyLogger struct {
conn **jsonrpc2.Conn
result chan<- error
}

func (l connNotifyLogger) Printf(string, ...interface{}) {
l.result <- (*l.conn).Notify(context.Background(), "log", nil)
}

func TestConn_Close(t *testing.T) {
Expand Down
Loading