channel

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Jan 2, 2020 License: Apache-2.0 Imports: 13 Imported by: 4

README

Channel

A library that implements bidirectional request/response based communication over websockets.

Public apis

see client and server

Usage

see example

Implementation Details

Channel

The server and client are wrappers around channel. channel is an abstraction that can send requests from one side to another and wait for the response. Channels have connected peers, in case of the client it is only one peer that is actually the server.

Each request to a peer gets a unique id, and the response to this request uses the same id. Requests from the client uses even ids, while requests from the server uses odd ones. This way each channel can distinguish between requests from its peer and responses to previous requests.

Packets

This protocol encapsulate each paket into this struct

type packetStruct struct {
	ID       int            `json:"id"`
	Endpoint string         `json:"endpoint"`
	Body     []byte         `json:"body,omitempty"`
	Error    *ProtocolError `json:"error,omitempty"`
}

It uses endpoints to allow communication for different reasons, each request sent to some endpoint will be processed by the listener listening on this endpoint.

Body is the body to be sent over to the peer as a byte array. It is done this way to add the flexibility for the user to choose how he wants to encode his data.

Errro an optional error in case the listener returns one.

Packet Encoding

Packets are encoded using gob, the underlying data can be encoded however the user likes it should be passed as []byte to the apis.

Errors

Responses are awaited for for some time, if it didn't receive one, it just returns a timeout error, if a response is received afterwards, it is silently discarded. Also malformed requets give an error immediately. Both these are protocol errors.

For listeners that return errors that are not protocol errors, the error is wrapped as an internal error and the message of the error is trasnsferred to the peer.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Channel

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

Channel abstracts a connection to an either a server or a client

func (*Channel) AddListener

func (ch *Channel) AddListener(endpoint string, listener func(context.Context, uuid.UUID, []byte) ([]byte, error)) error

func (*Channel) AddMiddleware

func (ch *Channel) AddMiddleware(middleware func(context.Context, string, uuid.UUID, []byte, func(context.Context, uuid.UUID, []byte) ([]byte, error)) ([]byte, error))

func (*Channel) GetPeer

func (ch *Channel) GetPeer(id uuid.UUID) *peer

func (*Channel) HandlePeer

func (ch *Channel) HandlePeer(peer *peer)

func (*Channel) Init

func (ch *Channel) Init()

func (*Channel) ListPeers

func (ch *Channel) ListPeers() []uuid.UUID

func (*Channel) NewPeer

func (ch *Channel) NewPeer(c *websocket.Conn, uri string) *peer

func (*Channel) Send

func (ch *Channel) Send(client uuid.UUID, endpoint string, body []byte) ([]byte, error)

func (*Channel) SetHooks

func (ch *Channel) SetHooks(
	onConnect *func(id uuid.UUID, uri string, remoteAddr string) error,
	onDisconnect *func(id uuid.UUID),
)

SetHooks sets connection and disconnection hooks

type ChannelOptions

type ChannelOptions struct {
	ProtoHandshake time.Duration
	ProtoWrite     time.Duration
	ProtoRead      time.Duration
	ProtoReconnect time.Duration
}

ChannelOptions options for the channel

type Client

type Client struct {
	URL     url.URL
	Channel *Channel
	// contains filtered or unexported fields
}

Client a protocol client

func NewClient

func NewClient(url url.URL, channelOptions ChannelOptions) *Client

NewClient Creates a new Client addr is the address to connect to channelOptions options, see ChannelOptions docs

func (*Client) AddListener

func (c *Client) AddListener(endpoint string, listener func([]byte) ([]byte, error)) error

AddListener adds a listener to the channel for some endpoint

func (*Client) IsConnected

func (c *Client) IsConnected() bool

IsConnected checks if a connection to the server is established

func (*Client) Listen

func (c *Client) Listen()

Listen starts connection loop to the server, auto connects when connection fails

func (*Client) Send

func (c *Client) Send(endpoint string, body []byte) ([]byte, error)

Send sends a byte array on the specified endpoint returns an optional response, an optional error

func (*Client) SetHooks

func (c *Client) SetHooks(
	onConnect *func() error,
	onDisconnect *func(),
)

SetHooks sets connection and disconnection hooks

type Conn

type Conn interface {
	SetWriteDeadline(time.Time) error
	NextWriter(int) (io.WriteCloser, error)
	NextReader() (messageType int, r io.Reader, err error)
	RemoteAddr() net.Addr
	Close() error
}

type ErrorCode

type ErrorCode int
const (
	BadRequestCode         ErrorCode = 1
	ClientNotConnectedCode ErrorCode = 2
	LocalErrorCode         ErrorCode = 3
	InternalErrorCode      ErrorCode = 4
	NotFoundCode           ErrorCode = 5
	TimeoutCode            ErrorCode = 6
)

type ProtocolError

type ProtocolError struct {
	Code    ErrorCode `json:"code"`
	Message string    `json:"message"`
	Reason  *string   `json:"reason"`
}

func ApplyReason

func ApplyReason(fn func(message string, reason *string) ProtocolError, message string, err error) *ProtocolError

func BadRequest

func BadRequest(message string, reason *string) ProtocolError

func ClientNotConnected

func ClientNotConnected(message string, reason *string) ProtocolError

func InternalError

func InternalError(message string, reason *string) ProtocolError

func LocalError

func LocalError(message string, reason *string) ProtocolError

func NotFound

func NotFound(message string, reason *string) ProtocolError

func Timeout

func Timeout(message string, reason *string) ProtocolError

func (ProtocolError) Error

func (e ProtocolError) Error() string

type Receiver

type Receiver interface {
	// contains filtered or unexported methods
}

type Server

type Server struct {
	Addr string
	Path string

	Channel *Channel
}

Server a protocol server

func NewServer

func NewServer(addr string, path string, channelOptions ChannelOptions) *Server

NewServer Creates a new Server addr is the address to listen on channelOptions options, see ChannelOptions docs

func (*Server) AddListener

func (s *Server) AddListener(endpoint string, listener func(context.Context, uuid.UUID, []byte) ([]byte, error)) error

AddListener adds a listener to the channel for some endpoint

func (*Server) AddMiddleware

func (ch *Server) AddMiddleware(
	middleware func(context.Context, string, uuid.UUID, []byte, func(context.Context, uuid.UUID, []byte) ([]byte, error)) ([]byte, error),
)

func (*Server) IsConnected

func (s *Server) IsConnected(client uuid.UUID) bool

IsConnected checks if the client is connected

func (*Server) Listen

func (s *Server) Listen()

Listen starts listening on connections

func (*Server) Peers

func (s *Server) Peers() []uuid.UUID

Peers returns a list of uuids of the connected clients

func (*Server) Send

func (s *Server) Send(client uuid.UUID, endpoint string, body []byte) ([]byte, error)

Send sends a byte array to some client on the specified endpoint returns an optional response, an optional error

func (*Server) SetHooks

func (s *Server) SetHooks(
	onConnect *func(id uuid.UUID, uri string, remoteAddr string) error,
	onDisconnect *func(id uuid.UUID),
)

SetHooks sets connection and disconnection hooks

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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