fatchoy

package module
v0.4.8 Latest Latest
Warning

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

Go to latest
Published: Jan 27, 2022 License: BSD-3-Clause Imports: 29 Imported by: 0

README

fatchoy

Gung Hay Fat Choy(恭喜發財)

A set of libraries to create online game server.

包含基本的基本的TCP通信,消息编解码,常用数据结构,以及简单的服务发现

How To Use

go get -u -v qchen.fun/fatchoy

各目录说明

目录 描述
codec 编解码
codes 错误码
collections 数据结构
debug 调试API
discovery 服务发现
log 日志
qnet 网络通信
x 工具包

开发规范指南

GUIDE

Documentation

Index

Constants

View Source
const (
	FOREACH_CONTINUE = 0
	FOREACH_EXIT     = 1
)

foreach控制

View Source
const (
	SERVICE_ALL  = 0xFF   // 所有服务
	INSTANCE_ALL = 0xFFFF // 所有实例
)
View Source
const (
	AllocPolicyRuntime = 0
	AllocPolicyPool    = 1
	AllocPolicyArena   = 2
)

不同的分配算法(策略)

View Source
const (
	SuffixREQ = "Req"
	SuffixACK = "Ack"
	SuffixNTF = "Ntf"
)
View Source
const (
	NodeServiceShift = 16
	NodeTypeShift    = 31
	NodeServiceMask  = 0x00FF0000
	NodeInstanceMask = 0x0000FFFF
)
View Source
const (
	StateInit         = 0
	StateStarting     = 1
	StateRunning      = 2
	StateShuttingDown = 3
	StateTerminated   = 4
)
View Source
const (
	TaskStateInit = 0
	TaskScheduled = 1 // task is scheduled for execution
	TaskExecuted  = 2 // a non-repeating task has already executed (or is currently executing) and has not been cancelled.
	TaskCancelled = 3 // task has been cancelled (with a call to TimerTask.Cancel).
)
View Source
const (
	PendingQueueCapacity = 128  // pending add/delete
	TimeoutQueueCapacity = 1024 // pending timed-out
)
View Source
const ClockEpoch int64 = 1577836800 // 2020-01-01 00:00:00 UTC

epoch of clock

View Source
const VERSION = "0.4.8"

版本号

Variables

View Source
var ErrContextInboundQueueFull = errors.New("context inbound queue full")
View Source
var ErrNoHandlers = errors.New("no handlers for command")

Functions

func CreateMessageByID added in v0.4.4

func CreateMessageByID(hash uint32) proto.Message

根据名称创建消息

func CreateMessageByName added in v0.4.4

func CreateMessageByName(name string) proto.Message

根据名称创建消息

func CreatePairingAck added in v0.4.4

func CreatePairingAck(req proto.Message) proto.Message

如果消息的名字是XXXReq,则尝试创建与其名称对应的XXXAck消息

func CreatePairingAckBy added in v0.4.4

func CreatePairingAckBy(reqName string) proto.Message

如果消息的名字是XXXReq,则尝试创建与其名称对应的XXXAck消息

func DateTime

func DateTime() string

func DeregisterHandler added in v0.4.8

func DeregisterHandler(command int32)

func DispatchMessage added in v0.4.8

func DispatchMessage(ctx context.Context, msg *Message) error

func FreeMessage added in v0.4.7

func FreeMessage(msg *Message)

回收Message

func GetEnv added in v0.4.7

func GetEnv(key string, def string) string

获取环境

func GetEnvBool added in v0.4.7

func GetEnvBool(key string) bool

获取环境变量bool值

func GetEnvFloat added in v0.4.7

func GetEnvFloat(key string, def float64) float64

获取环境变量float值

func GetEnvInt added in v0.4.7

func GetEnvInt(key string, def int) int

获取环境变量int值

func GetEnvInt64 added in v0.4.7

func GetEnvInt64(key string, def int64) int64

func GetMessageIDByName added in v0.4.4

func GetMessageIDByName(name string) uint32

根据名称获取消息ID

func GetMessageIDOf added in v0.4.4

func GetMessageIDOf(msg proto.Message) uint32

根据message获取消息ID

