rpc

package
v0.0.0-...-3442dc8 Latest Latest
Warning

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

Go to latest
Published: Mar 9, 2023 License: GPL-2.0 Imports: 31 Imported by: 0

Documentation

Overview

Package recws provides websocket client based on gorilla/websocket that will automatically reconnect if the connection is dropped.

Index

Constants

View Source
const HeadSize = 21
View Source
const StartCipher = 0x05 // 起始符

Variables

View Source
var (
	MaxSimultaneousTcpConn = 50 // max simultaneous Tcp connection for one Server

	MaxHttpHeaderBytes     = 10 * 1024 // 10k
	MaxHttpBodyReaderBytes = 10 * 1024 // 10k

	HttpWriteTimeout      = 10 * time.Second
	HttpReadHeaderTimeout = 5 * time.Second

	CertFilePath = "/mnt/c/Users/30640/Desktop/api_server/topia/api/rpc/example/test/server/server-cert.pem" // tmp test path
	KeyFilePath  = "/mnt/c/Users/30640/Desktop/api_server/topia/api/rpc/example/test/server/server-key.pem"  // tmp test path

	ClientMaxSubsToOneEvent = 5 // maximum times a client can subscribe to a single event simultaneously

	MaxSubQueueLength = 10 // maximum msgs for a single subscription queue to contain
)
View Source
var (
	ErrNonPublic          = errors.New("registered non-public service")
	ErrNoAvailable        = errors.New("no service is available, or provide service is not open")
	ErrCrc32              = errors.New("checksumIEEE error")
	ErrSerialization404   = errors.New("serialization 404")
	ErrCompressor404      = errors.New("compressor 404")
	ErrTimeout            = errors.New("time out")
	ErrCircuitBreaker     = errors.New("circuit breaker")
	ErrInput              = errors.New("input error")
	ErrMethodNameRegister = errors.New("register method name error")
	ErrAuth               = errors.New("auth error")
	ErrAuthLevel          = errors.New("insufficient auth level")
	ErrMethodName         = errors.New("method name error")
)
View Source
var ErrNotConnected = errors.New("websocket: not connected")

ErrNotConnected is returned when the application read/writes a message and the connection is closed

Functions

func Decode

func Decode(b []byte) (data []interface{}, err error)

func DistributedID

func DistributedID() (string, error)

func Encode

func Encode(data interface{}) ([]byte, error)

func EncodeMessage

func EncodeMessage(msgType MsgType, requestId string, methodName string, authCode string, errMsg *ErrMsg, payload []byte) (data []byte, err error)

EncodeMessage 基础编码

func IsPublic

func IsPublic(name string) bool

IsPublic is public

func IsPublicOrBuiltinType

func IsPublicOrBuiltinType(t reflect.Type) bool

func PrintStack

func PrintStack()

func RandStringRunes

func RandStringRunes(n int) string

func RefNew

func RefNew(refType reflect.Type) interface{}

create interface{} by refType

Types

type AuthLevel

type AuthLevel byte
const (
	None    AuthLevel = 0
	Read    AuthLevel = 1
	Write   AuthLevel = 2
	Sign    AuthLevel = 3
	Manager AuthLevel = 4
)

type AuthObject

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

func NewAuthObject

func NewAuthObject(m map[AuthLevel]string) *AuthObject

func (*AuthObject) Level

func (auth *AuthObject) Level(token string) (authority AuthLevel)

func (*AuthObject) Token

func (auth *AuthObject) Token(authority AuthLevel) (token string, err error)

type Client

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

func NewClient

func NewClient(addr string, options ...ClientOption) (*Client, error)

NewClient creates a new client

func (*Client) Call

func (c *Client) Call(methodName string, response interface{}, inArgs ...interface{}) (err error)

func (*Client) CallWithWS

func (c *Client) CallWithWS(methodName string, inArgs ...interface{}) (res *Message, err error)

TODO 仅测试用

func (*Client) CloseServer

func (c *Client) CloseServer() error

func (*Client) Subscribe

func (c *Client) Subscribe(eventName string, filterString string) (subMsgChan <-chan []byte, subID int, err error)

func (*Client) UnSubscribe

func (c *Client) UnSubscribe(eventName string, subID int) error

func (*Client) UnSubscribeAll

func (c *Client) UnSubscribeAll() error

type ClientOption

