rpc

package module
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 27, 2021 License: BSD-3-Clause Imports: 15 Imported by: 0

README

RPC Package

Go Reference Go Report Card Build Status

Based off of (copied from) the net/rpc package with the following changes:

go get -u github.com/renevo/rpc
  • Server and Client context.Context implementations.
  • Header support
    • Client Header Injection
    • Server Header Inspection and Injection
  • Server Middleware
  • Requests now have a unique ID rather than a Sequence number

The following features have been removed:

  • DialHTTP
  • ServeHTTP
  • HandleHTTP

The HTTP functionality could be added to this relatively easily through server.ServeRequest

Stability

This API is mostly stable, however it will not be given a 1.x release until it is.

Documentation

Overview

Package rpc provides access to the exported methods of an object across a network or other I/O connection. A server registers an object, making it visible as a service with the name of the type of the object. After registration, exported methods of the object will be accessible remotely. A server may register multiple objects (services) of different types but it is an error to register multiple objects of the same type.

Only methods that satisfy these criteria will be made available for remote access; other methods will be ignored:

  • the method's type is exported.
  • the method is exported.
  • the method has three arguments, all exported (or builtin) types.
  • the method's first argument is a context.Context
  • the method's third argument is a pointer.
  • the method has return type error.

In effect, the method must look schematically like

func (t *T) MethodName(ctx context.Context, argType T1, replyType *T2) error

where T1 and T2 can be marshaled by encoding/gob. These requirements apply even if a different codec is used. (In the future, these requirements may soften for custom codecs.)

The method's second argument represents the arguments provided by the caller; the third argument represents the result parameters to be returned to the caller. The method's return value, if non-nil, is passed back as a string that the client sees as if created by errors.New. If an error is returned, the reply parameter will not be sent back to the client.

The server may handle requests on a single connection by calling ServeConn. More typically it will create a network listener and call Accept.

A client wishing to use the service establishes a connection and then invokes NewClient on the connection. The convenience function Dial performs both steps for a raw network connection. The resulting Client object has two methods, Call and Go, that specify the service and method to call, a context, a pointer containing the arguments, and a pointer to receive the result parameters.

The Call method waits for the remote call to complete or the context.Context to complete while the Go method launches the call asynchronously and signals completion using the Call structure's Done channel.

Unless an explicit codec is set up, package encoding/gob is used to transport the data.

Here is a simple example. A server wishes to export an object of type Arith:

package server

import "errors"

type Args struct {
	A, B int
}

type Quotient struct {
	Quo, Rem int
}

type Arith int

func (t *Arith) Multiply(ctx context.Context, args *Args, reply *int) error {
	*reply = args.A * args.B
	return nil
}

func (t *Arith) Divide(ctx context.Context, args *Args, quo *Quotient) error {
	if args.B == 0 {
		return errors.New("divide by zero")
	}
	quo.Quo = args.A / args.B
	quo.Rem = args.A % args.B
	return nil
}

The server calls (for HTTP service):

arith := new(Arith)
rpc.Register(arith)

l, e := net.Listen("tcp", ":1234")
if e != nil {
	log.Fatal("listen error:", e)
}
go rpc.Accept(context.Background(), l)

At this point, clients can see a service "Arith" with methods "Arith.Multiply" and "Arith.Divide". To invoke one, a client first dials the server:

ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
client, err := rpc.Dial(ctx, "tcp", serverAddress + ":1234")

if err != nil {
	log.Fatal("dialing:", err)
}

Then it can make a remote call:

// Synchronous call
args := &server.Args{7,8}
var reply int
err = client.Call(ctx, "Arith.Multiply", args, &reply)
if err != nil {
	log.Fatal("arith error:", err)
}
fmt.Printf("Arith: %d*%d=%d", args.A, args.B, reply)

or

// Asynchronous call
quotient := new(Quotient)
divCall := client.Go(ctx, "Arith.Divide", args, quotient, nil)
replyCall := <-divCall.Done	// will be equal to divCall
// check errors, print, etc.

A server implementation will often provide a simple, type-safe wrapper for the client.

Index

Constants

This section is empty.

Variables

View Source
var DefaultServer = NewServer()

DefaultServer is the default instance of *Server.

View Source
var ErrShutdown = errors.New("connection is shut down")

ErrShutdown is returned when the client has been closed and a call to Go or Call is executed.

Functions

func Accept

func Accept(ctx context.Context, lis net.Listener)

Accept accepts connections on the listener and serves requests to DefaultServer for each incoming connection. Accept blocks; the caller typically invokes it in a go statement.

func ContextID