func GetMessageNameByID added in v0.4.4

func GetMessageNameByID(hash uint32) string

根据消息ID获取名称

func GetPairingAckName added in v0.4.4

func GetPairingAckName(reqName string) string

根据Req消息的名称,返回其对应的Ack消息名称

func GetServiceNames added in v0.2.6

func GetServiceNames() []string

所有服务类型名

func IBody2Bytes added in v0.4.1

func IBody2Bytes(body interface{}) []byte

将body转为[]byte,用于网络传输

func IBody2Float added in v0.4.1

func IBody2Float(body interface{}) float64

将body转为float4

func IBody2Int64 added in v0.4.1

func IBody2Int64(body interface{}) int64

将body转为int64

func IBody2String added in v0.4.1

func IBody2String(body interface{}) string

将body转为string

func IBodyAsBytes added in v0.4.1

func IBodyAsBytes(body interface{}) []byte

func Now

func Now() time.Time

func NowString

func NowString() string

func PB2JSON added in v0.4.1

func PB2JSON(msg proto.Message) string

func RegisterAllAPI added in v0.4.4

func RegisterAllAPI()

自动注册所有protobuf消息 因为protobuf使用init()注册(RegisterType),此API需要在import后调用

func RegisterHandler added in v0.4.8

func RegisterHandler(command int32, action MessageHandler)

func RegisterService added in v0.3.8

func RegisterService(s Service)

注册服务

func SafeToBody added in v0.4.1

func SafeToBody(val interface{}) interface{}

interface转换为body

func SetMessageAllocPolicy added in v0.4.7

func SetMessageAllocPolicy(policy int)

设置分配策略

func SetPanicHandler added in v0.4.8

func SetPanicHandler(f PanicHandler)

func StartClock

func StartClock()

开启时钟

func StopClock

func StopClock()

关闭时钟

func WallClock

func WallClock() *datetime.Clock

Types

type ArenaAllocator added in v0.4.2

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

arena算法的分配器 思路是:

	 一次申请一个block(N个元素的数组),然后从block数组里再逐个按需分配,block分配完了就丢掉(交给GC),再申请另一个block
  这样对runtime来说每次malloc都是以N个元素大小的单位,理论上可以减缓GC的压力,并且业务层无需做Free

func NewArenaAllocator added in v0.4.2

func NewArenaAllocator(blockSize int) *ArenaAllocator

func (*ArenaAllocator) Alloc added in v0.4.2

func (a *ArenaAllocator) Alloc() *Message

分配一个消息

func (*ArenaAllocator) Free added in v0.4.2

func (a *ArenaAllocator) Free(msg *Message)

没有实现手动回收

type Endpoint

type Endpoint interface {
	MessageEndpoint

	// 原始连接对象
	RawConn() net.Conn

	// 发送/接收计数数据
	Stats() *stats.Stats

	ErrorChan() <-chan error
	OutMsgChan() chan<- *Message

	// 开启read/write线程
	Go(EndpointFlag)

	// 设置加解密
	SetEncryptPair(cipher.BlockCryptor, cipher.BlockCryptor)
}

网络端点

type EndpointFlag

type EndpointFlag uint32

开启reader/writer标记

const (
	EndpointReader     EndpointFlag = 0x01 // 只开启reader
	EndpointWriter     EndpointFlag = 0x02 // 只开启writer
	EndpointReadWriter EndpointFlag = 0x03 // 开启reader和writer
)

type EndpointMap

type EndpointMap interface {
	Size() int
	Has(node NodeID) bool
	Get(node NodeID) Endpoint
	IsEmpty() bool
	Foreach(func(Endpoint) bool)
	Put(node NodeID, endpoint Endpoint)
	PutIfAbsent(node NodeID, endpoint Endpoint)
	Remove(node NodeID)
	Pop(node NodeID) Endpoint
	Clear()
}

线程安全的Endpoint字典

type IMessageAllocator added in v0.4.2

type IMessageAllocator interface {
	Alloc() *Message
	Free(*Message)
}

func GetMessageAllocator added in v0.4.7

func GetMessageAllocator(policy int) IMessageAllocator

