getty

package module
v1.8.4 Latest Latest
Warning

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

Go to latest
Published: Nov 6, 2021 License: Apache-2.0 Imports: 27 Imported by: 0

README

getty

a netty like asynchronous network I/O library

Build Status codecov go.dev reference Go Report Card license

INTRO

Getty is a asynchronous network I/O library in golang. Getty works on tcp/udp/websocket network protocol and supplies a uniform interface.

In getty there are two goroutines in one connection(session), one reads tcp stream/udp packet/websocket package, the other handles logic process and writes response into network write buffer. If your logic process may take a long time, you should start a new logic process goroutine by yourself in codec.go:(Codec)OnMessage.

You can also handle heartbeat logic in codec.go:(Codec):OnCron. If you use tcp/udp, you should send hearbeat package by yourself, and then invoke session.go:(Session)UpdateActive to update its active time. Please check whether the tcp session has been timeout or not in codec.go:(Codec)OnCron by session.go:(Session)GetActive.

Whatever if you use websocket, you do not need to care about hearbeat request/response because Getty do this task in session.go:(Session)handleLoop by sending/received websocket ping/pong frames. You just need to check whether the websocket session has been timeout or not in codec.go:(Codec)OnCron by session.go:(Session)GetActive.

LICENCE

Apache License 2.0

Documentation

Index

Constants

View Source
const (
	CompressNone            CompressType = flate.NoCompression      // 0
	CompressZip                          = flate.DefaultCompression // -1
	CompressBestSpeed                    = flate.BestSpeed          // 1
	CompressBestCompression              = flate.BestCompression    // 9
	CompressHuffman                      = flate.HuffmanOnly        // -2
	CompressSnappy                       = 10
)
View Source
const (
	LoggerLevelDebug  = LoggerLevel(zapcore.DebugLevel)
	LoggerLevelInfo   = LoggerLevel(zapcore.InfoLevel)
	LoggerLevelWarn   = LoggerLevel(zapcore.WarnLevel)
	LoggerLevelError  = LoggerLevel(zapcore.ErrorLevel)
	LoggerLevelDPanic = LoggerLevel(zapcore.DPanicLevel)
	LoggerLevelPanic  = LoggerLevel(zapcore.PanicLevel)
	LoggerLevelFatal  = LoggerLevel(zapcore.FatalLevel)
)
View Source
const (

	// MaxWheelTimeSpan 900s, 15 minute
	MaxWheelTimeSpan = 900e9
)

Variables

View Source
var (
	ErrSessionClosed  = perrors.New("session Already Closed")
	ErrSessionBlocked = perrors.New("session Full Blocked")
	ErrNullPeerAddr   = perrors.New("peer address is nil")
)
View Source
var EndPointType_name = map[int32]string{
	0: "UDP_ENDPOINT",
	1: "UDP_CLIENT",
	2: "TCP_CLIENT",
	3: "WS_CLIENT",
	4: "WSS_CLIENT",
	7: "TCP_SERVER",
	8: "WS_SERVER",
	9: "WSS_SERVER",
}
View Source
var EndPointType_value = map[string]int32{
	"UDP_ENDPOINT": 0,
	"UDP_CLIENT":   1,
	"TCP_CLIENT":   2,
	"WS_CLIENT":    3,
	"WSS_CLIENT":   4,
	"TCP_SERVER":   7,
	"WS_SERVER":    8,
	"WSS_SERVER":   9,
}

Functions

func Online

func Online(logfile string) error

func SetLogger

func SetLogger(logger Logger)

SetLogger customize yourself logger.

func SetLoggerCallerDisable

func SetLoggerCallerDisable() error

SetLoggerCallerDisable disable caller info in production env for performance improve. It is highly recommended that you execute this method in a production environment.

func SetLoggerLevel

func SetLoggerLevel(level LoggerLevel) error

SetLoggerLevel set logger level

Types

type Client

type Client interface {
	EndPoint
}

func NewTCPClient

func NewTCPClient(opts ...ClientOption) Client

NewTCPClient builds a tcp client.

func NewUDPClient

func NewUDPClient(opts ...ClientOption) Client

NewUDPClient builds a connected udp client

type ClientOption

type ClientOption func(*ClientOptions)

func WithClientSslEnabled

func WithClientSslEnabled(sslEnabled bool) ClientOption

WithClientSslEnabled enable use tls

func WithClientTaskPool

func WithClientTaskPool(pool gxsync.GenericTaskPool) ClientOption

WithClientTaskPool @pool client task pool.

func WithClientTlsConfigBuilder

func WithClientTlsConfigBuilder(tlsConfigBuilder TlsConfigBuilder) ClientOption

WithClientTlsConfigBuilder sslConfig is tls config

func WithConnectionNumber

func WithConnectionNumber(num int) ClientOption

WithConnectionNumber @num is connection number.

func WithLocalAddressClient

func WithLocalAddressClient(addr net.Addr) ClientOption

WithLocalAddressClient @addr is server address.

func WithReconnectInterval

func WithReconnectInterval(reconnectInterval int) ClientOption

