lokas

package module
v0.3.37 Latest Latest
Warning

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

Go to latest
Published: Jun 8, 2023 License: MIT Imports: 21 Imported by: 3

README

lokas

a go implementation of entity-component system

Documentation

Index

Constants

View Source
const (
	DEFAULT_PACKET_LEN = 2048 * 4
	DEFAULT_ACTOR_TTL  = 15
)

Variables

This section is empty.

Functions

func Get added in v0.2.1

func Get[T IComponent](entity IEntity) T

func LogActorId added in v0.3.34

func LogActorId(actor IActorInfo) zap.Field

func LogActorInfo added in v0.3.34

func LogActorInfo(actor IActorInfo) log.ZapFields

func LogActorProcessId added in v0.3.34

func LogActorProcessId(actor IActorInfo) zap.Field

func LogActorReceiveMsgInfo added in v0.3.34

func LogActorReceiveMsgInfo(actor IActorInfo, serializable protocol.ISerializable, transid uint32, fromActorId util.ID) log.ZapFields

func LogActorSendMsgInfo added in v0.3.34

func LogActorSendMsgInfo(actor IActorInfo, serializable protocol.ISerializable, transid uint32, toActorId util.ID) log.ZapFields

func LogActorType added in v0.3.34

func LogActorType(actor IActorInfo) zap.Field

func LogAvatarGate added in v0.3.34

func LogAvatarGate(avatar IAvatarSession) zap.Field

func LogAvatarInfo added in v0.3.34

func LogAvatarInfo(avatar IActor) log.ZapFields

func LogAvatarMsgDetail added in v0.3.34

func LogAvatarMsgDetail(avatar IAvatar, transId uint32, msg protocol.ISerializable, sess util.ID) log.ZapFields

func LogAvatarMsgInfo added in v0.3.34

func LogAvatarMsgInfo(avatar IAvatar, transId uint32, msg protocol.ISerializable, sess util.ID) log.ZapFields

func LogAvatarName added in v0.3.34

func LogAvatarName(avatar IAvatarSession) zap.Field

func LogAvatarServer added in v0.3.34

func LogAvatarServer(avatar IAvatarSession) zap.Field

func LogAvatarSessionId added in v0.3.34

func LogAvatarSessionId(avatar IAvatarSession) zap.Field

func LogAvatarSessionInfo added in v0.3.34

func LogAvatarSessionInfo(avatar IAvatarSession) log.ZapFields

func LogAvatarSessionMsgInfo added in v0.3.34

func LogAvatarSessionMsgInfo(avatar IAvatarSession, transId uint32, msg protocol.ISerializable, sess util.ID) log.ZapFields

func LogAvatarUserId added in v0.3.34

func LogAvatarUserId(avatar IAvatarSession) zap.Field

func LogModule added in v0.3.34

func LogModule(s IModule) zap.Field

func LogServiceInfo added in v0.3.34

func LogServiceInfo(service *ServiceInfo) log.ZapFields

func Remove added in v0.2.1

func Remove[T IComponent](entity IEntity) T

func Sibling added in v0.2.2

func Sibling[T IComponent](c IComponent) T

Types

type ActorState

type ActorState int //Actor health state
const (
	ACTOR_STARTING ActorState = iota + 1
	ACTOR_HEALTHY
	ACTOR_UNHEALTHY
	ACTOR_ERRORED
	ACTOR_STOPPED
)

type AsyncCallBack

type AsyncCallBack func(context IReqContext)

type Context

type Context struct {
	SessionCreator        func(conn IConn) ISession
	Splitter              bufio.SplitFunc      // packet splitter
	IPChecker             func(ip string) bool // check if an accepted connection is allowed
	IdleTimeAfterOpen     time.Duration        // idle time when open, conn will be closed if not activated after this time
	ReadBufferSize        int                  // buffer size for reading
	WriteBufferSize       int                  // buffer size for writing
	UseNoneBlockingChan   bool                 // use none blocking chan
	ChanSize              int                  // chan size for bufferring
	MaxMessageSize        int                  // max message size for a single packet
	MergedWriteBufferSize int                  // buffer size for merged write
	DisableMergedWrite    bool                 // disable merge multiple message to a single net.Write
	EnableStatistics      bool                 // enable statistics of packets send and recv
	Extra                 interface{}          // used for special cases when custom data is needed
	LongPacketPicker      LongPacketPicker     // check and pick long packet when recv
	LongPacketCreator     LongPacketCreator    // create long packet for send
	MaxPacketWriteLen     int                  // data size for long packet
}