type Message added in v0.4.1

type Message struct {
	Command  int32           `json:"cmd"`            // 协议命令,即如何执行消息
	MsgID    uint32          `json:"mid,omitempty"`  // 协议ID,即如何解析body
	Seq      uint16          `json:"seq,omitempty"`  // 会话内的唯一序列号
	Flags    PacketFlag      `json:"flg,omitempty"`  // 标志位
	Node     NodeID          `json:"node,omitempty"` // 源/目标节点
	Refers   []NodeID        `json:"ref,omitempty"`  // 组播session列表
	Body     interface{}     `json:"body,omitempty"` // 消息内容,int32/int64/float64/string/bytes/proto.Message
	Endpoint MessageEndpoint `json:"-"`              // 关联的endpoint
}

Message表示一个应用层消息

func AllocMessage added in v0.4.2

func AllocMessage() *Message

分配一个Message

func NewMessage added in v0.4.1

func NewMessage(cmd int32, flags PacketFlag, seq uint16, body interface{}) *Message

func (*Message) AddRefers added in v0.4.3

func (m *Message) AddRefers(refers ...NodeID)

func (*Message) AutoDecode added in v0.4.5

func (m *Message) AutoDecode() error

根据MsgID把body的字节流解析为proto消息

func (*Message) Clone added in v0.4.1

func (m *Message) Clone() *Message

func (*Message) DecodeTo added in v0.4.1

func (m *Message) DecodeTo(msg proto.Message) error

func (*Message) EncodeToBytes added in v0.4.1

func (m *Message) EncodeToBytes() []byte

func (*Message) Errno added in v0.4.1

func (m *Message) Errno() int32

func (*Message) Refuse added in v0.4.4

func (m *Message) Refuse(errno int32) error

返回一个错误码消息

func (*Message) Reply added in v0.4.4

func (m *Message) Reply(ack proto.Message) error

响应proto消息内容

func (*Message) ReplyAny added in v0.4.4

func (m *Message) ReplyAny(body interface{}) error

body的类型仅支持int64/float64/string/bytes/proto.Message

func (*Message) Reset added in v0.4.1

func (m *Message) Reset()

func (*Message) SetBody added in v0.4.1

func (m *Message) SetBody(val interface{})

func (*Message) SetErrno added in v0.4.1

func (m *Message) SetErrno(ec int32)

func (*Message) String added in v0.4.1

func (m *Message) String() string

type MessageDispatcher added in v0.4.8

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

消息派发

func DefaultDispatcher added in v0.4.8

func DefaultDispatcher() *MessageDispatcher

func NewMessageDispatcher added in v0.4.8

func NewMessageDispatcher() *MessageDispatcher

func (*MessageDispatcher) Deregister added in v0.4.8

func (d *MessageDispatcher) Deregister(command int32)

取消所有

func (*MessageDispatcher) DeregisterOne added in v0.4.8

func (d *MessageDispatcher) DeregisterOne(command int32, handler MessageHandler)

取消单个注册

func (*MessageDispatcher) Dispatch added in v0.4.8

func (d *MessageDispatcher) Dispatch(ctx context.Context, msg *Message) error

func (*MessageDispatcher) Register added in v0.4.8

func (d *MessageDispatcher) Register(command int32, handler MessageHandler)

注册一个

func (*MessageDispatcher) SetPanicHandler added in v0.4.8

func (d *MessageDispatcher) SetPanicHandler(f PanicHandler)

type MessageEndpoint

type MessageEndpoint interface {
	// 节点ID
	NodeID() NodeID
	SetNodeID(NodeID)

	// 远端地址
	RemoteAddr() string

	// 发送消息(非阻塞)
	Send(*Message) error

	// 关闭读/写
	Close() error
	ForceClose(error)

	IsRunning() bool

	// 绑定自定义数据
	SetUserData(interface{})
	UserData() interface{}
}

绑定到消息上的endpoint

type MessageHandler added in v0.4.1

type MessageHandler func(context.Context, *Message) error

消息处理器

type NetPacket added in v0.4.1

type NetPacket struct {
	Timestamp int64
	Head      []byte
	Body      []byte
	Session   Endpoint
}

