pigeon

package module
v0.0.0-...-f9b4097 Latest Latest
Warning

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

Go to latest
Published: May 12, 2018 License: MIT Imports: 10 Imported by: 0

README

Pigeon

Build License MIT

Introduction

Pigeon is a high-performance event-driven TCP network framework.

Installation

Install:

$ go get -u github.com/mervinkid/pigeon

Development

Pigeon use dep for dependency management. To install dependencies make sure to dep have been installed in user system then typing following command.

$ dep ensure

User Case

Contributing

  1. Fork it.
  2. Create your feature branch. ($ git checkout feature/my-feature-branch)
  3. Commit your changes. ($ git commit -am 'What feature I just added.')
  4. Push to the branch. ($ git push origin feature/my-feature-branch)
  5. Create a new Pull Request

Author

@Mervin

License

The MIT License (MIT). For detail see LICENSE.

Documentation

Index

Constants

View Source
const (
	LTrace Level = 1
	LDebug       = LTrace<<1 + 1
	LInfo        = LDebug<<1 + 1
	LWarn        = LInfo<<1 + 1
	LError       = LWarn<<1 + 1
	LNone        = LError<<1 + 1
)
View Source
const (
	TagSize    = 1
	LengthSize = 4
)

Variables

View Source
var (
	NilInitializerError = errors.New("initializer is nil")
	NilConnError        = errors.New("conn is nil")
	NilDecoderError     = errors.New("decoder is nil")
	NilEncoderError     = errors.New("encoder is nil")
	NilHandlerError     = errors.New("handler is nil")
)

Errors

View Source
var AckTimeoutError = errors.New("ack timeout")
View Source
var ClientNotRunningError = errors.New("client is not running")

Errors

View Source
var (
	ErrInvalidChannel = errors.New("invalid channel")
)
View Source
var NilCallbackError = errors.New("callback is nil")
View Source
var NilListenerError = errors.New("listener is nil")

Functions

func AddLogger

func AddLogger(name string, logger Logger)

AddLogger register a logger into global logger proxy.

func Debug

func Debug(fmt string, args ...interface{})

func Error

func Error(fmt string, args ...interface{})

func Info

func Info(fmt string, args ...interface{})

func LifecycleCheckRun

func LifecycleCheckRun(l Lifecycle) bool

LifecycleCheckRun returns true is specified Lifecycle instance is valid and current is running.

func LifecycleStart

func LifecycleStart(l Lifecycle) error

LifecycleStart check and start specified Lifecycle instance.

func LifecycleStop

func LifecycleStop(l Lifecycle)

LifecycleStop check and stop specified Lifecycle instance.

func NewDecodeError

func NewDecodeError(decoder, msg string) error

NewDecodeError create instance of DecodeError with specified error message.

func NewEncodeError

func NewEncodeError(encoder, msg string) error

NewEncodeError create instance of EncodeError with specified error message.

func RemoveLogger

func RemoveLogger(name string)

RemoveLogger will cancel the specified logger from global logger proxy.

func SetLogLevel

func SetLogLevel(level Level)

SetLogLevel set output limit to global logger proxy.

func Trace

func Trace(fmt string, args ...interface{})

func Warn

func Warn(fmt string, args ...interface{})

Types

type AcceptHandleFunc

type AcceptHandleFunc func(conn net.Conn)

type Acceptor

type Acceptor interface {
	Lifecycle
	Sync
}

Acceptor is a interface wraps necessary methods for network connection acceptance. The implementation should be based on FSM.

func NewAcceptor

func NewAcceptor(config AcceptorConfig) Acceptor

Create a new ParallelAcceptor with acceptor properties.

type AcceptorConfig

type AcceptorConfig struct {
	Parallelism      uint8
	Listener         net.Listener
	AcceptHandleFunc func(conn net.Conn)
}

AcceptorConfig is a data struct for acceptor initialization.

type AckManager