Content context for create a dialer or a listener

type IActor

type IActor interface {
	IEntity
	// IProxy
	IModule
	timer.TimeHandler
	PId() util.ProcessId
	ReceiveMessage(msg *protocol.RouteMessage)
	OnMessage(msg *protocol.RouteMessage)
	SendMessage(actorId util.ID, transId uint32, msg protocol.ISerializable) error
	Call(actorId util.ID, req protocol.ISerializable) (protocol.ISerializable, error)
	GetLeaseId() (clientv3.LeaseID, bool, error)
	Update(dt time.Duration, now time.Time)

	ReceiveData(recv *protocol.RouteDataMsg) error

	Subscribe(key string) error
	Unsubscribe(key string) error
	Publish(key string, msg protocol.ISerializable) error
	Request(key string, msg protocol.ISerializable) (protocol.ISerializable, error)
}

IActor standard interface for actor

type IActorContainer

type IActorContainer interface {
	AddActor(actor IActor)
	RemoveActor(actor IActor)
	RemoveActorById(id util.ID) IActor
	GetActorIds() []util.ID
	GetActor(id util.ID) IActor
	StartActor(actor IActor) error
}

IActorContainer container for IActor

type IActorInfo added in v0.1.4

type IActorInfo interface {
	GetId() util.ID
	PId() util.ProcessId
	Type() string
}

type IAvatar added in v0.1.29

type IAvatar interface {
	IActor
	IAvatarSession
	SendEvent(serializable protocol.ISerializable) error
}

type IAvatarSession added in v0.1.29

type IAvatarSession interface {
	GetGameId() string
	GetServerId() int32
	GetGateId() util.ID
	GetUserName() string
	GetUserId() util.ID
	GetId() util.ID
}

type IComponent

type IComponent interface {
	protocol.ISerializable
	GetEntity() IEntity
	SetDirty(d bool)
	Dirty() bool
	SetRuntime(engine IRuntime)
	GetRuntime() IRuntime
	SetEntity(e IEntity)
	OnAdd(e IEntity, r IRuntime)
	OnRemove(e IEntity, r IRuntime)
	OnCreate(r IRuntime)
	OnDestroy(r IRuntime)
	GetSibling(t protocol.BINARY_TAG) IComponent
}

IComponent base component of protocol

type IComponentPool

type IComponentPool interface {
	Recycle(comp IComponent)
	Get() IComponent
	Create(args ...interface{}) IComponent
	Destroy()
}

IComponentPool pool for IComponent

type IConfig

type IConfig interface {
	Save() error
	Load() error
	LoadFromLocal() error
	GetFolder() string
	LoadFromRemote() error
	SetRemoteConfig(p string, etcd string)
	Set(key string, value interface{})
	Get(key string) interface{}
	Sub(key string) IConfig
	GetBool(key string) bool
	GetFloat64(key string) float64
	GetInt(key string) int
	GetString(key string) string
	GetStringMap(key string) map[string]interface{}
	GetStringMapString(key string) map[string]string
	GetStringMapStringSlice(key string) map[string][]string
	GetIntSlice(key string) []int
	GetInt32Slice(key string) []int32
	GetSizeInBytes(key string) uint
	GetStringSlice(key string) []string
	GetTime(key string) time.Time
	GetDuration(key string) time.Duration
	IsSet(key string) bool
	AllSettings() map[string]interface{}
}

type IConn

type IConn interface {
	net.Conn
	SetUserData(userData interface{}) // set application layer reference data
	GetUserData() interface{}         // get application layer reference data
	GetSession() ISession             // get the bound session
	GetConnTime() time.Time           // get connection init time
	Activate()                        // activate the conn, used with idle check
	// GraceClose() error                // gracefully close the connection, after all the pending packets sent to the peer
	Wait() // wait for close
}

IConn interface for a connection, either a client connection or server accepted connection

type IContext

