realtime

package
v0.0.4 Latest Latest
Warning

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

Go to latest
Published: Oct 24, 2021 License: MIT Imports: 25 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ErrorCodeBadRequest         ErrorCode = 0x0000 // bad request etc.
	ErrorCodeUnauthorized       ErrorCode = 0x0001 // unauthenticated
	ErrorCodeForbidden          ErrorCode = 0x0003 // short permission
	ErrorCodeNotFound           ErrorCode = 0x0004 // undefined request code
	ErrorCodeTooManyRequests    ErrorCode = 0x001d // too many requests
	ErrorCodeConnectionClosed   ErrorCode = 0x007d // connection closed
	ErrorCodeTooManyConnections ErrorCode = 0x007e // too many connections
	ErrorCodeServerStopped      ErrorCode = 0x007f // server stopper

	ErrorCodeRoomCreateError    ErrorCode = 0x0100 // create room error
	ErrorCodeRoomEnterError     ErrorCode = 0x0101 // enter room error
	ErrorCodeRoomExitError      ErrorCode = 0x0102 // exit room error
	ErrorCodeRoomLockError      ErrorCode = 0x0103 // lock room error
	ErrorCodeRoomUnlockError    ErrorCode = 0x0104 // unlock room error
	ErrorCodeRoomAutoMatchError ErrorCode = 0x0110 // auto match error

	ErrorCodeInternal ErrorCode = 0xffff // server internal error

	RequestCodeUserValue   RequestCode = 0x00fe // request code of broadcast user original value
	RequestCodeUserMessage RequestCode = 0x00ff // request code of send user original message

	RequestCodeRoomCreate    RequestCode = 0x0100
	RequestCodeRoomEnter     RequestCode = 0x0101
	RequestCodeRoomExit      RequestCode = 0x0102
	RequestCodeRoomLock      RequestCode = 0x0103
	RequestCodeRoomUnlock    RequestCode = 0x0104
	RequestCodeRoomAutoMatch RequestCode = 0x0110
	RequestCodeRoomBroadcast RequestCode = 0x01ff

	EventCodeUserUpdated       EventCode = 0x8000
	EventCodeUserEnteredRoom   EventCode = 0x8002
	EventCodeUserExitedRoom    EventCode = 0x8003
	EventCodeUserEnteredServer EventCode = 0x8006
	EventCodeUserExitedServer  EventCode = 0x8007
	EventCodeUserEnteredAOIMap EventCode = 0x8010
	EventCodeUserExitedAOIMap  EventCode = 0x8011
	EventCodeUserMovedOnAOIMap EventCode = 0x8012
	EventCodeUserValue         EventCode = 0x80fe
	EventCodeUserMessage       EventCode = 0x80ff

	EventCodeRoomCreated   EventCode = 0x8100
	EventCodeRoomUpdated   EventCode = 0x8101
	EventCodeRoomRemoved   EventCode = 0x8102
	EventCodeRoomLocked    EventCode = 0x8103
	EventCodeRoomUnlocked  EventCode = 0x8104
	EventCodeRoomUserList  EventCode = 0x8105
	EventCodeRoomBroadcast EventCode = 0x81ff

	EventCodeErrorServer EventCode = 0x8ffe
	EventCodeErrorClient EventCode = 0x8fff
)
View Source
const (
	PermissionCodeAuthorized = 1 << (27 - iota)
	PermissionCodeReadonlyAccess
	PermissionCodeNormalAccess
	PermissionCodeIgnoreMaintenance
	PermissionCodeIgnoreEventLimit
	PermissionCodeCustomerSupportTicketAccess
	PermissionCodeSystemMailAccess
	PermissionCodeUserManagementAccess
	PermissionCodeNotificationAccess
	PermissionCodeAdminAccess

	RolePermissionUnauthorized = 0
	RolePermissionAuthorized   = PermissionCodeAuthorized
	RolePermissionNormalUser   = RolePermissionAuthorized | PermissionCodeReadonlyAccess | PermissionCodeNormalAccess
	RolePermissionStaff        = RolePermissionNormalUser | PermissionCodeIgnoreMaintenance | PermissionCodeIgnoreEventLimit
	RolePermissionOperator     = RolePermissionStaff |
		PermissionCodeCustomerSupportTicketAccess |
		PermissionCodeSystemMailAccess |
		PermissionCodeUserManagementAccess |
		PermissionCodeNotificationAccess
	RolePermissionOperatorManager = RolePermissionOperator | PermissionCodeAdminAccess
	RolePermissionProprietor      = 0x7fffffff
)
View Source
const (
	AuthenticationLevelProvider = iota
	AuthenticationLevelDeveloper
	AuthenticationLevelAppManager
	AuthenticationLevelUser
)
View Source
const (
	HeaderV0Original = headerProtocolVer0 | headerCmdOriginal
)