type ClientOption func(options *ClientOptions)

func SetClientAUTH

func SetClientAUTH(token string) ClientOption

func SetClientAttempts

func SetClientAttempts(attempts int) ClientOption

func SetClientCache

func SetClientCache(cache httpcache.Cache) ClientOption

func SetClientSleepTime

func SetClientSleepTime(sleepTime time.Duration) ClientOption

func SetClientTLS

func SetClientTLS(config *tls.Config) ClientOption

func SetClientTimeOut

func SetClientTimeOut(timeout time.Duration) ClientOption

func SetClientWS

func SetClientWS(maxMessageSize int, pingWait string, logger log.Logger) ClientOption

using websocket

type ClientOptions

type ClientOptions struct {
	AUTH string
	// contains filtered or unexported fields
}

type ErrMsg

type ErrMsg struct {
	Errtype   Errtype `json:"err_type"`
	ErrCode   int     `json:"err_code"`
	ErrString string  `json:"err_string"`
	Data      string  `json:"data"`
}

type Errtype

type Errtype int
const (
	NoErr                 Errtype = 0
	ErrMethodNotFound     Errtype = 1
	ErrAuthFailed         Errtype = 2
	ErrIllegalArgument    Errtype = 3
	ErrServiceReturnError Errtype = 4 // Error return by called service

	ErrNoSuchEvent       Errtype = 5
	ErrExceedMaxSubLimit Errtype = 6 // client is trying to sub one event for more than ClientMaxSubsToOneEvent
	ErrInvalidSubID      Errtype = 7
	ErrNoSuchSub         Errtype = 8
)
type Header struct {
	Sc             byte
	RequestIdSize  uint32
	MethodNameSize uint32
	AuthCodeSize   uint32
	ErrMsgSize     uint32
	PayloadSize    uint32
}

func DecodeHeader

func DecodeHeader(data []byte) (*Header, error)

type Message

type Message struct {
	Header     *Header
	MsgType    MsgType
	RequestId  string // also used as subID when MsgType == MsgSubscribe
	MethodName string // also used as eventName when MsgType is related to subscribe
	AuthCode   string
	ErrMsg     ErrMsg
	Payload    []byte
}

func DecodeMessage

func DecodeMessage(data []byte) (*Message, error)

DecodeMessage 完整Decode

func DecodeMessageV2

func DecodeMessageV2(data []byte, header *Header, headSize uint32) (*Message, error)

func IODecodeMessage

func IODecodeMessage(r io.Reader) (*Message, error)

type MsgType

type MsgType byte
const (
	MsgCall              MsgType = 1
	MsgCallResp          MsgType = 2
	MsgSubscribeReq      MsgType = 3
	MsgSubscribeReqAck   MsgType = 4
	MsgUnsubscribeReq    MsgType = 5
	MsgUnsubscribeReqAck MsgType = 6
	MsgSubscribe         MsgType = 7 // subscribed msg
)

type Option

type Option func(options *Options)

func SetAUTH

func SetAUTH(auth *AuthObject) Option

func SetCache

func SetCache(cache *freecache.Cache) Option

func SetEnableTLS

func SetEnableTLS(enable bool) Option

func SetWebsocket

func SetWebsocket(upgrader *websocket.Upgrader) Option

type Options

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

type Queue

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

Queue

type RecConn

type RecConn struct {
	// RecIntvlMin specifies the initial reconnecting interval,
	// default to 2 seconds
	RecIntvlMin time.Duration
	// RecIntvlMax specifies the maximum reconnecting interval,
	// default to 30 seconds
	RecIntvlMax time.Duration
	// RecIntvlFactor specifies the rate of increase of the reconnection
	// interval, default to 1.5
	RecIntvlFactor float64
	// HandshakeTimeout specifies the duration for the handshake to complete,
	// default to 2 seconds
	HandshakeTimeout time.Duration
	// Proxy specifies the proxy function for the dialer
	// defaults to ProxyFromEnvironment
	Proxy func(*http.Request) (*url.URL, error)
	// Client TLS config to use on reconnect
	TLSClientConfig *tls.Config
	// SubscribeHandler fires after the connection successfully establish.
	SubscribeHandler func() error
	// KeepAliveTimeout is an interval for sending ping/pong messages
	// disabled if 0
	KeepAliveTimeout time.Duration
	// NonVerbose suppress connecting/reconnecting messages.
	NonVerbose bool

	*websocket.Conn
	// contains filtered or unexported fields
}

