github.com/calmw/ethereum@v0.1.1/rpc/server.go (about)

     1  // Copyright 2015 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-ethereum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package rpc
    18  
    19  import (
    20  	"context"
    21  	"io"
    22  	"sync"
    23  	"sync/atomic"
    24  
    25  	"github.com/calmw/ethereum/log"
    26  )
    27  
    28  const MetadataApi = "rpc"
    29  const EngineApi = "engine"
    30  
    31  // CodecOption specifies which type of messages a codec supports.
    32  //
    33  // Deprecated: this option is no longer honored by Server.
    34  type CodecOption int
    35  
    36  const (
    37  	// OptionMethodInvocation is an indication that the codec supports RPC method calls
    38  	OptionMethodInvocation CodecOption = 1 << iota
    39  
    40  	// OptionSubscriptions is an indication that the codec supports RPC notifications
    41  	OptionSubscriptions = 1 << iota // support pub sub
    42  )
    43  
    44  // Server is an RPC server.
    45  type Server struct {
    46  	services serviceRegistry
    47  	idgen    func() ID
    48  
    49  	mutex  sync.Mutex
    50  	codecs map[ServerCodec]struct{}
    51  	run    atomic.Bool
    52  }
    53  
    54  // NewServer creates a new server instance with no registered handlers.
    55  func NewServer() *Server {
    56  	server := &Server{
    57  		idgen:  randomIDGenerator(),
    58  		codecs: make(map[ServerCodec]struct{}),
    59  	}
    60  	server.run.Store(true)
    61  	// Register the default service providing meta information about the RPC service such
    62  	// as the services and methods it offers.
    63  	rpcService := &RPCService{server}
    64  	server.RegisterName(MetadataApi, rpcService)
    65  	return server
    66  }
    67  
    68  // RegisterName creates a service for the given receiver type under the given name. When no
    69  // methods on the given receiver match the criteria to be either a RPC method or a
    70  // subscription an error is returned. Otherwise a new service is created and added to the
    71  // service collection this server provides to clients.
    72  func (s *Server) RegisterName(name string, receiver interface{}) error {
    73  	return s.services.registerName(name, receiver)
    74  }
    75  
    76  // ServeCodec reads incoming requests from codec, calls the appropriate callback and writes
    77  // the response back using the given codec. It will block until the codec is closed or the
    78  // server is stopped. In either case the codec is closed.
    79  //
    80  // Note that codec options are no longer supported.
    81  func (s *Server) ServeCodec(codec ServerCodec, options CodecOption) {
    82  	defer codec.close()
    83  
    84  	if !s.trackCodec(codec) {
    85  		return
    86  	}
    87  	defer s.untrackCodec(codec)
    88  
    89  	c := initClient(codec, s.idgen, &s.services)
    90  	<-codec.closed()
    91  	c.Close()
    92  }
    93  
    94  func (s *Server) trackCodec(codec ServerCodec) bool {
    95  	s.mutex.Lock()
    96  	defer s.mutex.Unlock()
    97  
    98  	if !s.run.Load() {
    99  		return false // Don't serve if server is stopped.
   100  	}
   101  	s.codecs[codec] = struct{}{}
   102  	return true
   103  }
   104  
   105  func (s *Server) untrackCodec(codec ServerCodec) {
   106  	s.mutex.Lock()
   107  	defer s.mutex.Unlock()
   108  
   109  	delete(s.codecs, codec)
   110  }
   111  
   112  // serveSingleRequest reads and processes a single RPC request from the given codec. This
   113  // is used to serve HTTP connections. Subscriptions and reverse calls are not allowed in
   114  // this mode.
   115  func (s *Server) serveSingleRequest(ctx context.Context, codec ServerCodec) {
   116  	// Don't serve if server is stopped.
   117  	if !s.run.Load() {
   118  		return
   119  	}
   120  
   121  	h := newHandler(ctx, codec, s.idgen, &s.services)
   122  	h.allowSubscribe = false
   123  	defer h.close(io.EOF, nil)
   124  
   125  	reqs, batch, err := codec.readBatch()
   126  	if err != nil {
   127  		if err != io.EOF {
   128  			resp := errorMessage(&invalidMessageError{"parse error"})
   129  			codec.writeJSON(ctx, resp, true)
   130  		}
   131  		return
   132  	}
   133  	if batch {
   134  		h.handleBatch(reqs)
   135  	} else {
   136  		h.handleMsg(reqs[0])
   137  	}
   138  }
   139  
   140  // Stop stops reading new requests, waits for stopPendingRequestTimeout to allow pending
   141  // requests to finish, then closes all codecs which will cancel pending requests and
   142  // subscriptions.
   143  func (s *Server) Stop() {
   144  	s.mutex.Lock()
   145  	defer s.mutex.Unlock()
   146  
   147  	if s.run.CompareAndSwap(true, false) {
   148  		log.Debug("RPC server shutting down")
   149  		for codec := range s.codecs {
   150  			codec.close()
   151  		}
   152  	}
   153  }
   154  
   155  // RPCService gives meta information about the server.
   156  // e.g. gives information about the loaded modules.
   157  type RPCService struct {
   158  	server *Server
   159  }
   160  
   161  // Modules returns the list of RPC services with their version number
   162  func (s *RPCService) Modules() map[string]string {
   163  	s.server.services.mu.Lock()
   164  	defer s.server.services.mu.Unlock()
   165  
   166  	modules := make(map[string]string)
   167  	for name := range s.server.services.services {
   168  		modules[name] = "1.0"
   169  	}
   170  	return modules
   171  }
   172  
   173  // PeerInfo contains information about the remote end of the network connection.
   174  //
   175  // This is available within RPC method handlers through the context. Call
   176  // PeerInfoFromContext to get information about the client connection related to
   177  // the current method call.
   178  type PeerInfo struct {
   179  	// Transport is name of the protocol used by the client.
   180  	// This can be "http", "ws" or "ipc".
   181  	Transport string
   182  
   183  	// Address of client. This will usually contain the IP address and port.
   184  	RemoteAddr string
   185  
   186  	// Additional information for HTTP and WebSocket connections.
   187  	HTTP struct {
   188  		// Protocol version, i.e. "HTTP/1.1". This is not set for WebSocket.
   189  		Version string
   190  		// Header values sent by the client.
   191  		UserAgent string
   192  		Origin    string
   193  		Host      string
   194  	}
   195  }
   196  
   197  type peerInfoContextKey struct{}
   198  
   199  // PeerInfoFromContext returns information about the client's network connection.
   200  // Use this with the context passed to RPC method handler functions.
   201  //
   202  // The zero value is returned if no connection info is present in ctx.
   203  func PeerInfoFromContext(ctx context.Context) PeerInfo {
   204  	info, _ := ctx.Value(peerInfoContextKey{}).(PeerInfo)
   205  	return info
   206  }