type IContext interface {
	Get(key string) interface{}
	GetIdType(key string) util.ID
	GetProcessIdType(key string) util.ProcessId
	GetString(key string) string
	GetInt(key string) int
	GetBool(key string) bool
	GetInt32(key string) int32
	GetInt64(key string) int64
	GetFloat32(key string) float32
	GetFloat64(key string) float64
	Set(key string, value interface{})
}

IContext context interface

type IEntity

type IEntity interface {
	events.EventEmmiter
	Dirty() bool
	SetDirty(bool)
	Get(t protocol.BINARY_TAG) IComponent
	GetOrCreate(t protocol.BINARY_TAG) IComponent
	Add(c IComponent)
	Remove(t protocol.BINARY_TAG) IComponent
	RemoveAll()
	SetId(id util.ID)
	GetId() util.ID
	Components() map[protocol.BINARY_TAG]IComponent
}

IEntity entity of ecs system,container of IComponent

type IEntityNetClient added in v0.0.8

type IEntityNetClient interface {
	IEntity
	INetClient
}

type IGameHandler added in v0.1.29

type IGameHandler interface {
	GetInitializer() func(avatar IActor, process IProcess) error
	GetSerializer() func(avatar IActor, process IProcess) error
	GetDeserializer() func(avatar IActor, process IProcess) error
	GetUpdater() func(avatar IActor, process IProcess) error
	GetMsgDelegator() func(avatar IActor, actorId util.ID, transId uint32, msg protocol.ISerializable) (protocol.ISerializable, error)
}

type ILogInfo added in v0.3.34

type ILogInfo interface {
	LogInfo() log.ZapFields
}

type IModel

type IModel interface {
	GetId() util.ID
	Deserialize(a IProcess) error
	Initialize(a IProcess) error
	Serialize(a IProcess) error
}

type IModule

type IModule interface {
	Type() string
	Load(conf IConfig) error
	Unload() error
	GetProcess() IProcess
	SetProcess(IProcess)
	Start() error
	Stop() error
	OnStart() error
	OnStop() error
}

IModule module interface

type IModuleCtor

type IModuleCtor interface {
	Type() string
	Create() IModule
}

IModuleCtor module export interface

type INetClient

type INetClient interface {
	SendMessage(transId uint32, msg interface{})
	SetProtocol(p protocol.TYPE)
	Connect(addr string) *promise.Promise[interface{}]
	Disconnect(bool) *promise.Promise[interface{}]
	Request(req interface{}) *promise.Promise[interface{}]
	SetMessageHandler(handler func(msg *protocol.BinaryMessage))
	GetContext(uint32) IReqContext
	Connected() bool
	OnRecvCmd(cmdId protocol.BINARY_TAG, time time.Duration) *promise.Promise[interface{}]
	OnRecv(conn IConn, data []byte)
}

INetClient interface for client

type IProcess

type IProcess interface {
	IRegistry
	IActorContainer
	IRouter
	IProxy
	Add(modules IModule) IModule             //add a module
	RegisterModule(ctor IModuleCtor)         //register a module ctor
	LoadAllModule(IProcessConfig) error      //load all module from config
	LoadMod(name string, conf IConfig) error //load a module with config
	UnloadMod(name string) error             //unload a module
	Get(name string) IModule                 //get a module
	Load(IProcessConfig) error               //load config
	Start() error                            //start process
	Stop() error                             //stop process
	PId() util.ProcessId                     //PId
	GetId() util.ID                          //PId to snowflake
	Type() string
	GenId() util.ID                                             //gen snowflake Id,goroutine safe
	GetLogger() *log.ComposeLogger                              //get process logger
	GetMongo() *qmgo.Database                                   //get mongo client
	GetRedis() *redisclient.Client                              //get redis client
	GetEtcd() *etcdclient.Client                                //get etcd client
	GetOss() *ossclient.Client                                  //get etcd client
	GetDocker() (*dockerclient.Client, error)                   //get docker client
	GlobalMutex(key string, ttl int) (*etcdclient.Mutex, error) //create a distributed global mutex based on etcd
	Config() IConfig                                            //get config
	GameId() string                                             //get game id
	ServerId() int32                                            //get server id
	GameServerId() string                                       //get game and server id
	Version() string                                            //get version

}

IProcess the interface for application entry

type IProcessConfig