Variables

This section is empty.

Functions

func NewServer

func NewServer(engine engine.Interface, listener Listener, c ServerConfig) (newServer *serverImpl, err error)

func RegisterHandler

func RegisterHandler(id string, h Handler)

RegisterHandler register a realtime.Handler by specified id

func RegisterMiddleware

func RegisterMiddleware(id string, m Middleware)

func RegisterOnConnected

func RegisterOnConnected(id string, h func(conn Connection))

func RegisterOnDisconnected

func RegisterOnDisconnected(id string, h func(conn Connection, errorCode ErrorCode))

func RunHandler

func RunHandler(ctx Ctx, builtinHandler string)

Types

type AreaOfInterestMap

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

AreaOfInterestMap represents area of interest map data structure

func NewAreaOfInterestMap

func NewAreaOfInterestMap(
	server Server,
	mapID uint16,
	sizeX float64, sizeY float64,
	cellNumW uint16, cellNumH uint16) (newMap *AreaOfInterestMap)

NewAreaOfInterestMap creates and returns a new area of interest map

func (*AreaOfInterestMap) Insert

func (m *AreaOfInterestMap) Insert(connID uint16, userID []byte, x float64, y float64)

Insert inserts a user into area of interest map

func (*AreaOfInterestMap) Move

func (m *AreaOfInterestMap) Move(connID uint16, userID []byte, posX float64, posY float64, speed float64)

Move moves a user in the area of interest map

func (*AreaOfInterestMap) OnInsertUser

func (m *AreaOfInterestMap) OnInsertUser(
	fn func(connID uint16, userID []byte, x float64, y float64) (resp Response)) (ret *AreaOfInterestMap)

OnInsertUser sets the callback fn on user inserted into map

func (*AreaOfInterestMap) OnMoveUser

func (m *AreaOfInterestMap) OnMoveUser(
	fn func(connID uint16, userID []byte, x float64, y float64, speed float64) (resp Response)) (ret *AreaOfInterestMap)

OnMoveUser sets the callback fn on user moved on the map

func (*AreaOfInterestMap) OnRemoveUser

func (m *AreaOfInterestMap) OnRemoveUser(fn func(connID uint16, userID []byte) (resp Response)) (ret *AreaOfInterestMap)

OnRemoveUser sets the callback fn on user removed from map

func (*AreaOfInterestMap) Remove

func (m *AreaOfInterestMap) Remove(connID uint16, userID []byte)

Remove removes a user into area of interest map

type Connection

type Connection interface {
	// Server returns the reference of realtime server instance
	Server() (server Server)
	// Close closes the connection with an error
	Close(code ErrorCode, err string)
	// AppID returns the application id of connection
	AppID() []byte
	// UserID returns the user id(hayabusa id) of connection
	UserID() []byte
	// StringUserID returns the string type user id(hayabusa id) of connection
	StringUserID() string
	// Token returns the access token that connection use
	Token() []byte
}

Connection is interface connection implements

type Ctx

type Ctx interface {
	// Request is the received requested packet
	Request
	// Response is the sending response packet
	Response
	// Server returns reference of realtime server
	Server() Server
	// AppID returns using application id
	AppID() []byte
	// UserID returns the id of the request source user
	UserID() []byte
	// Token returns the token of the request source user
	Token() []byte
	// ConnectionID returns the connection id of the request source user
	ConnectionID() uint16
	// Header returns request header
	Header() uint8
	// EventCode returns request event code
	EventCode() uint16
	// Payload returns request payload body
	Payload() []byte
	// OutMessage returns default sending message
	OutMessage() Response
	// Cache returns reference of cache instance
	Cache(cacheID ...string) (plugin *plugins.Cache)
	// Redis returns reference of redis connection
	Redis(instanceID ...string) (plugin *plugins.Redis)
	// CsvTable find and returns csv table under given table name
	CsvTable(tableName string, args ...string) plugins.MasterTable
	// GetConnection find and returns connection by connection id
	GetConnection(ConnectionID uint16) Connection
	// CloseConnection closes the connection in used with error code
	CloseConnection(code ErrorCode, err string)
	// IsInRoom returns true when current user is in a room
	IsInRoom() bool
	// CurrentRoomID returns the current room id
	CurrentRoomID() uint16
	// Send sends packet to specified user
	Send(destConnID uint16, out ...Response) Ctx
	// BroadcastServer broadcasts packet to all online users
	BroadcastServer(out ...Response) Ctx
	// BroadcastApplication broadcasts packet to users in the same application
	BroadcastApplication(out ...Response) Ctx
	// BroadcastRoom broadcasts packet to users in the same room
	BroadcastRoom(out ...Response) Ctx
	// Authorization returns stored user authorization information
	Authorization() interface{}
	// SetAuthorization set and stores user authorization information
	SetAuthorization(authorization interface{}) Ctx
	// ValueTable returns user original parameters table
	ValueTable() CtxValueTable
	// Debug writes debug level log
	Debug(format string, args ...interface{}) Ctx
	// Infof writes info level log
	Infof(format string, args ...interface{}) Ctx
	// Warnf writes warn level log
	Warnf(format string, args ...interface{}) Ctx
	// Assert throws a fatal error if ok is not true
	Assert(ok bool, format string, args ...interface{}) Ctx
	// ErrorClientRequest responses client side error: bad request, unauthorized, forbidden etc.
	ErrorClientRequest(errorCode uint16, format string, args ...interface{})
	// ErrorServerInternal responses server side internal error
	ErrorServerInternal(format string, args ...interface{})
	// Now returns the time when request came
	Now() time.Time
}