网络packet

type NodeID

type NodeID uint32

节点ID 一个32位整数表示的节点号,用以标识一个service(最高位为0),或者一个客户端session(最高位为1) 如果是服务编号:8位服务编号,16位服务实例编号

服务实例二进制布局
	--------------------------------------
	|  reserved |  service  |  instance  |
	--------------------------------------
	32          24         16            0

func MakeNodeID

func MakeNodeID(service uint8, instance uint16) NodeID

根据服务号和实例号创建一个节点ID

func MustParseNodeID

func MustParseNodeID(s string) NodeID

解析16进制字符串的节点ID

func (NodeID) Instance

func (n NodeID) Instance() uint16

service节点的实例编号

func (NodeID) IsTypeBackend

func (n NodeID) IsTypeBackend() bool

是否service节点

func (NodeID) Service

func (n NodeID) Service() uint8

service节点的service类型

func (NodeID) String

func (n NodeID) String() string

type NodeIDSet

type NodeIDSet = collections.OrderedIDSet

没有重复ID的有序集合

type PacketFlag

type PacketFlag uint16

消息标志位

const (
	// 低8位用于表达一些传输flag
	PFlagCompressed PacketFlag = 0x01 // 压缩
	PFlagEncrypted  PacketFlag = 0x02 // 加密
	PFlagError      PacketFlag = 0x04 // 错误标记
	PFlagHashCmd    PacketFlag = 0x10 // CMD是字符串hash
	PFlagReserve    PacketFlag = 0x20 //
	PFlagRPC        PacketFlag = 0x40 // 远程调用

	// 高8位用于server之间通信使用
	PFlagRawBody   PacketFlag = 0x0100 // body是未解析的字节流
	PFlagMulticast PacketFlag = 0x1000 // 组播消息
	PFlagRoute     PacketFlag = 0x2000 // 路由消息
)

func (PacketFlag) Clear added in v0.1.21

func (g PacketFlag) Clear(n PacketFlag) PacketFlag

func (PacketFlag) Has added in v0.1.21

func (g PacketFlag) Has(n PacketFlag) bool

type PanicHandler added in v0.4.8

type PanicHandler func(*Message, interface{})

type PoolAllocator added in v0.4.2

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

使用sync.Pool的分配器

func NewPoolAllocator added in v0.4.2

func NewPoolAllocator() *PoolAllocator

func (*PoolAllocator) Alloc added in v0.4.2

func (a *PoolAllocator) Alloc() *Message

func (*PoolAllocator) Free added in v0.4.2

func (a *PoolAllocator) Free(msg *Message)

放回pool里供后面的Alloc使用

type Runnable added in v0.4.8

type Runnable interface {
	Run() error
}

Runnable代表一个可执行对象

type RuntimeAllocator added in v0.4.2

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

使用new函数的分配器

func NewRuntimeAllocator added in v0.4.2

func NewRuntimeAllocator() *RuntimeAllocator

func (*RuntimeAllocator) Alloc added in v0.4.2

func (a *RuntimeAllocator) Alloc() *Message

func (*RuntimeAllocator) Free added in v0.4.2

func (a *RuntimeAllocator) Free(msg *Message)

type Service

type Service interface {
	Type() uint8
	Name() string

	// 节点ID
	NodeID() NodeID
	SetNodeID(id NodeID)

	// 当前状态
	State() int32
	SetState(int32)

	// 上下文对象
	Context() *ServiceContext

	// 初始化
	Init(context.Context, *ServiceContext) error

	// 启动服务
	Startup(context.Context) error
}

一个Service代表一个服务

func CreateService added in v0.3.1

func CreateService(name string) Service

根据名称创建Service对象

type ServiceContext

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

服务的上下文

func NewServiceContext

func NewServiceContext(queueSize int) *ServiceContext

func (*ServiceContext) AddFinalizer added in v0.1.28

func (c *ServiceContext) AddFinalizer(action func())

func (*ServiceContext) Close

func (c *ServiceContext) Close()

关闭context

func (*ServiceContext) InboundQueue added in v0.1.6

func (c *ServiceContext) InboundQueue() chan<- *Message