func ContextID(ctx context.Context) string

ContextID returns the rpc request ID from the supplied context.Context

func ContextServiceMethod

func ContextServiceMethod(ctx context.Context) string

ContextServiceMethod returns the service method name fromt he supplied context.Context

func ContextWithHeaders

func ContextWithHeaders(ctx context.Context, h Header) context.Context

ContextWithHeaders will set the current headers for a client context. This has no effect on a server.

func ServeCodec

func ServeCodec(ctx context.Context, codec ServerCodec)

ServeCodec is like ServeConn but uses the specified codec to decode requests and encode responses.

func ServeConn

func ServeConn(ctx context.Context, conn io.ReadWriteCloser)

ServeConn runs the DefaultServer on a single connection. ServeConn blocks, serving the connection until the client hangs up. The caller typically invokes ServeConn in a go statement. ServeConn uses the gob wire format (see package gob) on the connection. To use an alternate codec, use ServeCodec. See NewClient's comment for information about concurrent access.

func ServeRequest

func ServeRequest(ctx context.Context, codec ServerCodec) error

ServeRequest is like ServeCodec but synchronously serves a single request. It does not close the codec upon completion.

Types

type Call

type Call struct {
	ServiceMethod string      // The name of the service and method to call.
	Args          interface{} // The argument to the function (*struct).
	Reply         interface{} // The reply from the function (*struct).
	Error         error       // After completion, the error status.
	Done          chan *Call  // Receives *Call when Go is complete.
}

Call represents an active RPC.

type Client

type Client struct {
	// contains filtered or unexported fields
}

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.

func Dial

func Dial(ctx context.Context, network, address string) (*Client, error)

Dial connects to an RPC server at the specified network address.

func NewClient

func NewClient(conn io.ReadWriteCloser) *Client

NewClient returns a new Client to handle requests to the set of services at the other end of the connection. It adds a buffer to the write side of the connection so the header and payload are sent as a unit.

The read and write halves of the connection are serialized independently, so no interlocking is required. However each half may be accessed concurrently so the implementation of conn should protect against concurrent reads or concurrent writes.

func NewClientWithCodec

func NewClientWithCodec(codec ClientCodec) *Client

NewClientWithCodec is like NewClient but uses the specified codec to encode requests and decode responses.

func (*Client) Call

func (client *Client) Call(ctx context.Context, serviceMethod string, args interface{}, reply interface{}) error

Call invokes the named function, waits for it to complete or context.Done(), and returns its error status.

func (*Client) Close

func (client *Client) Close() error

Close calls the underlying codec's Close method. If the connection is already shutting down, ErrShutdown is returned.

func (*Client) Go

func (client *Client) Go(ctx context.Context, serviceMethod string, args interface{}, reply interface{}, done chan *Call) *Call

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 panic.

type ClientCodec

type ClientCodec interface {
	WriteRequest(*Request, interface{}) error
	ReadResponseHeader(*Response) error
	ReadResponseBody(interface{}) error

	// Close can be called multiple times and must be idempotent.
	Close() error
}

A ClientCodec implements writing of RPC requests and reading of RPC responses for the client side of an RPC session. The client calls WriteRequest to write a request to the connection and calls ReadResponseHeader and ReadResponseBody in pairs to read responses. The client calls Close when finished with the connection. ReadResponseBody may be called with a nil argument to force the body of the response to be read and then discarded.

type Header map[string][]string

A Header represents the key-value pairs in an RPC header.

The keys should be in canonical form, as returned by CanonicalHeaderKey.

func ContextHeader

func ContextHeader(ctx context.Context) Header

ContextHeader returns the rpc.Header from the supplied context.Context

func (Header) Add

func (h Header) Add(key, value string) Header

Add adds the key, value pair to the header. It appends to any existing values associated with key. The key is case insensitive; it is canonicalized by CanonicalHeaderKey.

func (Header) Del

func (h Header) Del(key string)

Del deletes the values associated with key. The key is case insensitive; it is canonicalized by CanonicalHeaderKey.

func (Header) Get

func (h Header) Get(key string) string

Get gets the first value associated with the given key. If there are no values associated with the key, Get returns "". It is case insensitive; textproto.CanonicalMIMEHeaderKey is used to canonicalize the provided key. To use non-canonical keys, access the map directly.

func (Header) Set

func (h Header) Set(key, value string) Header

Set sets the header entries associated with key to the single element value. It replaces any existing values associated with key. The key is case insensitive; it is canonicalized by textproto.CanonicalMIMEHeaderKey. To use non-canonical keys, assign to the map directly.