type AckManager interface {
	// InitAck init and register a ack transaction to manager.
	InitAck(key interface{})

	// WaitAck will block invoker goroutine until specified ack transaction commit or timeout.
	WaitAck(key interface{}, timeout time.Duration) (data interface{}, err error)

	// CommitAck commit specified ack transaction.
	CommitAck(key interface{}, data interface{})
}

AckManager is the interface wraps methods for acknowledgement management.

func NewAckManager

func NewAckManager() AckManager

NewAckManager will create a instance of default implementation of AckManage. The current default implementation is safeAckManager.

type ApolloConfig

type ApolloConfig struct {
	TLVConfig
	// contains filtered or unexported fields
}

func (*ApolloConfig) RegisterEntity

func (c *ApolloConfig) RegisterEntity(constructor func() ApolloEntity)

type ApolloEntity

type ApolloEntity interface {
	TypeCode() uint16
}

type ByteBuf

type ByteBuf interface {
	io.Writer
	io.Reader

	ReadIndex() int
	ReadBytes(length int) []byte
	ReadableBytes() int

	WriteIndex() int
	WriteBytes(bytes []byte)
	WritableBytes() int

	Capacity() int
	Reset()
	Release()
}

ByteBuf is the interface provide necessary method of byte buffer with double indexes. The implementation must be designed to consist of two indexes that are read and written separately.

The relationship between reading index and writing index:

+--------------+--------------------+------------------+
|  read bytes  |   readable bytes   |  writable bytes  |
|              |  (unread content)  |      (free)      |
+--------------+--------------------+------------------+
↑              ↑                    ↑                  ↑
0    <=   readerIndex    <=    writerIndex    <=    capacity
+------------------------------------------------------+

Method Reset will reset both read index and write index to 0. Method Release will release read bytes and recalculate indexes.

func NewByteBuf

func NewByteBuf(initSize int) ByteBuf

Create a new instance of ElasticUnsafeByteBuf with init size.

type Channel

type Channel interface {
	Sender
	Close
	Remote() net.Addr
	IsConnected() bool
	GetContext(key string) interface{}
	AddContext(key string, val interface{})
	DelContext(key string)
}

func NewChannel

func NewChannel(pipeline Pipeline) Channel

type ChannelGroup

type ChannelGroup interface {
	// Add will add a specified channel to channel group.
	Add(channel Channel)

	// Remove will remove specified channel from channel group.
	Remove(channel Channel)

	// CloseAll will close all channel which management by channel group and remove
	// all channel from channel group.
	CloseAll()
}

ChannelGroup is a interface wraps methods for channel management which provide batch close support for channels.

func NewHashSafeChannelGroup

func NewHashSafeChannelGroup() ChannelGroup

NewHashSafeChannelGroup create a instance of ChannelGroup based on hash-table.

type ChannelHandler

type ChannelHandler interface {
	// ChannelActivate will be invoked while connection is ready.
	ChannelActivate(channel Channel) error

	// ChannelInActivate will be invoked after connection closed.
	ChannelInactivate(channel Channel) error

	// ChannelRead will be invoked while a message is ready.
	ChannelRead(channel Channel, in interface{}) error

	// ChannelError will be invoked while some exception happened.
	ChannelError(channel Channel, channelErr error)
}

ChannelHandler is the interface provide necessary methods for channel event handle which invoked by pipeline.

type Client

type Client interface {
	Lifecycle
	Sync
	Sender
}

Client is the interface that wraps the basic method to implement a tcp network client.

func NewClient

func NewClient(cfg ClientConfig, initializer PipelineInitializer) Client

NewClient create a new PipelineClient instance with specified configuration and initializer.

type ClientConfig

type ClientConfig struct {
	TCPConfig
	Timeout time.Duration
}

ClientConfig provide properties for client configuration

type Close

type Close interface {
	Close()
}

Close is the interface which wraps method Close().

type DecodeError

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

DecodeError is a error implementation with detail error string output include decoder name and cause for decode exception. The format of complete error string is '$DECODER decode error cause $CAUSE'.

