..

ipfs-cluster中rpc的使用

go-libp2p-gorpc 简介:

Package rpc is heavily inspired by Go standard net/rpc package. It aims to do the same thing, except it uses Libp2p for communication and provides context support for cancelling operations.

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.

rpc 方法的标准:

  • the method’s type is exported.
  • the method is exported.
  • the method has 3 arguments.
  • the method’s first argument is a context.
  • the method’s second are third arguments are both exported (or builtin) types.
  • the method’s second argument is a pointer.
  • the method has return type error.

方法:

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

The method’ first argument represents the arguments provided by the caller;
The second argument represents the result parameters to be returned to the caller.

ipfs-cluster 中示例

GoContext

API 说明1

调用 CommitOp2libp2praft 会自动调用 ApplyTo. (相当于回调函数)。

cc.shutdownLock.RLock() // do not shut down while committing
_, finalErr = cc.consensus.CommitOp(op)
cc.shutdownLock.RUnlock()

1)调用GoContext

func (op *LogOp) ApplyTo(cstate consensus.State) (consensus.State, error) {
	case LogOpPin:
		err = state.Add(ctx, pin)
		if err != nil {
			logger.Error(err)
			goto ROLLBACK
		}
		// Async, we let the PinTracker take care of any problems
		op.consensus.rpcClient.GoContext(
			ctx,
			"",
			"PinTracker",
			"Track",
			pin,
			&struct{}{},
			nil,
		)
}

2)自定义RPC方法,符合标准特征

// Track runs PinTracker.Track().
func (rpcapi *PinTrackerRPCAPI) Track(ctx context.Context, in *api.Pin, out *struct{}) error {
	return rpcapi.tracker.Track(ctx, in)
}