type IProcessConfig interface {
	IConfig
	GetName() string    //config name
	ServerName() string //serverName
	GetProcessId() util.ProcessId
	GetGameId() string
	GetServerId() int32
	GetVersion() string
	GetDb(string) interface{}
	GetAllSub() []IConfig //get all config for sub modules
	GetDockerCLI() interface{}
}

type IProxy

type IProxy interface {
	Send(id util.ProcessId, msg *protocol.RouteMessage) error

	SendData(id util.ProcessId, data []byte) error
}

IProxy universal module interface for connection

type IRegistry

type IRegistry interface {
	GetProcessIdByActor(actorId util.ID) (util.ProcessId, error)
	RegisterActors() error
	RegisterActorRemote(actor IActor) error
	UnregisterActorRemote(actor IActor) error
	RegisterActorLocal(actor IActor) error
	UnregisterActorLocal(actor IActor) error
	GetActorIdsByTypeAndServerId(serverId int32, typ string) []util.ID

	GetServiceRegisterMgr() IServiceRegisterMgr
	GetServiceDiscoverMgr() IServiceDiscoverMgr
}

IRegistry interface for global registration

type IReqContext

type IReqContext interface {
	context.Context
	IContext
	GetTransId() uint32
	GetResp() interface{}
	SetResp(interface{})
	SetCallback(cb AsyncCallBack)
	GetCallback() AsyncCallBack
	Cancel(err error)
	Finish()
}

type IRouter

type IRouter interface {
	RouteMsg(msg *protocol.RouteMessage)
	RouteMsgLocal(msg *protocol.RouteMessage) error

	// RouteMsgByAvatar(fromActorId util.ID, toActorId util.ID, transId uint32, reqType uint8, msg protocol.ISerializable) error
	RouteMsgToService(fromActorId util.ID, serviceType string, serviceId uint16, lineId uint16, transId uint32, reqType uint8, msg protocol.ISerializable, protocolType protocol.TYPE) error

	RouteDataByService(routeDataMsg *protocol.RouteDataMsg, serviceType string, serviceId uint16, lineId uint16) error

	RouteMsgWithPid(routeMsg *protocol.RouteMessage, pid util.ProcessId) error

	RouteDataMsgLocal(dataMsg *protocol.RouteDataMsg) error
}

IRouter interface for router

type IRuntime

type IRuntime interface {
	Init(updateTime int64, timeScale float32, server bool)
	GetContext(name string) interface{}
	SetContext(name string, value interface{})
	GetEntity(util.ID) IEntity
	CurrentTick() int64
	Start()
	Stop()
	RunningTime() int64
	GetTimeScale() float32
	SetTimeScale(scale float32)
	RegisterComponent(name string, c IComponent)
	RegisterSingleton(name string, c IComponent)
	GetComponentType(name string) reflect.Type
	IsSyncAble(compName string) bool
	CreateEntity() IEntity
	IsServer() bool
	//private
	MarkDirtyEntity(e IEntity)
}

IRuntime interface for ecs runtime

type IServiceDiscoverMgr added in v0.2.30

type IServiceDiscoverMgr interface {
	FindServiceInfo(serviceType string, serviceId uint16, lineId uint16) (*ServiceInfo, bool)

	// if serviceId is zero, get a random serviceId; if lineId is zero, get a random lineId
	FindRandServiceInfo(serviceType string, serviceId uint16, lineId uint16) (*ServiceInfo, bool)
}

type IServiceRegisterMgr added in v0.2.21

type IServiceRegisterMgr interface {
	Register(info *ServiceInfo) error
	Unregister(serviceType string, serviceId uint16, lineId uint16) error
	UpdateServiceInfo(info *ServiceInfo) error
	FindServiceInfo(serviceType string, serviceId uint16, lineId uint16) (*ServiceInfo, bool)
	FindServiceList(serviceType string) ([]*ServiceInfo, bool)
}

type ISession

type ISession interface {
	GetId() util.ID
	GetConn() IConn                 // get corresponding IConn
	OnOpen(conn IConn)              // called when IConn is opened
	OnClose(conn IConn)             // called when IConn is closed
	OnRecv(conn IConn, data []byte) // called when IConn receives data, ATTENTION: data is a slice and must be consumed immediately
}

ISession connection session interface

type ISessionManager

type ISessionManager interface {
	AddSession(id util.ID, session ISession)
	ResetSession(id util.ID, session ISession)
	RemoveSession(id util.ID)
	GetSession(id util.ID) ISession
	GetSessionCount() int
	Clear()
	Range(f func(id util.ID, session ISession) bool)
}

