isle/go/daemon/rpc.go

87 lines
2.5 KiB
Go

//go:generate mockery --name RPC --inpackage --filename rpc_mock.go
package daemon
import (
"context"
"isle/bootstrap"
"isle/daemon/daecommon"
"isle/daemon/jsonrpc2"
"isle/daemon/network"
"isle/nebula"
"net/http"
"dev.mediocregopher.com/mediocre-go-lib.git/mlog"
)
// CreateNetworkOpts are optional arguments to the CreateNetwork method. A nil
// value is equivalent to a zero value.
type CreateNetworkOpts struct {
// Config will be used as the NetworkConfig for the new Network, rather than
// picking one provided in the Daemon's Config.
Config *daecommon.NetworkConfig
}
func (o *CreateNetworkOpts) withDefaults() *CreateNetworkOpts {
if o == nil {
o = new(CreateNetworkOpts)
}
return o
}
// RPC defines the methods which the Daemon exposes over RPC (via the RPCHandler
// or HTTPHandler methods). Method documentation can be found on the Daemon
// type.
type RPC interface {
CreateNetwork(
ctx context.Context,
creationParams bootstrap.CreationParams,
ipNet nebula.IPNet,
hostName nebula.HostName,
opts *CreateNetworkOpts,
) error
JoinNetwork(context.Context, network.JoiningBootstrap) error
LeaveNetwork(context.Context) error
GetNetworks(context.Context) ([]bootstrap.CreationParams, error)
SetConfig(context.Context, daecommon.NetworkConfig) error
// All network.RPC methods are automatically implemented by Daemon using the
// currently joined network. If no network is joined then any call to these
// methods will return ErrNoNetwork.
//
// If more than one Network is joined then all calls to these methods must
// be accompanied with a context produced by WithNetwork, in order to choose
// the network. These methods may return these errors, in addition to those
// documented on the individual methods:
//
// Errors:
// - ErrNoNetwork
// - ErrNoMatchingNetworks
// - ErrMultipleMatchingNetworks
network.RPC
}
// NewRPCHandler returns a jsonrpc2.Handler which will use the given RPC to
// serve all methods defined on the interface.
func NewRPCHandler(
logger *mlog.Logger, rpc RPC,
) jsonrpc2.Handler {
return jsonrpc2.Chain(
jsonrpc2.NewMLogMiddleware(logger),
jsonrpc2.ExposeServerSideErrorsMiddleware,
)(
jsonrpc2.NewDispatchHandler(&rpc),
)
}
// HTTPRPCHandler returns an http.Handler which will use the Daemon to serve all
// methods defined on the RPC interface via the JSONRPC2 protocol.
func (d *Daemon) HTTPRPCHandler() http.Handler {
handler := NewRPCHandler(d.logger.WithNamespace("rpc"), d)
return jsonrpc2.NewHTTPHandler(handler)
}