消息队列,仅接收

func (*ServiceContext) Instance added in v0.1.2

func (c *ServiceContext) Instance() Service

service实例

func (*ServiceContext) MessageQueue

func (c *ServiceContext) MessageQueue() <-chan *Message

消息队列,仅消费

func (*ServiceContext) QuitDone added in v0.1.24

func (c *ServiceContext) QuitDone() <-chan struct{}

等待close完成

func (*ServiceContext) RunID added in v0.1.5

func (c *ServiceContext) RunID() string

唯一运行ID

func (*ServiceContext) Send added in v0.1.5

func (c *ServiceContext) Send(pkt *Message)

投递一条消息到context

func (*ServiceContext) SetInstance added in v0.2.9

func (c *ServiceContext) SetInstance(inst Service)

func (*ServiceContext) StartTime added in v0.1.24

func (c *ServiceContext) StartTime() time.Time

type State added in v0.1.19

type State int32

service state

func (*State) CAS added in v0.1.19

func (s *State) CAS(old, new int32) bool

func (*State) Get added in v0.1.19

func (s *State) Get() int32

func (*State) IsRunning added in v0.1.19

func (s *State) IsRunning() bool

func (*State) IsShuttingDown added in v0.1.19

func (s *State) IsShuttingDown() bool

func (*State) IsTerminated added in v0.1.19

func (s *State) IsTerminated() bool

func (*State) Set added in v0.1.19

func (s *State) Set(n int32)

type Task added in v0.4.8

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

待执行的任务

func NewTask added in v0.4.8

func NewTask(action func() error) *Task

func (*Task) Cancel added in v0.4.8

func (r *Task) Cancel() bool

func (*Task) Run added in v0.4.8

func (r *Task) Run() error

func (*Task) SetState added in v0.4.8

func (r *Task) SetState(state int32)

func (*Task) State added in v0.4.8

func (r *Task) State() int32

type Timer added in v0.4.8

type Timer interface {
	Start()

	// 关闭定时器
	Shutdown()

	// 在`timeUnits`时间后执行`r`
	RunAfter(timeUnits int, r Runnable) int

	// 每隔`interval`时间执行`r`
	RunEvery(interval int, r Runnable) int

	// 取消一个timer
	Cancel(id int) bool

	// 判断timer是否在计划中
	IsPending(id int) bool

	// 超时的待执行runner
	Chan() <-chan Runnable

	// timer数量
	Size() int
}

定时器

func NewDefaultTimerQueue added in v0.4.8

func NewDefaultTimerQueue() Timer

func NewTimerQueue added in v0.4.8

func NewTimerQueue(tickInterval, timeUnit time.Duration) Timer

type TimerQueue added in v0.4.8

type TimerQueue struct {
	C chan Runnable // 到期的定时器
	// contains filtered or unexported fields
}

最小堆实现的定时器 标准库的四叉堆实现的time.Timer已经可以满足大多数高精度的定时需求 这个实现主要是为了在大量timer的场景,把timer的压力从runtime放到应用上

func (*TimerQueue) Cancel added in v0.4.8

func (s *TimerQueue) Cancel(id int) bool

取消一个timer

func (*TimerQueue) Chan added in v0.4.8

func (s *TimerQueue) Chan() <-chan Runnable

func (*TimerQueue) IsPending added in v0.4.8

func (s *TimerQueue) IsPending(id int) bool

func (*TimerQueue) RunAfter added in v0.4.8

func (s *TimerQueue) RunAfter(timeUnits int, r Runnable) int

创建一个定时器,在`timeUnits`时间后运行`r`

func (*TimerQueue) RunEvery added in v0.4.8

func (s *TimerQueue) RunEvery(interval int, r Runnable) int

创建一个定时器,每隔`interval`时间运行一次`r`

func (*TimerQueue) Shutdown added in v0.4.8

func (s *TimerQueue) Shutdown()

func (*TimerQueue) Size added in v0.4.8

func (s *TimerQueue) Size() int

func (*TimerQueue) Start added in v0.4.8

func (s *TimerQueue) Start()

Starts the background thread explicitly

Jump to

Keyboard shortcuts

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