WithReconnectInterval @reconnectInterval is server address.

func WithRootCertificateFile

func WithRootCertificateFile(cert string) ClientOption

WithRootCertificateFile @certs is client certificate file. it can be empty.

func WithServerAddress

func WithServerAddress(addr string) ClientOption

WithServerAddress @addr is server address.

type ClientOptions

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

type ClientTlsConfigBuilder

type ClientTlsConfigBuilder struct {
	ClientKeyCertChainPath        string
	ClientPrivateKeyPath          string
	ClientKeyPassword             string
	ClientTrustCertCollectionPath string
}

ClientTlsConfigBuilder impl TlsConfigBuilder for client

func (*ClientTlsConfigBuilder) BuildTlsConfig

func (c *ClientTlsConfigBuilder) BuildTlsConfig() (*tls.Config, error)

BuildTlsConfig impl TlsConfigBuilder method

type CompressType

type CompressType int

type Connection

type Connection interface {
	ID() uint32
	SetCompressType(CompressType)
	LocalAddr() string
	RemoteAddr() string

	// UpdateActive update session's active time
	UpdateActive()
	// GetActive get session's active time
	GetActive() time.Time

	// SetReadTimeout sets deadline for the future read calls.
	SetReadTimeout(time.Duration)

	// SetWriteTimeout sets deadline for the future read calls.
	SetWriteTimeout(time.Duration)
	// contains filtered or unexported methods
}

Connection wrap some connection params and operations

type EndPoint

type EndPoint interface {
	// ID get EndPoint ID
	ID() EndPointID
	// EndPointType get endpoint type
	EndPointType() EndPointType
	// RunEventLoop run event loop and serves client request.
	RunEventLoop(newSession NewSessionCallback)
	// IsClosed check the endpoint has been closed
	IsClosed() bool
	// Close close the endpoint and free its resource
	Close()
	// GetTaskPool get task pool implemented by dubbogo/gost
	GetTaskPool() gxsync.GenericTaskPool
}

EndPoint represents the identity of the client/server

type EndPointID

type EndPointID = int32

type EndPointType

type EndPointType int32
const (
	UDP_ENDPOINT EndPointType = 0
	UDP_CLIENT   EndPointType = 1
	TCP_CLIENT   EndPointType = 2
	WS_CLIENT    EndPointType = 3
	WSS_CLIENT   EndPointType = 4
	TCP_SERVER   EndPointType = 7
	WS_SERVER    EndPointType = 8
	WSS_SERVER   EndPointType = 9
)

func (EndPointType) String

func (x EndPointType) String() string

type EventListener

type EventListener interface {
	// OnOpen invoked when session opened
	// If the return error is not nil, @Session will be closed.
	OnOpen(Session) error

	// OnClose invoked when session closed.
	OnClose(Session)

	// OnError invoked when got error.
	OnError(Session, error)

	// OnCron invoked periodically, its period can be set by (Session)SetCronPeriod
	OnCron(Session)

	// OnMessage invoked when getty received a package. Pls attention that do not handle long time
	// logic processing in this func. You'd better set the package's maximum length.
	// If the message's length is greater than it, u should should return err in
	// Reader{Read} and getty will close this connection soon.
	//
	// If ur logic processing in this func will take a long time, u should start a goroutine
	// pool(like working thread pool in cpp) to handle the processing asynchronously. Or u
	// can do the logic processing in other asynchronous way.
	// !!!In short, ur OnMessage callback func should return asap.
	//
	// If this is a udp event listener, the second parameter type is UDPContext.
	OnMessage(Session, interface{})
}

EventListener is used to process pkg that received from remote session

type Logger

type Logger interface {
	Info(args ...interface{})
	Warn(args ...interface{})
	Error(args ...interface{})
	Debug(args ...interface{})

	Infof(fmt string, args ...interface{})
	Warnf(fmt string, args ...interface{})
	Errorf(fmt string, args ...interface{})
	Debugf(fmt string, args ...interface{})
}

Logger for user who want to customize logger of getty

func GetLogger

func GetLogger() Logger

GetLogger get getty logger

type LoggerLevel

type LoggerLevel int8

type NewSessionCallback

type NewSessionCallback func(Session) error

NewSessionCallback will be invoked when server accepts a new client connection or client connects to server successfully. If there are too many client connections or u do not want to connect a server again, u can return non-nil error. And then getty will close the new session.

type PacketServer

type PacketServer interface {
	Server
	// PacketConn get the network listener
	PacketConn() net.PacketConn
}

PacketServer is like udp listen endpoint

type ReadWriter

type ReadWriter interface {
	Reader
	Writer
}

ReadWriter interface use for handle application packages

type Reader