func (*DecodeError) Error

func (e *DecodeError) Error() string

type DecoderInitFunc

type DecoderInitFunc func() FrameDecoder

type EncodeError

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

EncodeError is a error implementation with detail error string output include encoder name and cause for encode exception. The format of complete error string is '$ENCODER encode error cause $CAUSE'.

func (*EncodeError) Error

func (e *EncodeError) Error() string

type EncoderInitFunc

type EncoderInitFunc func() FrameEncoder

type FrameCodec

type FrameCodec interface {
	FrameDecoder
	FrameEncoder
}

FrameCodec is the interface that wraps the basic method for both encode and decode.

type FrameDecoder

type FrameDecoder interface {
	Decode(in ByteBuf) (result interface{}, err error)
}

FrameDecoder is the interface that wraps the basic method for decode tcp stream. A FrameDecoder will be instantiated and init by PipelineInitializer in Pipeline initializing.

Model:

+-------------------------+
|     (src)↓              |
|  Decode(in) → (result)  |
+-------------------------+

func NewApolloFrameDecoder

func NewApolloFrameDecoder(config ApolloConfig) FrameDecoder

NewApolloFrameDecoder create a new apolloFrameDecoder instance with configuration.

func NewStringFrameDecoder

func NewStringFrameDecoder() FrameDecoder

NewStringFrameDecoder create a new stringFrameDecoder instance.

func NewTLVFrameDecoder

func NewTLVFrameDecoder(config TLVConfig) FrameDecoder

NewTLVFrameDecoder create instance of tlvFrameDecoder with specified configuration.

type FrameEncoder

type FrameEncoder interface {
	Encode(msg interface{}) (result []byte, err error)
}

FrameDecoder is the interface that wraps the basic method for encode tcp stream. A FrameEncoder will be instantiated and init by PipelineInitializer in Pipeline initializing.

Model:

+-------------------------+
|     (src)↓              |
|  Encode(in) → (result)  |
+-------------------------+

func NewApolloFrameEncoder

func NewApolloFrameEncoder(config ApolloConfig) FrameEncoder

NewApolloFrameEncoder create a new apolloFrameEncoder instance with configuration.

func NewStringFrameEncoder

func NewStringFrameEncoder() FrameEncoder

NewStringFrameEncoder create a new stringFrameEncoder instance.

func NewTLVFrameEncoder

func NewTLVFrameEncoder(config TLVConfig) FrameEncoder

NewTLVFrameEncoder create instance of tlvFrameEncoder with specified configuration.

type FunctionalChannelHandler

type FunctionalChannelHandler struct {
	HandleActivate   func(channel Channel) error
	HandleInactivate func(channel Channel) error
	HandleRead       func(channel Channel, in interface{}) error
	HandleError      func(channel Channel, err error)
}

FunctionalChannelHandler is a public implementation of ChannelHandler interface which support functional definition for business logic.

func (*FunctionalChannelHandler) ChannelActivate

func (h *FunctionalChannelHandler) ChannelActivate(channel Channel) error

func (*FunctionalChannelHandler) ChannelError

func (h *FunctionalChannelHandler) ChannelError(channel Channel, channelErr error)

func (*FunctionalChannelHandler) ChannelInactivate

func (h *FunctionalChannelHandler) ChannelInactivate(channel Channel) error

func (*FunctionalChannelHandler) ChannelRead

func (h *FunctionalChannelHandler) ChannelRead(channel Channel, in interface{}) error

type FunctionalPipelineInitializer

type FunctionalPipelineInitializer struct {
	DecoderInit DecoderInitFunc
	EncoderInit EncoderInitFunc
	HandlerInit HandlerInitFunc
}

FunctionalPipelineInitializer is a public implementation of PipelineInitializer interface which support functional definition for pipeline initialization logic.

func (*FunctionalPipelineInitializer) InitDecoder

func (*FunctionalPipelineInitializer) InitEncoder

func (*FunctionalPipelineInitializer) InitHandler