type ITaskPipeLine added in v0.1.27

type ITaskPipeLine interface {
	Name() string
	SetName(s string)
	Idx() int
	SetIdx(int)
	GetContext() IContext
	SetContext(context IContext)
	GetParent() ITaskPipeLine
	GetPrev() ITaskPipeLine
	GetNext() ITaskPipeLine
	GetSibling(idx int) ITaskPipeLine
	GetChildren() []ITaskPipeLine
	GetChildById(idx int) ITaskPipeLine
	GetChildByName(s string) ITaskPipeLine
	Add(flow ITaskPipeLine) ITaskPipeLine
	Insert(flow ITaskPipeLine, idx int) ITaskPipeLine
	Remove(flow ITaskPipeLine) ITaskPipeLine
	RemoveAt(idx int) ITaskPipeLine
	Execute() *promise.Promise[interface{}]
	SetInput(context IContext)
	GetInput() IContext
	SetExecFunc(f func() (IContext, err error))
}

type ITestCase

type ITestCase interface {
	Test() *promise.Promise[interface{}]
	TestWithContext(ctx IContext) *promise.Promise[interface{}]
	Name() string
	SetName(string)
	GetTestCase(num int) ITestCase
	GetTestCaseByName(name string) ITestCase
	AddTestCase(name string, testCase ITestCase)
	GetLength() int
}

type Key

type Key string

func (Key) Assemble

func (this Key) Assemble(args ...interface{}) string

type LongPacketCreator

type LongPacketCreator func(data []byte, idx int) ([]byte, error)

create long packet args: data:binary to create idx: long packet index return: 1.long packet

type LongPacketPicker

type LongPacketPicker func(data []byte) (bool, int, []byte)

pick long packet from binary args: data:binary return: 1.is long packet 2.long packet index, if index = 0 is the last long packet 3.if is long packet return real packet binary else return nil

type Server

type Server interface {
	Start(addr string) error                     //start server
	Stop()                                       //stop server
	Broadcast(sessionIds []util.ID, data []byte) // broadcast data to all connected sessions
	GetActiveConnNum() int                       // get current count of connections
}

Server the interface for wsserver and tcpserver

type Service

type Service struct {
	Id        protocol.BINARY_TAG //service Id
	ProcessId util.ProcessId      //server Id
	ActorId   util.ID             //actor Id
	Type      ServiceType         //rpc pub/sub stateless
	Host      string
	Port      int
}

Service the registry for service details

type ServiceInfo added in v0.2.21

type ServiceInfo struct {
	// Id          uint32
	ServiceType string
	ServiceId   uint16
	LineId      uint16
	ProcessId   util.ProcessId
	ActorId     util.ID
	// GameId      string
	Host    string
	Port    uint16
	Version string
	Cnt     int
}

type ServiceInfos added in v0.3.6

type ServiceInfos []*ServiceInfo

func (ServiceInfos) Len added in v0.3.6

func (infos ServiceInfos) Len() int

func (ServiceInfos) Less added in v0.3.6

func (infos ServiceInfos) Less(i, j int) bool

func (ServiceInfos) Swap added in v0.3.6

func (infos ServiceInfos) Swap(i, j int)

type ServiceType

type ServiceType int
const (
	//rpc have a actorId<util.Id> to route message
	//SERVICE_RPC ServiceType = iota + 1
	//subscribe have a actorId<util.Id> to pub message
	SERVICE_SUB ServiceType = iota + 1
	//stateless  do not have local state
	SERVICE_STATELESS
	SERVICE_SERVER
)

type UserRouteInfo added in v0.3.6

type UserRouteInfo struct {
	UserId        util.ID
	GateServiceId uint16
	ServiceInfo   *ServiceInfo
}

Directories

Path Synopsis
log
color
Package color adds coloring functionality for TTY output.
Package color adds coloring functionality for TTY output.
lox
tcp
ws
encoding/number_json
Package json implements encoding and decoding of JSON as defined in RFC 7159.
Package json implements encoding and decoding of JSON as defined in RFC 7159.
ini
keys
this is a generate file,do not modify it!
this is a generate file,do not modify it!
zip

Jump to

Keyboard shortcuts

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