Ctx is interface ctx implements

type CtxValueTable

type CtxValueTable interface {
	Set(key int, value interface{}) CtxValueTable
	GetInt(key int, def ...int) int
	GetUint(key int, def ...uint) uint
	GetInt16(key int, def ...int16) int16
	GetUint16(key int, def ...uint16) uint16
	GetByte(key int, def ...byte) byte
	GetBool(key int, def ...bool) bool
	GetFloat32(key int, def ...float32) float32
	GetFloat64(key int, def ...float64) float64
	GetBytes(key int) []byte
	GetString(key int, def ...string) string
}

CtxValueTable is interface ctxValueTable implements

type ErrorCode

type ErrorCode = uint16

type EventCode

type EventCode = uint16

type Handler

type Handler func(ctx Ctx)

Handler is function type for processing socket requests

func (Handler) Combine

func (h Handler) Combine(next ...Handler) Handler

Combine returns a new Handler that processes multiple businesses in sequence

type KcpConfig

type KcpConfig struct {
	Mtu        int `yaml:"mtu" default:"736"`
	SndWnd     int `yaml:"snd_wnd" default:"128"`
	RcvWnd     int `yaml:"rcv_wnd" default:"128"`
	TurboLevel int `yaml:"turbo_level" default:"-1"`
	// if TurboLevel is filled in, the following configuration will be ignored
	NoDelay  bool          `yaml:"no_delay" default:"false"`
	Interval time.Duration `yaml:"interval" default:"25ms"`
	Resend   int           `yaml:"resend" default:"2"`
	Nc       bool          `yaml:"nc" default:"false"`
}

type KcpListener

type KcpListener struct {
	*kcp.Listener
	Config *ServerConfig
}

func (*KcpListener) Accept

func (l *KcpListener) Accept(context.Context) (connectionInterface, error)

type Listener

type Listener interface {
	Close() error
	Addr() net.Addr
	Accept(context.Context) (connectionInterface, error)
}

type Middleware

type Middleware func(h Handler) Handler

Middleware is function type which receives a RealtimeHandler and returns a new RealtimeHandler type closure included middleware logic

func (Middleware) Apply

func (m Middleware) Apply(h Handler) Handler

Apply returns a new RealtimeHandler included middleware logic

func (Middleware) Left

func (m Middleware) Left(inner Middleware) Middleware

Left returns a new RealtimeMiddleware first including process logic in m, and then includes inner

func (Middleware) Right

func (m Middleware) Right(outer Middleware) Middleware

Right returns a new RealtimeMiddleware first including process logic in outer, and then includes m

type PermissionCode

type PermissionCode = int32

type QuicConfig

type QuicConfig struct {
}

type QuicListener

type QuicListener struct {
	quic.Listener
}

func (*QuicListener) Accept

func (l *QuicListener) Accept(ctx context.Context) (connectionInterface, error)

type Request

type Request interface {
	ReadBool(val *bool) Request
	ReadInt8(val *int8) Request
	ReadUint8(val *uint8) Request
	ReadInt16(val *int16) Request
	ReadUint16(val *uint16) Request
	ReadInt32(val *int32) Request
	ReadUint32(val *uint32) Request
	ReadInt64(val *int64) Request
	ReadUint64(val *uint64) Request
	ReadFloat32(val *float32) Request
	ReadFloat64(val *float64) Request
	ReadBytes() []byte
	ReadString() string
	Payload() []byte
}

