Categorygithub.com/openweb3/go-rpc-provider
modulepackage
0.3.4
Repository: https://github.com/openweb3/go-rpc-provider.git
Documentation: pkg.go.dev

# README

go-rpc-provider

go-rpc-provider is enhanced on the basis of the package github.com/ethereum/go-ethereum/rpc

Features

  • Replace HTTP by fasthttp to improve performance of concurrency HTTP request
  • Refactor function func (err *jsonError) Error() to return 'data' of JSON RPC response
  • Set HTTP request header 'Connection' to 'Keep-Alive' to reuse TCP connection for avoiding the amount of TIME_WAIT on the RPC server, and the RPC server also need to set 'Connection' to 'Keep-Alive'.
  • Add remote client address to WebSocket context for tracing.
  • Add client pointer to context when new RPC connection for tracing.
  • Add HTTP request in RPC context in function ServeHTTP for tracing.
  • Support variadic arguments for RPC service
  • Add provider wrapper for convenient extension
  • Support MiddlewarableProvider to extend provider features, currently support
    • NewRetriableProvider to create MiddlewarableProvider instance with auto-retry when failing
    • NewTimeoutableProvider to create MiddlewarableProvider instance with timeout when CallContext/BatchCallContext
    • NewLoggerProvider to create MiddlewarableProvider instance for logging request/response when CallContext/BatchCallContext
    • NewProviderWithOption to create MiddlewarableProvider instance includes all features of NewRetriableProvider, NewTimeoutableProvider and NewLoggerProvider

Usage

rpc.Client implements a provider interface, so you could use it as a provider

create a simple RPC client

	rpc.Dial("http://localhost:8545")

create a simple RPC client with context for canceling or timeout the initial connection establishment

	rpc.DialContext("http://localhost:8545")

For feature extension, we apply MiddlewarableProvider for hook CallContext/BatchCallContext/Subscribe, such as log rpc request and response or cache environment variable in the context.

you can create MiddlewarableProvider by NewMiddlewarableProvider and pass the provider created below as the parameter

	p, e := rpc.DialContext(context.Background(), "http://localhost:8545")
	if e != nil {
		t.Fatal(e)
	}
	mp := NewMiddlewarableProvider(p)
	mp.HookCallContext(callContextLogMiddleware)
	mp.HookCallContext(otherMiddleware)

the callContextLogMiddleware is like

func callContextLogMiddleware(f providers.CallContextFunc) providers.CallContextFunc {
	return func(ctx context.Context, resultPtr interface{}, method string, args ...interface{}) error {
		fmt.Printf("request %v %v\n", method, args)
		err := f(ctx, resultPtr, method, args...)
		j, _ := json.Marshal(resultPtr)
		fmt.Printf("response %s\n", j)
		return err
	}
}

The simplest way to create middlewarable provider is by providers.NewBaseProvider. It will create a MiddlewareProvider and it could set the max connection number for client with the server.