func (Header) Values

func (h Header) Values(key string) []string

Values returns all values associated with the given key. It is case insensitive; textproto.CanonicalMIMEHeaderKey is used to canonicalize the provided key. To use non-canonical keys, access the map directly. The returned slice is not a copy.

type MiddlewareFunc

type MiddlewareFunc func(MiddlewareHandler) MiddlewareHandler

MiddlewareFunc is a function which receives a MiddlewareHandler and returns another MiddlewareHandler. Typically, the returned handler is a closure which does something with the Response and Request passed to it, and then calls the handler passed as parameter to the MiddlewareFunc.

func (MiddlewareFunc) Middleware

Middleware allows MiddlewareFunc to implement the middleware interface.

type MiddlewareHandler

type MiddlewareHandler func(context.Context, ResponseWriter, *Request)

MiddlewareHandler used for calling Middleware

type Request

type Request struct {
	ServiceMethod string // format: "Service.Method"
	ID            string // RequestID
	Header        Header // Request headers
	// contains filtered or unexported fields
}

Request is a header written before every RPC call. It is used internally but documented here as an aid to debugging, such as when analyzing network traffic.

type Response

type Response struct {
	ServiceMethod string // echoes that of the Request
	ID            string // echoes that of the Request
	Header        Header // Response Headers
	Error         string // error, if any.
	// contains filtered or unexported fields
}

Response is a header written before every RPC return. It is used internally but documented here as an aid to debugging, such as when analyzing network traffic.

type ResponseWriter

type ResponseWriter interface {
	Header() Header
	WriteError(err error)
	Err() error
}

ResponseWriter provides an interface for middleware to write response headers and errors

type Server

type Server struct {
	// contains filtered or unexported fields
}

Server represents an RPC Server.

func NewServer

func NewServer() *Server

NewServer returns a new Server.

func (*Server) Accept

func (server *Server) Accept(ctx context.Context, lis net.Listener)

Accept accepts connections on the listener and serves requests for each incoming connection. Accept blocks until the listener returns a non-nil error. The caller typically invokes Accept in a go statement.

func (*Server) Register

func (server *Server) Register(rcvr interface{}) error

Register publishes in the server the set of methods of the receiver value that satisfy the following conditions:

  • exported method of exported type
  • three arguments
  • the first argument is a context.Context
  • the second argument is an exported type
  • the third argument is a pointer and an exported type
  • one return value, of type error

It returns an error if the receiver is not an exported type or has no suitable methods. It also logs the error using package log. The client accesses each method using a string of the form "Type.Method", where Type is the receiver's concrete type.

func (*Server) RegisterName

func (server *Server) RegisterName(name string, rcvr interface{}) error

RegisterName is like Register but uses the provided name for the type instead of the receiver's concrete type.

func (*Server) ServeCodec

func (server *Server) ServeCodec(ctx context.Context, codec ServerCodec)

ServeCodec is like ServeConn but uses the specified codec to decode requests and encode responses.

func (*Server) ServeConn

func (server *Server) ServeConn(ctx context.Context, conn io.ReadWriteCloser)

ServeConn runs the server on a single connection. ServeConn blocks, serving the connection until the client hangs up. The caller typically invokes ServeConn in a go statement. ServeConn uses the gob wire format (see package gob) on the connection. To use an alternate codec, use ServeCodec. See NewClient's comment for information about concurrent access.

func (*Server) ServeRequest

func (server *Server) ServeRequest(ctx context.Context, codec ServerCodec) error

ServeRequest is like ServeCodec but synchronously serves a single request. It does not close the codec upon completion.

func (*Server) Use

func (s *Server) Use(mwf ...MiddlewareFunc)

Use appends a MiddlewareFunc to the chain. Middleware can be used to intercept or otherwise modify requests and/or responses, and are executed in the order that they are applied to the Server.

type ServerCodec

type ServerCodec interface {
	ReadRequestHeader(*Request) error
	ReadRequestBody(interface{}) error
	WriteResponse(*Response, interface{}) error

	// Close can be called multiple times and must be idempotent.
	Close() error
}

A ServerCodec implements reading of RPC requests and writing of RPC responses for the server side of an RPC session. The server calls ReadRequestHeader and ReadRequestBody in pairs to read requests from the connection, and it calls WriteResponse to write a response back. The server calls Close when finished with the connection. ReadRequestBody may be called with a nil argument to force the body of the request to be read and discarded.

type ServerError

type ServerError string

ServerError represents an error that has been returned from the remote side of the RPC connection.

func (ServerError) Error

func (e ServerError) Error() string

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL