Skip to content

Commit

Permalink
Add subscription support to jsonrpc package
Browse files Browse the repository at this point in the history
  • Loading branch information
joshklop committed Jul 28, 2023
1 parent 3362f70 commit 7329d5d
Show file tree
Hide file tree
Showing 7 changed files with 408 additions and 73 deletions.
2 changes: 1 addition & 1 deletion jsonrpc/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ func (h *HTTP) ServeHTTP(writer http.ResponseWriter, req *http.Request) {
if conn == nil {
return
}
if err := h.rpc.Handle(conn); err != nil {
if err := h.rpc.Handle(req.Context(), conn); err != nil {
writer.WriteHeader(http.StatusInternalServerError)
}

Check warning on line 105 in jsonrpc/http.go

View check run for this annotation

Codecov / codecov/patch

jsonrpc/http.go#L104-L105

Added lines #L104 - L105 were not covered by tests
}
34 changes: 27 additions & 7 deletions jsonrpc/memconn.go
Original file line number Diff line number Diff line change
@@ -1,29 +1,49 @@
package jsonrpc

import "io"
import (
"context"
"errors"
"io"
)

// MemConn is a simple in-memory JSON RPC connection.
type MemConn struct {
ctx context.Context
send chan<- []byte
recv <-chan []byte
}

func NewMemConn(send chan<- []byte, recv <-chan []byte) *MemConn {
func NewMemConn(ctx context.Context, send chan<- []byte, recv <-chan []byte) *MemConn {
return &MemConn{
ctx: ctx,
send: send,
recv: recv,
}
}

func (m *MemConn) Read(p []byte) (int, error) {
msg, ok := <-m.recv
if !ok {
return 0, io.EOF
select {
case <-m.ctx.Done():
return 0, ErrRead{
Inner: m.ctx.Err(),
}
case msg, ok := <-m.recv:
if !ok {
return 0, io.EOF
}

Check warning on line 33 in jsonrpc/memconn.go

View check run for this annotation

Codecov / codecov/patch

jsonrpc/memconn.go#L32-L33

Added lines #L32 - L33 were not covered by tests
return copy(p, msg), nil
}
return copy(p, msg), nil
}

func (m *MemConn) Write(p []byte) (l int, err error) {
defer func() {
if panicked := recover(); panicked != nil {
l = 0
err = errors.New("memconn: write on closed connection")
}

Check warning on line 43 in jsonrpc/memconn.go

View check run for this annotation

Codecov / codecov/patch

jsonrpc/memconn.go#L41-L43

Added lines #L41 - L43 were not covered by tests
}()
m.send <- p
return len(p), nil
l = len(p)
err = nil
return
}
Loading

0 comments on commit 7329d5d

Please sign in to comment.