The RecConn type represents a Reconnecting WebSocket connection.

func (*RecConn) Close

func (rc *RecConn) Close()

Close closes the underlying network connection without sending or waiting for a close frame.

func (*RecConn) CloseAndReconnect

func (rc *RecConn) CloseAndReconnect()

CloseAndReconnect will try to reconnect.

func (*RecConn) Dial

func (rc *RecConn) Dial(urlStr string, reqHeader http.Header)

Dial creates a new client connection. The URL url specifies the host and request URI. Use requestHeader to specify the origin (Origin), subprotocols (Sec-WebSocket-Protocol) and cookies (Cookie). Use GetHTTPResponse() method for the response.Header to get the selected subprotocol (Sec-WebSocket-Protocol) and cookies (Set-Cookie).

func (*RecConn) GetDialError

func (rc *RecConn) GetDialError() error

GetDialError returns the last dialer error. nil on successful connection.

func (*RecConn) GetHTTPResponse

func (rc *RecConn) GetHTTPResponse() *http.Response

GetHTTPResponse returns the http response from the handshake. Useful when WebSocket handshake fails, so that callers can handle redirects, authentication, etc.

func (*RecConn) GetURL

func (rc *RecConn) GetURL() string

GetURL returns current connection url

func (*RecConn) IsConnected

func (rc *RecConn) IsConnected() bool

IsConnected returns the WebSocket connection state

func (*RecConn) ReadJSON

func (rc *RecConn) ReadJSON(v interface{}) error

ReadJSON reads the next JSON-encoded message from the connection and stores it in the value pointed to by v.

See the documentation for the encoding/json Unmarshal function for details about the conversion of JSON to a Go value.

If the connection is closed ErrNotConnected is returned

func (*RecConn) ReadMessage

func (rc *RecConn) ReadMessage() (messageType int, message []byte, err error)

ReadMessage is a helper method for getting a reader using NextReader and reading from that reader to a buffer.

If the connection is closed ErrNotConnected is returned

func (*RecConn) SetTLSClientConfig

func (rc *RecConn) SetTLSClientConfig(tlsClientConfig *tls.Config)

func (*RecConn) Shutdown

func (rc *RecConn) Shutdown(writeWait time.Duration)

Shutdown gracefully closes the connection by sending the websocket.CloseMessage. The writeWait param defines the duration before the deadline of the write operation is hit.

func (*RecConn) WriteJSON

func (rc *RecConn) WriteJSON(v interface{}) error

WriteJSON writes the JSON encoding of v to the connection.

See the documentation for encoding/json Marshal for details about the conversion of Go values to JSON.

If the connection is closed ErrNotConnected is returned

func (*RecConn) WriteMessage

func (rc *RecConn) WriteMessage(messageType int, data []byte) error

WriteMessage is a helper method for getting a writer using NextWriter, writing the message and closing the writer.

If the connection is closed ErrNotConnected is returned

type RequestType

type RequestType byte
const (
	Request RequestType = iota
	Response
	HeartBeat
)

type Server

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

Server struct

func NewServer

func NewServer(addr string, options ...Option) *Server

NewServer creates a new server

func (*Server) Register

func (s *Server) Register(obj interface{}, name string, authority AuthLevel, cacheAble bool, cacheExpireSeconds int, timeout time.Duration) error

func (*Server) Start

func (s *Server) Start()

Run server

func (*Server) Verify

func (s *Server) Verify(reqToken string, methodName string) (bool, error)

type WebsocketClient

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

func (*WebsocketClient) Connect

func (ws *WebsocketClient) Connect() error

func (*WebsocketClient) Run

func (ws *WebsocketClient) Run() error

type WebsocketServer

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

func (*WebsocketServer) Close

func (ws *WebsocketServer) Close()

func (*WebsocketServer) IsConnected

func (ws *WebsocketServer) IsConnected() bool

func (*WebsocketServer) ReadMessage

func (ws *WebsocketServer) ReadMessage() (messageType int, message []byte, err error)

func (*WebsocketServer) WriteMessage

func (ws *WebsocketServer) WriteMessage(messageType int, data []byte) error

Directories

Path Synopsis
example
timeout/client command
timeout/server command

Jump to

Keyboard shortcuts

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