type Reader interface {
	// Read Parse tcp/udp/websocket pkg from buffer and if possible return a complete pkg.
	// When receiving a tcp network streaming segment, there are 4 cases as following:
	// case 1: a error found in the streaming segment;
	// case 2: can not unmarshal a pkg header from the streaming segment;
	// case 3: unmarshal a pkg header but can not unmarshal a pkg from the streaming segment;
	// case 4: just unmarshal a pkg from the streaming segment;
	// case 5: unmarshal more than one pkg from the streaming segment;
	//
	// The return value is (nil, 0, error) as case 1.
	// The return value is (nil, 0, nil) as case 2.
	// The return value is (nil, pkgLen, nil) as case 3.
	// The return value is (pkg, pkgLen, nil) as case 4.
	// The handleTcpPackage may invoke func Read many times as case 5.
	Read(Session, []byte) (interface{}, int, error)
}

Reader is used to unmarshal a complete pkg from buffer

type Server

type Server interface {
	EndPoint
}

Server interface

func NewTCPServer

func NewTCPServer(opts ...ServerOption) Server

NewTCPServer builds a tcp server.

func NewUDPEndPoint

func NewUDPEndPoint(opts ...ServerOption) Server

NewUDPEndPoint builds a unconnected udp server.

func NewWSSServer

func NewWSSServer(opts ...ServerOption) Server

NewWSSServer builds a secure websocket server.

func NewWSServer

func NewWSServer(opts ...ServerOption) Server

NewWSServer builds a websocket server.

type ServerOption

type ServerOption func(*ServerOptions)

func WithLocalAddress

func WithLocalAddress(addr string) ServerOption

WithLocalAddress @addr server listen address.

func WithServerSslEnabled

func WithServerSslEnabled(sslEnabled bool) ServerOption

WithServerSslEnabled enable use tls

func WithServerTaskPool

func WithServerTaskPool(pool gxsync.GenericTaskPool) ServerOption

WithServerTaskPool @pool server task pool.

func WithServerTlsConfigBuilder

func WithServerTlsConfigBuilder(tlsConfigBuilder TlsConfigBuilder) ServerOption

WithServerTlsConfigBuilder sslConfig is tls config

func WithWebsocketServerCert

func WithWebsocketServerCert(cert string) ServerOption

WithWebsocketServerCert @cert: server certificate file

func WithWebsocketServerPath

func WithWebsocketServerPath(path string) ServerOption

WithWebsocketServerPath @path: websocket request url path

func WithWebsocketServerPrivateKey

func WithWebsocketServerPrivateKey(key string) ServerOption

WithWebsocketServerPrivateKey @key: server private key(contains its public key)

func WithWebsocketServerRootCert

func WithWebsocketServerRootCert(cert string) ServerOption

WithWebsocketServerRootCert @cert is the root certificate file to verify the legitimacy of server

type ServerOptions

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

type ServerTlsConfigBuilder

type ServerTlsConfigBuilder struct {
	ServerKeyCertChainPath        string
	ServerPrivateKeyPath          string
	ServerKeyPassword             string
	ServerTrustCertCollectionPath string
}

ServerTlsConfigBuilder impl TlsConfigBuilder for server

func (*ServerTlsConfigBuilder) BuildTlsConfig

func (s *ServerTlsConfigBuilder) BuildTlsConfig() (*tls.Config, error)

BuildTlsConfig impl TlsConfigBuilder method

type Session

type Session interface {
	Connection
	Reset()
	Conn() net.Conn
	Stat() string
	IsClosed() bool
	// EndPoint get endpoint type
	EndPoint() EndPoint

	SetMaxMsgLen(int)
	SetName(string)
	SetEventListener(EventListener)
	SetPkgHandler(ReadWriter)
	SetReader(Reader)
	SetWriter(Writer)
	SetCronPeriod(int)

	SetWaitTime(time.Duration)

	GetAttribute(interface{}) interface{}
	SetAttribute(interface{}, interface{})
	RemoveAttribute(interface{})

	// WritePkg the Writer will invoke this function. Pls attention that if timeout is less than 0, WritePkg will send @pkg asap.
	// for udp session, the first parameter should be UDPContext.
	// totalBytesLength: @pkg stream bytes length after encoding @pkg.
	// sendBytesLength: stream bytes length that sent out successfully.
	// err: maybe it has illegal data, encoding error, or write out system error.
	WritePkg(pkg interface{}, timeout time.Duration) (totalBytesLength int, sendBytesLength int, err error)
	WriteBytes([]byte) (int, error)
	WriteBytesArray(...[]byte) (int, error)
	Close()
}

Session wrap connection between the server and the client

type StreamServer

type StreamServer interface {
	Server
	// Listener get the network listener
	Listener() net.Listener
}

StreamServer is like tcp/websocket/wss server

type TlsConfigBuilder

type TlsConfigBuilder interface {
	BuildTlsConfig() (*tls.Config, error)
}

TlsConfigBuilder tls config builder interface

type UDPContext

type UDPContext struct {
	Pkg      interface{}
	PeerAddr *net.UDPAddr
}

func (UDPContext) String

func (c UDPContext) String() string

type Writer

type Writer interface {
	// Write if @Session is udpGettySession, the second parameter is UDPContext.
	Write(Session, interface{}) ([]byte, error)
}

Writer is used to marshal pkg and write to session

Jump to

Keyboard shortcuts

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