Request is interface that received binary data packet implements

type RequestCode

type RequestCode = uint16

type Response

type Response interface {
	WriteBool(val bool) Response
	WriteInt8(val int8) Response
	WriteUint8(val uint8) Response
	WriteInt16(val int16) Response
	WriteUint16(val uint16) Response
	WriteInt32(val int32) Response
	WriteUint32(val uint32) Response
	WriteInt64(val int64) Response
	WriteUint64(val uint64) Response
	WriteFloat32(val float32) Response
	WriteFloat64(val float64) Response
	WriteBytes(val []byte) Response
	WriteString(val string) Response
	WriteBytesNoLen(val []byte) Response

	WriteRoom(roomID uint16) Response
	WriteUserStatus(connectionID uint16) Response
	SetHeader(header uint8) Response
	SetHeader2(protocolVer, cmd uint8) Response
	SetEventCode(code uint16) Response
	Reset() Response
}

Response is interface that sending binary data packet implements

type RoomStatus

type RoomStatus struct {
	ID            uint16
	RoomType      uint8
	Status        uint8
	CreatedAt     time.Time
	UntilAt       time.Time
	UserNum       uint16
	ScoreCenter   float32
	ScoreVariance float32
	Mux           []byte
}

type Server

type Server interface {
	// Redis returns reference of specified redis connection
	Redis(instanceID string) (plugin *plugins.Redis)
	// Cache returns reference of specified cache instance
	Cache(cacheID string) (plugin *plugins.Cache)
	// SendMessage sends packet to a specified connection
	SendMessage(connID uint16, out Response)
	// SendMessageMultiple sends packet to multiple connections
	SendMessageMultiple(connectionIDList []uint16, out Response)
	// BroadcastMessageRoom broadcasts packet to specified room
	BroadcastMessageRoom(roomID uint16, out Response)
	// BroadcastMessageApplication broadcasts packet to specified application
	BroadcastMessageApplication(appID []byte, out Response)
	// BroadcastMessageServer broadcasts packet to all online connections
	BroadcastMessageServer(out Response)
	// ConnectionNum returns connection num
	ConnectionNum() int
	// CreateRoom creates new room and returns id
	CreateRoom() (roomID uint16, ok bool)
	// DestroyRoom destroys specified room
	DestroyRoom(roomID uint16)
	// RoomEnterUser lets specified user do enter specified room
	RoomEnterUser(roomID uint16, connectionID uint16) (ok bool)
	// RoomExitUser lets specified user do exit specified room
	RoomExitUser(roomID uint16, connectionID uint16) (ok bool)
	// RoomUserNum returns number of useserver in the specified room
	RoomUserNum(roomID uint16) int
	// RoomUserList returns user list in the room
	RoomUserList(roomID uint16) (list [][]byte)
	// RoomStatus returns room status information
	RoomStatus(roomID uint16) *RoomStatus
	// RoomSetMatch sets auto matching parameters
	// mux is a multiplexer id that avoids data interference
	// scoreCenter, scoreVariance is for builtin matching algorithm
	RoomSetMatch(roomID uint16, mux []byte, scoreCenter float32, scoreVariance float32)
	// RoomSetUserNum sets min/max user num
	RoomSetUserNum(roomID uint16, num uint16)
	// Now returns the time when request came at
	Now() time.Time
}

Server is interface server implements

type ServerConfig

type ServerConfig struct {
	ID                   string        `yaml:"id" required:"true"`
	Network              string        `yaml:"network" default:"udp"`
	Address              string        `yaml:"address" default:"localhost:8443"`
	ByteOrder            string        `yaml:"byte_order" default:"big"`
	CertFile             string        `yaml:"cert_file" default:"cert.pem"`
	KeyFile              string        `yaml:"key_file" default:"key.pem"`
	Password             string        `yaml:"password" default:""`
	Salt                 string        `yaml:"salt" default:""`
	WriteTimeout         time.Duration `yaml:"write_timeout" default:"200ms"`
	ReadTimeout          time.Duration `yaml:"read_timeout" default:"10s"`
	Heartbeat            time.Duration `yaml:"heartbeat" default:"5s"`
	Protocol             string        `yaml:"protocol" default:"kcp"`
	KcpConfig            `yaml:"kcp"`
	QuicConfig           `yaml:"quic"`
	ControllerFilepath   string `yaml:"controller_filepath" required:"true"`
	plugins.LoggerConfig `yaml:"log"`
}

Jump to

Keyboard shortcuts

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