For example, created by providers.NewBaseProvider` and use the logging middleware created below to hook by HookCallContext

	p, e := warpper.NewBaseProvider(context.Background(), "http://localhost:8545")
	if e != nil {
		return e
	}
	p.HookCallContext(callLogMiddleware)
	NewClientWithProvider(p)

However, we also apply several functions to create kinds of instances of MiddlewarableProvider. The functions are providers.NewTimeoutableProvider, providers.NewRetriableProvider.

And the simplest way to create NewMiddlewarableProvider with retry and timeout features is to use providers.NewProviderWithOption

Server

The rpc package is extended based on go-ethereum. And we extend RPC server features for hook on handle requests on both "batch call msg" and "call msg".

Usage

Both rpc.HookHandleMsg and rpc.HookHandleBatch are globally effective, it will effective to both HTTP and Websocket when hook once.

Note:

  • HookHandleCallMsg works when "call msg" and "batch call msg", for example, batch requests [ jsonrpc_a, jsonrpc_b ], it will trigger function nested by HookHandleBatch once and function netsed by HookHandleCallMsg twice
  • HookHandleBatch works only when "call msg"
	rpc.HookHandleCallMsg(func(next rpc.HandleCallMsgFunc) rpc.HandleCallMsgFunc {
		return func(ctx context.Context, msg *rpc.JsonRpcMessage) *rpc.JsonRpcMessage {
			fmt.Printf("request call msg %v\n", utils.PrettyJSON(msg))
			fmt.Printf("callmsg -- request context key of %v value %v\n", "test-k", ctx.Value("test-k"))
			result := next(ctx, msg)
			fmt.Printf("response call msg %v\n", utils.PrettyJSON(result))
			return result
		}
	})
	rpc.HookHandleBatch(func(next rpc.HandleBatchFunc) rpc.HandleBatchFunc {
		return func(ctx context.Context, msgs []*rpc.JsonRpcMessage) []*rpc.JsonRpcMessage {
			fmt.Printf("request batch %v\n", utils.PrettyJSON(msgs))
			fmt.Printf("batch -- request context key of %v value %v\n", "test-k", ctx.Value("test-k"))
			results := next(ctx, msgs)
			fmt.Printf("response batch %v\n", utils.PrettyJSON(results))
			return results
		}
	})

# Packages

No description provided by the author
No description provided by the author
No description provided by the author

# Functions

No description provided by the author
No description provided by the author
Client retrieves the client from the context, if any.
Dial creates a new client for the given URL.
DialContext creates a new RPC client, just like Dial.
DialHTTP creates a new RPC client that connects to an RPC server over HTTP.
DialHTTPWithClient creates a new RPC client that connects to an RPC server over HTTP using the provided HTTP Client.
DialInProc attaches an in-process connection to the given RPC server.
DialIO creates a client which uses the given IO channels.
DialIPC create a new IPC client that connects to the given endpoint.
DialStdIO creates a client on stdin/stdout.
DialWebsocket creates a new RPC client that communicates with a JSON-RPC server that is listening on the given endpoint.
DialWebsocketWithDialer creates a new RPC client that communicates with a JSON-RPC server that is listening on the given endpoint using the provided dialer.
No description provided by the author
No description provided by the author
NewCodec creates a codec on the given connection.
NewFuncCodec creates a codec which uses the given functions to read and write.
NewID returns a new, random ID.
NewServer creates a new server instance with no registered handlers.
NotifierFromContext returns the Notifier value stored in ctx, if any.
No description provided by the author
StartIPCEndpoint starts an IPC endpoint.

# Constants

No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
OptionMethodInvocation is an indication that the codec supports RPC method calls.
support pub sub.
No description provided by the author
No description provided by the author

# Variables

DefaultHTTPTimeouts represents the default timeout values used if further configuration is not provided.
No description provided by the author
No description provided by the author
ErrNotificationsUnsupported is returned when the connection doesn't support notifications.
ErrNotificationNotFound is returned when the notification for the given id is not found.
No description provided by the author
PreventMessagesWithouID is a HandleCallMsgMiddleware for preventing messages without ID.

# Structs

API describes the set of methods offered over the RPC interface.
BatchElem is an element in a batch request.
No description provided by the author
Client represents a connection to an RPC server.
ClientSubscription is a subscription established through the Client's Subscribe or EthSubscribe methods.
No description provided by the author
HTTPTimeouts represents the configuration params for the HTTP RPC server.
Notifier is tied to a RPC connection that supports subscriptions.
PeerInfo contains information about the remote end of the network connection.
No description provided by the author
RPCService gives meta information about the server.
Server is an RPC server.
No description provided by the author
A Subscription is created by a notifier and tied to that notifier.
No description provided by the author

# Interfaces

Conn is a subset of the methods of net.Conn which are sufficient for ServerCodec.
ConnRemoteAddr wraps the RemoteAddr operation, which returns a description of the peer address of a connection.
Error wraps RPC errors, which contain an error code in addition to the message.
ServerCodec implements reading, parsing and writing RPC messages for the server side of a RPC session.

# Type aliases

No description provided by the author
No description provided by the author
CodecOption specifies which type of messages a codec supports.
client connection handler.
DecimalOrHex unmarshals a non-negative decimal or hex parameter into a uint64.
No description provided by the author
No description provided by the author
Handle CallMsg Middleware.
No description provided by the author
ID defines a pseudo random number that is used to identify RPC subscriptions.
No description provided by the author
No description provided by the author