type HandlerInitFunc

type HandlerInitFunc func() ChannelHandler

type Init

type Init interface {
	Init() error
}

Init is the interface that wraps the basic method for init.

type Level

type Level uint8

type Lifecycle

type Lifecycle interface {
	Start() error
	Stop()
	IsRunning() bool
}

LifeCycle is the interface that wraps the basic method for standard service lifecycle control.

type Logger

type Logger interface {
	Trace(format string, args ...interface{})
	Debug(format string, args ...interface{})
	Info(format string, args ...interface{})
	Warn(format string, args ...interface{})
	Error(format string, args ...interface{})
}

type Pipeline

type Pipeline interface {
	Lifecycle
	Sync
	Sender
	GetChannel() Channel
	Remote() net.Addr
}

Pipeline is the interface defined necessary methods which makes a pipeline of FrameDecoder, FrameEncoder, and ChannelHandler for inbound and outbound data processing.

Model:

+---------------------------------------+
|         TCP Network Connection        |
+---------------------------------------+
        ↑(write)               ↓(read)
+----------------+     +----------------+
|  FrameEncoder  |     |  FrameDecoder  |
+----------------+     +----------------+
        ↑(outbound)            ↓(inbound)
+----------------+     +----------------+
|    Channel     |     | ChannelHandler |
+----------------+     +----------------+

State:

+-----+           +---------+          +----------+
| NEW | → Start → | RUNNING | → Stop → | SHUTDOWN |
+-----+           +---------+          +----------+

Notes: The implementations should be parallel safe and based on FSM.

func NewPipeline

func NewPipeline(conn net.Conn, initializer PipelineInitializer) (Pipeline, error)

NewPipeline create and init pipeline with initializer.

type PipelineInitializer

type PipelineInitializer interface {
	//  InitDecoder used for decoder initialization.
	InitDecoder() FrameDecoder

	//  InitEncoder used for encoder initialization.
	InitEncoder() FrameEncoder

	// InitHandler used for channel handler initialization.
	InitHandler() ChannelHandler
}

ChannelHandler is the interface provide necessary methods for pipeline initialization which invoked by pipeline.

type Sender

type Sender interface {
	Send(data interface{}) error
	SendFuture(data interface{}, callback func(err error))
}

type Server

type Server interface {
	Lifecycle
	Sync
}

Server is the interface that wraps the basic method to implement a tcp network server based on FSM.

func NewServer

func NewServer(cfg ServerConfig, initializer PipelineInitializer) Server

NewServer init a new server instance with specified configuration and initializer.

type ServerConfig

type ServerConfig struct {
	TCPConfig
	AcceptorSize uint8
}

ServerConfig provide properties for server configuration

type Sync

type Sync interface {
	Sync()
}

Sync is the interface that wraps the Sync() method which will block invoker goroutine.

type TCPConfig

type TCPConfig struct {
	Port            int
	IP              net.IP
	KeepAlive       bool
	KeepAlivePeriod time.Duration
}

func (*TCPConfig) ApplyTCP

func (c *TCPConfig) ApplyTCP(conn *net.TCPConn)

TryApplyTCPConfig will setup specified tcp connection with specified config if possible.

type TLVConfig

type TLVConfig struct {
	TagValue   uint8
	FrameLimit uint32
}

TLVConfig is a data struct provide configuration properties for both tlvFrameDecoder and tlvFrameEncoder.

+----------+-----------+-----------+
|    TAG   |  LENGTH   |   VALUE   |
| (1 byte) | (4 bytes) | (payload) |
+----------+-----------+-----------+
     ↑
  TagValue

type Type

type Type interface {
	Type() string
}

Type is the interface wraps method to get string type value.

type UnknownAddr

type UnknownAddr struct {
}

func (*UnknownAddr) Network

func (ua *UnknownAddr) Network() string

func (*UnknownAddr) String

func (ua *UnknownAddr) String() string

Jump to

Keyboard shortcuts

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