server

package
v2.0.0-...-32867ca Latest Latest
Warning

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

Go to latest
Published: Jun 21, 2024 License: MIT Imports: 64 Imported by: 0

Documentation

Overview

Copyright 2024 The Bombus Authors

Use of this source code is governed by a MIT style license that can be found in the LICENSE file.

Index

Constants

View Source
const (
	PeerMsg_NOTIFY = iota
	PeerMsg_REMOTESTATE
	PeerMsg_REMOTESTATEJOIN
)
View Source
const (
	StreamMode_NOTIFICATIONS uint8 = iota
	StreamMode_STATUS
	StreamMode_CHANNEL
	StreamMode_GROUP
)

Variables

View Source
var (
	ErrSessionTokenInvalid = errors.New("session token invalid")
	ErrRefreshTokenInvalid = errors.New("refresh token invalid")
)
View Source
var ErrSessionQueueFull = errors.New("session outgoing queue full")

Functions

func AuthenticateApple

func AuthenticateApple(ctx context.Context, logger *zap.Logger, db *gorm.DB, client *social.Client, bundleId, token, username string, create bool) (string, string, bool, error)

func AuthenticateCustom

func AuthenticateCustom(ctx context.Context, logger *zap.Logger, db *gorm.DB, customID, username string, create bool) (string, string, bool, error)

func AuthenticateDevice

func AuthenticateDevice(ctx context.Context, logger *zap.Logger, db *gorm.DB, deviceID, username string, create bool) (string, string, bool, error)

func AuthenticateEmail

func AuthenticateEmail(ctx context.Context, logger *zap.Logger, db *gorm.DB, email, password, username string, create bool) (string, string, bool, error)

func AuthenticateFacebook

func AuthenticateFacebook(ctx context.Context, logger *zap.Logger, db *gorm.DB, client *social.Client, appId, accessToken, username string, create bool) (string, string, bool, bool, error)

func AuthenticateUsername

func AuthenticateUsername(ctx context.Context, logger *zap.Logger, db *gorm.DB, username, password string, create bool) (string, bool, error)

func HashFromId

func HashFromId(id uuid.UUID) [6]byte

func NewConfig

func NewConfig(log *zap.Logger) *config

NewConfig constructs a Config struct which represents server settings, and populates it with default values.

func NewSocketWsAcceptor

func NewSocketWsAcceptor(runtime Runtime) func(c *gin.Context)

func NodeToHash

func NodeToHash(node string) [6]byte

func SessionLogout

func SessionLogout(config Config, sessionBan SessionBan, userID uuid.UUID, token, refreshToken string) error

func SessionRefresh

func SessionRefresh(ctx context.Context, logger *zap.Logger, db *gorm.DB, config Config, sessionBan SessionBan, token string) (uuid.UUID, string, map[string]string, string, error)

Types

type ApiServer

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

func StartApiServer

func StartApiServer(runtime Runtime) *ApiServer

func (*ApiServer) AbortContextError

func (s *ApiServer) AbortContextError(ctx *gin.Context, statusCode int, err error, md map[string]string)

func (*ApiServer) AbortError

func (s *ApiServer) AbortError(ctx *gin.Context, err error)

func (*ApiServer) AbortMessageError

func (s *ApiServer) AbortMessageError(ctx *gin.Context, err error, message string)

func (*ApiServer) AbortStatusError

func (s *ApiServer) AbortStatusError(ctx *gin.Context, statusCode int, err error)

func (*ApiServer) AuthenticateApple

func (s *ApiServer) AuthenticateApple(ctx *gin.Context)

func (*ApiServer) AuthenticateCustom

func (s *ApiServer) AuthenticateCustom(ctx *gin.Context)

func (*ApiServer) AuthenticateDevice

func (s *ApiServer) AuthenticateDevice(ctx *gin.Context)

func (*ApiServer) AuthenticateEmail

func (s *ApiServer) AuthenticateEmail(ctx *gin.Context)

func (*ApiServer) AuthenticateFacebook

func (s *ApiServer) AuthenticateFacebook(ctx *gin.Context)

func (*ApiServer) BindProtoJSON

func (s *ApiServer) BindProtoJSON(ctx *gin.Context, o proto.Message) error

func (*ApiServer) GetSessionExpiry

func (s *ApiServer) GetSessionExpiry(ctx *gin.Context) int64

func (*ApiServer) GetSessionToken

func (s *ApiServer) GetSessionToken(ctx *gin.Context) string

func (*ApiServer) GetSessionUserID

func (s *ApiServer) GetSessionUserID(ctx *gin.Context) (uuid.UUID, bool)

func (*ApiServer) GetSessionUsername

func (s *ApiServer) GetSessionUsername(ctx *gin.Context) string

func (*ApiServer) GetSessionVars

func (s *ApiServer) GetSessionVars(ctx *gin.Context) map[string]string

func (*ApiServer) ProtoJSON

func (s *ApiServer) ProtoJSON(ctx *gin.Context, data proto.Message)

func (*ApiServer) ProtoJSONWithStatus

func (s *ApiServer) ProtoJSONWithStatus(ctx *gin.Context, code int, data proto.Message)

func (*ApiServer) Rpc

func (s *ApiServer) Rpc(ctx *gin.Context)

func (*ApiServer) SessionLogout

func (s *ApiServer) SessionLogout(ctx *gin.Context)

func (*ApiServer) SessionRefresh

func (s *ApiServer) SessionRefresh(ctx *gin.Context)

func (*ApiServer) Stop

func (s *ApiServer) Stop()

type BinaryLog

type BinaryLog interface {
	Push(log *pb.Bombus_Peer_BinaryLog) bool
	NextID() uint64
	CurrentID() uint64
	GetBroadcasts(limit int) []*pb.Bombus_Peer_BinaryLog
	GetCheckPoint() *pb.Bombus_Peer_CheckPoint
	MergeCheckPoint(checkPoint *pb.Bombus_Peer_CheckPoint, join bool)
	SetLocalCheckPoint(name string, version uint64)
	ClearBinaryLogByNode(node string)
	GetBinaryLogVersionByNode(node string) (min, max uint64)
	GetBinaryLogVersions() map[string][2]uint64
	Len() int
	Stop()
}

func NewLocalBinaryLog

func NewLocalBinaryLog(ctx context.Context, logger *zap.Logger, node string, numMembers func() int) BinaryLog

type Config

type Config interface {
	GetName() string
	GetDataDir() string
	GetShutdownGraceSec() int
	GetLogger() *logger.Configuration
	GetSession() *SessionConfig
	GetSocket() *SocketConfig
	GetDatabase() *postgres.Config
	GetConsole() *ConsoleConfig
	GetRedis() *redis.Config
	GetMetrics() *MetricsConfig
	GetTracker() *TrackerConfig
	GetRuntime() *RuntimeConfig
	GetCluster() *PeerConfig
	GetSocial() *SocialConfig
	GetGoogleAuth() *GoogleAuthConfig
	Clone() Config
}

func ParseArgs

func ParseArgs(logger *zap.Logger, args []string) Config

type ConsoleConfig

type ConsoleConfig struct {
	Port                int    `yaml:"port" json:"port" usage:"The port for accepting connections for the embedded console, listening on all interfaces."`
	Address             string `` /* 157-byte string literal not displayed */
	MaxMessageSizeBytes int64  `` /* 154-byte string literal not displayed */
	ReadTimeoutMs       int    `yaml:"read_timeout_ms" json:"read_timeout_ms" usage:"Maximum duration in milliseconds for reading the entire request."`
	WriteTimeoutMs      int    `` /* 130-byte string literal not displayed */
	IdleTimeoutMs       int    `` /* 151-byte string literal not displayed */
	Username            string `yaml:"username" json:"username" usage:"Username for the embedded console. Default username is 'admin'."`
	Password            string `yaml:"password" json:"password" usage:"Password for the embedded console. Default password is 'password'."`
	TokenExpirySec      int64  `yaml:"token_expiry_sec" json:"token_expiry_sec" usage:"Token expiry in seconds. Default 86400."`
	SigningKey          string `yaml:"signing_key" json:"signing_key" usage:"Key used to sign console session tokens."`
}

ConsoleConfig is configuration relevant to the embedded console.

func NewConsoleConfig

func NewConsoleConfig() *ConsoleConfig

type DeferredMessage

type DeferredMessage struct {
	PresenceIDs []*PresenceID
	Envelope    *pb.Bombus_ResponseWriter
	Reliable    bool
}

Deferred message expected to be batched with other deferred messages. All deferred messages in a batch are expected to be for the same stream/mode and share a logger context.

type Endpoint

type Endpoint interface {
	Name() string
	Weight(v ...int32) int32
	Balancer(v ...int32) int32
	Status(v ...int32) int32
	PingRTT(v ...time.Duration) time.Duration
	Metadata() map[string]string
	GetMetadata(k string) string
	SetMetadata(k, v string)
	ResetMetadata(md map[string]string)
	DeleteMetadata(deleteKey string)
	PingCompleted(rtt time.Duration)
	BindMemberlistNode(node *memberlist.Node)
	MemberlistNode() *memberlist.Node
	SessionCount() int32
	PresenceCount() int32
	MatchCount() int32
	GoroutineCount() int32
	AvgLatencyMs() float64
	AvgRateSec() float64
	AvgInputKbs() float64
	AvgOutputKbs() float64
	MergeStateAt() int64
	UpdateState(status *pb.Bombus_Peer_Status)
	MarshalJSON() ([]byte, error)
	MarshalProtoBuffer() ([]byte, error)
}

func NewPeerEndpont

func NewPeerEndpont(name string, md map[string]string, status, weight, balancer int32, node ...*memberlist.Node) Endpoint

type GoogleAuthConfig

type GoogleAuthConfig struct {
	CredentialsJSON string         `yaml:"credentials_json" json:"credentials_json" usage:"Google's Access Credentials."`
	OAuthConfig     *oauth2.Config `yaml:"-" json:"-"`
}

func NewGoogleAuthConfig

func NewGoogleAuthConfig() *GoogleAuthConfig

type LocalBinaryLog

type LocalBinaryLog struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

func (*LocalBinaryLog) ClearBinaryLogByNode

func (b *LocalBinaryLog) ClearBinaryLogByNode(node string)

func (*LocalBinaryLog) CurrentID

func (b *LocalBinaryLog) CurrentID() uint64

func (*LocalBinaryLog) GetBinaryLogVersionByNode

func (b *LocalBinaryLog) GetBinaryLogVersionByNode(node string) (min, max uint64)

func (*LocalBinaryLog) GetBinaryLogVersions

func (b *LocalBinaryLog) GetBinaryLogVersions() map[string][2]uint64

func (*LocalBinaryLog) GetBroadcasts

func (b *LocalBinaryLog) GetBroadcasts(limit int) []*pb.Bombus_Peer_BinaryLog

func (*LocalBinaryLog) GetCheckPoint

func (b *LocalBinaryLog) GetCheckPoint() *pb.Bombus_Peer_CheckPoint

func (*LocalBinaryLog) Len

func (b *LocalBinaryLog) Len() int

func (*LocalBinaryLog) MergeCheckPoint

func (b *LocalBinaryLog) MergeCheckPoint(checkPoint *pb.Bombus_Peer_CheckPoint, join bool)

func (*LocalBinaryLog) NextID

func (b *LocalBinaryLog) NextID() uint64

func (*LocalBinaryLog) Push

func (*LocalBinaryLog) SetLocalCheckPoint

func (b *LocalBinaryLog) SetLocalCheckPoint(name string, version uint64)

func (*LocalBinaryLog) Stop

func (b *LocalBinaryLog) Stop()

type LocalMessageRouter

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

func (*LocalMessageRouter) SendDeferred

func (r *LocalMessageRouter) SendDeferred(logger *zap.Logger, messages []*DeferredMessage)

func (*LocalMessageRouter) SendToAll

func (r *LocalMessageRouter) SendToAll(logger *zap.Logger, envelope *pb.Bombus_ResponseWriter, reliable bool)

func (*LocalMessageRouter) SendToPresenceIDs

func (r *LocalMessageRouter) SendToPresenceIDs(logger *zap.Logger, presenceIDs []*PresenceID, envelope *pb.Bombus_ResponseWriter, reliable bool)

func (*LocalMessageRouter) SendToStream

func (r *LocalMessageRouter) SendToStream(logger *zap.Logger, stream PresenceStream, envelope *pb.Bombus_ResponseWriter, reliable bool)

func (*LocalMessageRouter) SetPeer

func (r *LocalMessageRouter) SetPeer(peer Peer)

type LocalMetrics

type LocalMetrics struct {
	PrometheusScope tally.Scope
	// contains filtered or unexported fields
}

func (*LocalMetrics) Api

func (m *LocalMetrics) Api(name string, elapsed time.Duration, recvBytes, sentBytes int64, isErr bool)

func (*LocalMetrics) ApiRpc

func (m *LocalMetrics) ApiRpc(id string, elapsed time.Duration, recvBytes, sentBytes int64, isErr bool)

func (*LocalMetrics) CountWebsocketClosed

func (m *LocalMetrics) CountWebsocketClosed(delta int64)

Increment the number of closed WS connections.

func (*LocalMetrics) CountWebsocketOpened

func (m *LocalMetrics) CountWebsocketOpened(delta int64)

Increment the number of opened WS connections.

func (*LocalMetrics) GaugePeers

func (m *LocalMetrics) GaugePeers(value float64)

Set the absolute value of currently peer members.

func (*LocalMetrics) GaugePresences

func (m *LocalMetrics) GaugePresences(value float64)

Set the absolute value of currently tracked presences.

func (*LocalMetrics) GaugeSessions

func (m *LocalMetrics) GaugeSessions(value float64)

Set the absolute value of currently active sessions.

func (*LocalMetrics) Message

func (m *LocalMetrics) Message(recvBytes int64, isErr bool)

func (*LocalMetrics) MessageBytesSent

func (m *LocalMetrics) MessageBytesSent(sentBytes int64)

func (*LocalMetrics) PeerRecv

func (m *LocalMetrics) PeerRecv(recvBytes int64)

func (*LocalMetrics) PeerSent

func (m *LocalMetrics) PeerSent(sentBytes int64)

func (*LocalMetrics) PresenceEvent

func (m *LocalMetrics) PresenceEvent(dequeueElapsed, processElapsed time.Duration)

Count presence events and time their processing.

func (*LocalMetrics) SnapshotLatencyMs

func (m *LocalMetrics) SnapshotLatencyMs() float64

func (*LocalMetrics) SnapshotRateSec

func (m *LocalMetrics) SnapshotRateSec() float64

func (*LocalMetrics) SnapshotRecvKbSec

func (m *LocalMetrics) SnapshotRecvKbSec() float64

func (*LocalMetrics) SnapshotSentKbSec

func (m *LocalMetrics) SnapshotSentKbSec() float64

func (*LocalMetrics) Stop

func (m *LocalMetrics) Stop(logger *zap.Logger)

type LocalPeer

type LocalPeer struct {
	sync.Mutex
	// contains filtered or unexported fields
}

func (*LocalPeer) AckPayload

func (s *LocalPeer) AckPayload() []byte

AckPayload is invoked when an ack is being sent; the returned bytes will be appended to the ack

func (*LocalPeer) Broadcast

func (s *LocalPeer) Broadcast(msg *pb.Bombus_Request, reliable bool)

func (*LocalPeer) BroadcastBinaryLog

func (s *LocalPeer) BroadcastBinaryLog(b *pb.Bombus_Peer_BinaryLog)

func (*LocalPeer) GetBroadcasts

func (s *LocalPeer) GetBroadcasts(overhead, limit int) [][]byte

GetBroadcasts is called when user data messages can be broadcast. It can return a list of buffers to send. Each buffer should assume an overhead as provided with a limit on the total byte size allowed. The total byte size of the resulting data to send must not exceed the limit. Care should be taken that this method does not block, since doing so would block the entire UDP packet receive loop.

func (*LocalPeer) GetServiceRegistry

func (s *LocalPeer) GetServiceRegistry() kit.ServiceRegistry

func (*LocalPeer) Join

func (s *LocalPeer) Join(members ...string) (int, error)

func (*LocalPeer) Local

func (s *LocalPeer) Local() Endpoint

func (*LocalPeer) LocalState

func (s *LocalPeer) LocalState(join bool) []byte

LocalState is used for a TCP Push/Pull. This is sent to the remote side in addition to the membership information. ALogger data can be sent here. See MergeRemoteState as well. The `join` boolean indicates this is for a join instead of a push/pull.

func (*LocalPeer) Member

func (s *LocalPeer) Member(name string) (Endpoint, bool)

func (*LocalPeer) MergeRemoteState

func (s *LocalPeer) MergeRemoteState(buf []byte, join bool)

MergeRemoteState is invoked after a TCP Push/Pull. This is the state received from the remote side and is the result of the remote side's LocalState call. The 'join' boolean indicates this is for a join instead of a push/pull.

func (*LocalPeer) NodeMeta

func (s *LocalPeer) NodeMeta(limit int) []byte

when broadcasting an alive message. It's length is limited to the given byte size. This metadata is available in the Node structure.

func (*LocalPeer) NotifyAlive

func (s *LocalPeer) NotifyAlive(node *memberlist.Node) error

NotifyAlive implements the memberlist.AliveDelegate interface.

func (*LocalPeer) NotifyConflict

func (s *LocalPeer) NotifyConflict(existing, other *memberlist.Node)

NotifyConflict is invoked when a name conflict is detected

func (*LocalPeer) NotifyJoin

func (s *LocalPeer) NotifyJoin(node *memberlist.Node)

NotifyJoin is invoked when a node is detected to have joined. The Node argument must not be modified.

func (*LocalPeer) NotifyLeave

func (s *LocalPeer) NotifyLeave(node *memberlist.Node)

NotifyLeave is invoked when a node is detected to have left. The Node argument must not be modified.

func (*LocalPeer) NotifyMerge

func (s *LocalPeer) NotifyMerge(peers []*memberlist.Node) error

NotifyMerge is invoked when a merge could take place. Provides a list of the nodes known by the peer. If the return value is non-nil, the merge is canceled.

func (*LocalPeer) NotifyMsg

func (s *LocalPeer) NotifyMsg(msg []byte)

NotifyMsg is called when a user-data message is received. Care should be taken that this method does not block, since doing so would block the entire UDP packet receive loop. Additionally, the byte slice may be modified after the call returns, so it should be copied if needed

func (*LocalPeer) NotifyPingComplete

func (s *LocalPeer) NotifyPingComplete(other *memberlist.Node, rtt time.Duration, payload []byte)

NotifyPing is invoked when an ack for a ping is received

func (*LocalPeer) NotifyUpdate

func (s *LocalPeer) NotifyUpdate(node *memberlist.Node)

NotifyUpdate is invoked when a node is detected to have updated, usually involving the meta data. The Node argument must not be modified.

func (*LocalPeer) NumMembers

func (s *LocalPeer) NumMembers() int

func (*LocalPeer) Request

func (s *LocalPeer) Request(ctx context.Context, endpoint Endpoint, msg *pb.Bombus_Request) (*pb.Bombus_ResponseWriter, error)

func (*LocalPeer) Send

func (s *LocalPeer) Send(endpoint Endpoint, msg *pb.Bombus_Request, reliable bool) error

func (*LocalPeer) Shutdown

func (s *LocalPeer) Shutdown()

func (*LocalPeer) Version

func (s *LocalPeer) Version() (map[string][2]uint64, int)

type LocalRpcRegistry

type LocalRpcRegistry struct {
	sync.Mutex
	// contains filtered or unexported fields
}

func (*LocalRpcRegistry) Deregister

func (r *LocalRpcRegistry) Deregister(id string)

func (*LocalRpcRegistry) Get

func (r *LocalRpcRegistry) Get(id string) (RpcHandle, bool)

func (*LocalRpcRegistry) Init

func (r *LocalRpcRegistry) Init() RpcRegistry

func (*LocalRpcRegistry) Register

func (r *LocalRpcRegistry) Register(id string, handle RpcHandle, routes ...*RpcRoute)

func (*LocalRpcRegistry) Reset

func (r *LocalRpcRegistry) Reset()

type LocalRuntime

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

func (*LocalRuntime) Context

func (r *LocalRuntime) Context() context.Context

func (*LocalRuntime) DB

func (r *LocalRuntime) DB() *gorm.DB

func (*LocalRuntime) GetConfig

func (r *LocalRuntime) GetConfig() Config

func (*LocalRuntime) GetConsoleLogger

func (r *LocalRuntime) GetConsoleLogger() *zap.Logger

func (*LocalRuntime) GetLogger

func (r *LocalRuntime) GetLogger() *zap.Logger

func (*LocalRuntime) GetMessageRouter

func (r *LocalRuntime) GetMessageRouter() MessageRouter

func (*LocalRuntime) GetMetrics

func (r *LocalRuntime) GetMetrics() Metrics

func (*LocalRuntime) GetPeer

func (r *LocalRuntime) GetPeer() Peer

func (*LocalRuntime) GetRpcRegistry

func (r *LocalRuntime) GetRpcRegistry() RpcRegistry

func (*LocalRuntime) GetSessionBan

func (r *LocalRuntime) GetSessionBan() SessionBan

func (*LocalRuntime) GetSessionRegistry

func (r *LocalRuntime) GetSessionRegistry() SessionRegistry

func (*LocalRuntime) GetSocialClient

func (r *LocalRuntime) GetSocialClient() *social.Client

func (*LocalRuntime) GetTracker

func (r *LocalRuntime) GetTracker() Tracker

func (*LocalRuntime) GetWorker

func (r *LocalRuntime) GetWorker() *worker.WorkerPool

func (*LocalRuntime) Shutdown

func (r *LocalRuntime) Shutdown()

type LocalSessionBan

type LocalSessionBan struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

func (*LocalSessionBan) Add

func (s *LocalSessionBan) Add(userID uuid.UUID, sessionExp int64, tokenId string, refreshExp int64, refreshTokenId string)

func (*LocalSessionBan) Ban

func (s *LocalSessionBan) Ban(userIDs []uuid.UUID)

func (*LocalSessionBan) IsValidRefresh

func (s *LocalSessionBan) IsValidRefresh(userID uuid.UUID, exp int64, tokenId string) bool

func (*LocalSessionBan) IsValidSession

func (s *LocalSessionBan) IsValidSession(userID uuid.UUID, exp int64, tokenId string) bool

func (*LocalSessionBan) Remove

func (s *LocalSessionBan) Remove(userID uuid.UUID, sessionExp int64, sessionTokenId string, refreshExp int64, refreshTokenId string)

func (*LocalSessionBan) RemoveAll

func (s *LocalSessionBan) RemoveAll(userID uuid.UUID)

func (*LocalSessionBan) Stop

func (s *LocalSessionBan) Stop()

func (*LocalSessionBan) Unban

func (s *LocalSessionBan) Unban(userIDs []uuid.UUID)

type LocalSessionRegistry

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

func (*LocalSessionRegistry) Add

func (r *LocalSessionRegistry) Add(session Session)

func (*LocalSessionRegistry) Count

func (r *LocalSessionRegistry) Count() int

func (*LocalSessionRegistry) Disconnect

func (r *LocalSessionRegistry) Disconnect(ctx context.Context, sessionID uuid.UUID, ban bool, reason ...PresenceReason) error

func (*LocalSessionRegistry) Get

func (r *LocalSessionRegistry) Get(sessionID uuid.UUID) Session

func (*LocalSessionRegistry) Range

func (r *LocalSessionRegistry) Range(fn func(Session) bool)

func (*LocalSessionRegistry) Remove

func (r *LocalSessionRegistry) Remove(sessionID uuid.UUID)

func (*LocalSessionRegistry) SingleSession

func (r *LocalSessionRegistry) SingleSession(ctx context.Context, tracker Tracker, userID, sessionID uuid.UUID)

func (*LocalSessionRegistry) Stop

func (r *LocalSessionRegistry) Stop()

type LocalTracker

type LocalTracker struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

func (*LocalTracker) ClearRemoteTrack

func (t *LocalTracker) ClearRemoteTrack()

func (*LocalTracker) ClearTrackByNode

func (t *LocalTracker) ClearTrackByNode(node string)

func (*LocalTracker) Count

func (t *LocalTracker) Count() int

func (*LocalTracker) CountByStream

func (t *LocalTracker) CountByStream(stream PresenceStream) int

func (*LocalTracker) CountByStreamModeFilter

func (t *LocalTracker) CountByStreamModeFilter(modes map[uint8]*uint8) map[*PresenceStream]int32

func (*LocalTracker) GetBySessionIDStreamUserID

func (t *LocalTracker) GetBySessionIDStreamUserID(node string, sessionID uuid.UUID, stream PresenceStream, userID uuid.UUID) *PresenceMeta

func (*LocalTracker) GetLocalBySessionIDStreamUserID

func (t *LocalTracker) GetLocalBySessionIDStreamUserID(sessionID uuid.UUID, stream PresenceStream, userID uuid.UUID) *PresenceMeta

func (*LocalTracker) ListByStream

func (t *LocalTracker) ListByStream(stream PresenceStream, includeHidden bool, includeNotHidden bool) []*Presence

func (*LocalTracker) ListLocalPresenceIDByStream

func (t *LocalTracker) ListLocalPresenceIDByStream(stream PresenceStream) []*PresenceID

func (*LocalTracker) ListLocalSessionIDByStream

func (t *LocalTracker) ListLocalSessionIDByStream(stream PresenceStream) []uuid.UUID

func (*LocalTracker) ListNodesForStream

func (t *LocalTracker) ListNodesForStream(stream PresenceStream) map[string]struct{}

func (*LocalTracker) ListPresenceIDByStream

func (t *LocalTracker) ListPresenceIDByStream(stream PresenceStream) []*PresenceID

func (*LocalTracker) ListPresenceIDByStreams

func (t *LocalTracker) ListPresenceIDByStreams(fill map[PresenceStream][]*PresenceID)

func (*LocalTracker) MergeRemoteState

func (t *LocalTracker) MergeRemoteState(fromNode string, presences []*pb.Bombus_Peer_Presence, join bool)

func (*LocalTracker) Range

func (t *LocalTracker) Range(fn func(sessionID uuid.UUID, presences []*Presence) bool)

func (*LocalTracker) SetPeer

func (t *LocalTracker) SetPeer(peer Peer)

func (*LocalTracker) Stop

func (t *LocalTracker) Stop()

func (*LocalTracker) StreamExists

func (t *LocalTracker) StreamExists(stream PresenceStream) bool

func (*LocalTracker) Track

func (t *LocalTracker) Track(ctx context.Context, sessionID uuid.UUID, stream PresenceStream, userID uuid.UUID, meta PresenceMeta, allowIfFirstForSession bool, nodeValue ...string) (bool, bool)

func (*LocalTracker) TrackMulti

func (t *LocalTracker) TrackMulti(ctx context.Context, sessionID uuid.UUID, ops []*TrackerOp, userID uuid.UUID, allowIfFirstForSession bool, nodeValue ...string) bool

func (*LocalTracker) TrackPeer

func (t *LocalTracker) TrackPeer(sessionID uuid.UUID, userID uuid.UUID, ops []*TrackerOp)

func (*LocalTracker) Untrack

func (t *LocalTracker) Untrack(sessionID uuid.UUID, stream PresenceStream, userID uuid.UUID, nodeValue ...string)

func (*LocalTracker) UntrackAll

func (t *LocalTracker) UntrackAll(sessionID uuid.UUID, reason PresenceReason, nodeValue ...string)

func (*LocalTracker) UntrackByModes

func (t *LocalTracker) UntrackByModes(sessionID uuid.UUID, modes map[uint8]struct{}, skipStream PresenceStream)

func (*LocalTracker) UntrackByStream

func (t *LocalTracker) UntrackByStream(stream PresenceStream)

func (*LocalTracker) UntrackLocalByModes

func (t *LocalTracker) UntrackLocalByModes(sessionID uuid.UUID, modes map[uint8]struct{}, skipStream PresenceStream)

func (*LocalTracker) UntrackLocalByStream

func (t *LocalTracker) UntrackLocalByStream(stream PresenceStream)

func (*LocalTracker) UntrackMulti

func (t *LocalTracker) UntrackMulti(sessionID uuid.UUID, streams []*PresenceStream, userID uuid.UUID, nodeValue ...string)

func (*LocalTracker) UntrackPeer

func (t *LocalTracker) UntrackPeer(sessionID uuid.UUID, userID uuid.UUID, streams []*PresenceStream, modes []uint32, reason PresenceReason, skipStream *PresenceStream)

func (*LocalTracker) Update

func (t *LocalTracker) Update(ctx context.Context, sessionID uuid.UUID, stream PresenceStream, userID uuid.UUID, meta PresenceMeta, allowIfFirstForSession bool, nodeValue ...string) bool

func (*LocalTracker) UpdateTrackPeer

func (t *LocalTracker) UpdateTrackPeer(sessionID uuid.UUID, userID uuid.UUID, ops []*TrackerOp)

type MapOf

type MapOf[K comparable, V any] struct {
	// contains filtered or unexported fields
}

MapOf is like a Go map[interface{}]interface{} but is safe for concurrent use by multiple goroutines without additional locking or coordination. Loads, stores, and deletes run in amortized constant time.

The MapOf type is specialized. Most code should use a plain Go map instead, with separate locking or coordination, for better type safety and to make it easier to maintain other invariants along with the map content.

The MapOf type is optimized for two common use cases: (1) when the entry for a given key is only ever written once but read many times, as in caches that only grow, or (2) when multiple goroutines read, write, and overwrite entries for disjoint sets of keys. In these two cases, use of a MapOf may significantly reduce lock contention compared to a Go map paired with a separate Mutex or RWMutex.

The zero MapOf is empty and ready for use. A MapOf must not be copied after first use.

func (*MapOf[K, V]) Delete

func (m *MapOf[K, V]) Delete(key K)

Delete deletes the value for a key.

func (*MapOf[K, V]) Load

func (m *MapOf[K, V]) Load(key K) (value V, ok bool)

Load returns the value stored in the map for a key, or nil if no value is present. The ok result indicates whether value was found in the map.

func (*MapOf[K, V]) LoadAndDelete

func (m *MapOf[K, V]) LoadAndDelete(key K) (value V, loaded bool)

LoadAndDelete deletes the value for a key, returning the previous value if any. The loaded result reports whether the key was present.

func (*MapOf[K, V]) LoadOrStore

func (m *MapOf[K, V]) LoadOrStore(key K, value V) (actual V, loaded bool)

LoadOrStore returns the existing value for the key if present. Otherwise, it stores and returns the given value. The loaded result is true if the value was loaded, false if stored.

func (*MapOf[K, V]) Range

func (m *MapOf[K, V]) Range(f func(key K, value V) bool)

Range calls f sequentially for each key and value present in the map. If f returns false, range stops the iteration.

Range does not necessarily correspond to any consistent snapshot of the MapOf's contents: no key will be visited more than once, but if the value for any key is stored or deleted concurrently, Range may reflect any mapping for that key from any point during the Range call.

Range may be O(N) with the number of elements in the map even if f returns false after a constant number of calls.

func (*MapOf[K, V]) Store

func (m *MapOf[K, V]) Store(key K, value V)

Store sets the value for a key.

type MessageRouter

type MessageRouter interface {
	SendToPresenceIDs(*zap.Logger, []*PresenceID, *pb.Bombus_ResponseWriter, bool)
	SendToStream(*zap.Logger, PresenceStream, *pb.Bombus_ResponseWriter, bool)
	SendDeferred(*zap.Logger, []*DeferredMessage)
	SendToAll(*zap.Logger, *pb.Bombus_ResponseWriter, bool)
	SetPeer(peer Peer)
}

MessageRouter is responsible for sending a message to a list of presences or to an entire stream.

func NewLocalMessageRouter

func NewLocalMessageRouter(sessionRegistry SessionRegistry, tracker Tracker, protojsonMarshaler *protojson.MarshalOptions) MessageRouter

type Metrics

type Metrics interface {
	Stop(logger *zap.Logger)

	SnapshotLatencyMs() float64
	SnapshotRateSec() float64
	SnapshotRecvKbSec() float64
	SnapshotSentKbSec() float64

	Api(name string, elapsed time.Duration, recvBytes, sentBytes int64, isErr bool)
	ApiRpc(id string, elapsed time.Duration, recvBytes, sentBytes int64, isErr bool)

	Message(recvBytes int64, isErr bool)
	MessageBytesSent(sentBytes int64)

	CountWebsocketOpened(delta int64)
	CountWebsocketClosed(delta int64)
	GaugeSessions(value float64)
	GaugePresences(value float64)
	GaugePeers(value float64)

	PresenceEvent(dequeueElapsed, processElapsed time.Duration)

	PeerRecv(recvBytes int64)
	PeerSent(sentBytes int64)
}

func NewLocalMetrics

func NewLocalMetrics(logger, startupLogger *zap.Logger, db *sql.DB, config Config) Metrics

type MetricsConfig

type MetricsConfig struct {
	ReportingFreqSec int    `yaml:"reporting_freq_sec" json:"reporting_freq_sec" usage:"Frequency of metrics exports. Default is 60 seconds."`
	Namespace        string `yaml:"namespace" json:"namespace" usage:"Namespace for Prometheus metrics. It will always prepend node name."`
	PrometheusPort   int    `yaml:"prometheus_port" json:"prometheus_port" usage:"Port to expose Prometheus. If '0' Prometheus exports are disabled."`
	Prefix           string `yaml:"prefix" json:"prefix" usage:"Prefix for metric names. Default is 'nakama', empty string '' disables the prefix."`
	CustomPrefix     string `` /* 147-byte string literal not displayed */
}

MetricsConfig is configuration relevant to metrics capturing and output.

func NewMetricsConfig

func NewMetricsConfig() *MetricsConfig

type Peer

type Peer interface {
	memberlist.Delegate
	memberlist.EventDelegate
	memberlist.AliveDelegate
	memberlist.ConflictDelegate
	memberlist.MergeDelegate
	memberlist.PingDelegate
	Shutdown()
	Join(members ...string) (int, error)
	Local() Endpoint
	NumMembers() int
	Member(name string) (Endpoint, bool)
	Broadcast(msg *pb.Bombus_Request, reliable bool)
	BroadcastBinaryLog(b *pb.Bombus_Peer_BinaryLog)
	Send(endpoint Endpoint, msg *pb.Bombus_Request, reliable bool) error
	Request(ctx context.Context, endpoint Endpoint, msg *pb.Bombus_Request) (*pb.Bombus_ResponseWriter, error)
	GetServiceRegistry() kit.ServiceRegistry
	Version() (map[string][2]uint64, int)
}

func NewLocalPeer

func NewLocalPeer(logger *zap.Logger, name string, metadata map[string]string, metrics Metrics, sessionRegistry SessionRegistry, tracker Tracker, messageRouter MessageRouter, c *PeerConfig) Peer

type PeerBroadcast

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

func (*PeerBroadcast) Finished

func (b *PeerBroadcast) Finished()

Finished is invoked when the message will no longer be broadcast, either due to invalidation or to the transmit limit being reached

func (*PeerBroadcast) Invalidates

func (b *PeerBroadcast) Invalidates(other memberlist.Broadcast) bool

Invalidates checks if enqueuing the current broadcast invalidates a previous broadcast

func (*PeerBroadcast) Message

func (b *PeerBroadcast) Message() []byte

Returns a byte form of the message

func (*PeerBroadcast) Name

func (b *PeerBroadcast) Name() string

The unique identity of this broadcast message.

type PeerConfig

type PeerConfig struct {
	Addr                string               `` /* 144-byte string literal not displayed */
	Port                int                  `yaml:"gossip_bindport" json:"gossip_bindport" usage:"Port number to bind Nakama to for discovery. Default value is 7352."`
	PushPullInterval    int                  `` /* 151-byte string literal not displayed */
	GossipInterval      int                  `` /* 152-byte string literal not displayed */
	TCPTimeout          int                  `` /* 219-byte string literal not displayed */
	ProbeTimeout        int                  `` /* 260-byte string literal not displayed */
	ProbeInterval       int                  `` /* 287-byte string literal not displayed */
	RetransmitMult      int                  `` /* 173-byte string literal not displayed */
	MaxGossipPacketSize int                  `` /* 236-byte string literal not displayed */
	BroadcastQueueSize  int                  `yaml:"broadcast_queue_size" json:"broadcast_queue_size" usage:"broadcast message queue size"`
	Members             []string             `yaml:"members" json:"members" usage:""`
	SecretKey           string               `` /* 201-byte string literal not displayed */
	Etcd                *etcd.Clientv3Config `yaml:"etcd" json:"etcd" usage:"Etcd config"`
	Weight              int32                `yaml:"weight" json:"weight" usage:"weight"`
	Balancer            int32                `yaml:"balancer" json:"balancer" usage:"balancer"`
	Grpc                *kit.GrpcConfig      `yaml:"grpc" json:"grpc" usage:"grpc client setting"`
}

func NewPeerConfig

func NewPeerConfig() *PeerConfig

func (*PeerConfig) Clone

func (c *PeerConfig) Clone() *PeerConfig

func (*PeerConfig) Valid

func (c *PeerConfig) Valid() error

type PeerEndpoint

type PeerEndpoint struct {
	sync.Mutex
	// contains filtered or unexported fields
}

func (*PeerEndpoint) AvgInputKbs

func (endpoint *PeerEndpoint) AvgInputKbs() float64

func (*PeerEndpoint) AvgLatencyMs

func (endpoint *PeerEndpoint) AvgLatencyMs() float64

func (*PeerEndpoint) AvgOutputKbs

func (endpoint *PeerEndpoint) AvgOutputKbs() float64

func (*PeerEndpoint) AvgRateSec

func (endpoint *PeerEndpoint) AvgRateSec() float64

func (*PeerEndpoint) Balancer

func (endpoint *PeerEndpoint) Balancer(v ...int32) int32

func (*PeerEndpoint) BindMemberlistNode

func (endpoint *PeerEndpoint) BindMemberlistNode(node *memberlist.Node)

func (*PeerEndpoint) DeleteMetadata

func (endpoint *PeerEndpoint) DeleteMetadata(deleteKey string)

func (*PeerEndpoint) GetMetadata

func (endpoint *PeerEndpoint) GetMetadata(k string) string

func (*PeerEndpoint) GoroutineCount

func (endpoint *PeerEndpoint) GoroutineCount() int32

func (*PeerEndpoint) MarshalJSON

func (endpoint *PeerEndpoint) MarshalJSON() ([]byte, error)

func (*PeerEndpoint) MarshalProtoBuffer

func (endpoint *PeerEndpoint) MarshalProtoBuffer() ([]byte, error)

func (*PeerEndpoint) MatchCount

func (endpoint *PeerEndpoint) MatchCount() int32

func (*PeerEndpoint) MemberlistNode

func (endpoint *PeerEndpoint) MemberlistNode() *memberlist.Node

func (*PeerEndpoint) MergeStateAt

func (endpoint *PeerEndpoint) MergeStateAt() int64

func (*PeerEndpoint) Metadata

func (endpoint *PeerEndpoint) Metadata() map[string]string

func (*PeerEndpoint) Name

func (endpoint *PeerEndpoint) Name() string

func (*PeerEndpoint) PingCompleted

func (endpoint *PeerEndpoint) PingCompleted(rtt time.Duration)

func (*PeerEndpoint) PingRTT

func (endpoint *PeerEndpoint) PingRTT(v ...time.Duration) time.Duration

func (*PeerEndpoint) PresenceCount

func (endpoint *PeerEndpoint) PresenceCount() int32

func (*PeerEndpoint) ResetMetadata

func (endpoint *PeerEndpoint) ResetMetadata(md map[string]string)

func (*PeerEndpoint) SessionCount

func (endpoint *PeerEndpoint) SessionCount() int32

func (*PeerEndpoint) SetMetadata

func (endpoint *PeerEndpoint) SetMetadata(k, v string)

func (*PeerEndpoint) Status

func (endpoint *PeerEndpoint) Status(v ...int32) int32

func (*PeerEndpoint) UpdateState

func (endpoint *PeerEndpoint) UpdateState(status *pb.Bombus_Peer_Status)

func (*PeerEndpoint) Weight

func (endpoint *PeerEndpoint) Weight(v ...int32) int32

type PeerInbox

type PeerInbox struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

func NewPeerInbox

func NewPeerInbox() *PeerInbox

func (*PeerInbox) Deregister

func (s *PeerInbox) Deregister(inbox string)

func (*PeerInbox) Register

func (s *PeerInbox) Register(inbox string, reply chan *pb.Bombus_Peer_Frame) error

func (*PeerInbox) Send

func (s *PeerInbox) Send(frame *pb.Bombus_Peer_Frame)

type Presence

type Presence struct {
	ID     PresenceID
	Stream PresenceStream
	UserID uuid.UUID
	Meta   PresenceMeta
}

func (*Presence) GetHidden

func (p *Presence) GetHidden() bool

func (*Presence) GetNodeId

func (p *Presence) GetNodeId() string

func (*Presence) GetPersistence

func (p *Presence) GetPersistence() bool

func (*Presence) GetReason

func (p *Presence) GetReason() PresenceReason

func (*Presence) GetSessionId

func (p *Presence) GetSessionId() string

func (*Presence) GetStatus

func (p *Presence) GetStatus() string

func (*Presence) GetUserId

func (p *Presence) GetUserId() string

func (*Presence) GetUsername

func (p *Presence) GetUsername() string

type PresenceEvent

type PresenceEvent struct {
	Joins  []*Presence
	Leaves []*Presence

	QueueTime time.Time
}

type PresenceID

type PresenceID struct {
	Node      string
	SessionID uuid.UUID
}

type PresenceMeta

type PresenceMeta struct {
	Format      SessionFormat
	Hidden      bool
	Persistence bool
	Username    string
	Status      string
	Reason      uint32
}

func (*PresenceMeta) GetHidden

func (pm *PresenceMeta) GetHidden() bool

func (*PresenceMeta) GetPersistence

func (pm *PresenceMeta) GetPersistence() bool

func (*PresenceMeta) GetReason

func (pm *PresenceMeta) GetReason() PresenceReason

func (*PresenceMeta) GetStatus

func (pm *PresenceMeta) GetStatus() string

func (*PresenceMeta) GetUsername

func (pm *PresenceMeta) GetUsername() string

type PresenceReason

type PresenceReason uint8
const (
	PresenceReason_UNKNOWN PresenceReason = iota
	PresenceReason_JOIN
	PresenceReason_UPDATE
	PresenceReason_LEAVE
	PresenceReason_DISCONNECT
)

type PresenceStream

type PresenceStream struct {
	Mode       uint8
	Subject    uuid.UUID
	Subcontext uuid.UUID
	Label      string
}

type RouterMiddleware

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

func NewRouterMiddleware

func NewRouterMiddleware(logger *zap.Logger, metrics Metrics, sessionBan SessionBan, config Config) *RouterMiddleware

func (*RouterMiddleware) Access

func (m *RouterMiddleware) Access() gin.HandlerFunc

func (*RouterMiddleware) Authorization

func (m *RouterMiddleware) Authorization() gin.HandlerFunc

func (*RouterMiddleware) MaxBytesReader

func (m *RouterMiddleware) MaxBytesReader() gin.HandlerFunc

func (*RouterMiddleware) RateLimiter

func (m *RouterMiddleware) RateLimiter() gin.HandlerFunc

type RpcHandle

type RpcHandle func(ctx *gin.Context, runtime Runtime)

type RpcRegistry

type RpcRegistry interface {
	Init() RpcRegistry
	Register(id string, handle RpcHandle, routes ...*RpcRoute)
	Deregister(id string)
	Reset()
	Get(id string) (RpcHandle, bool)
}

func NewLocalRpcRegistry

func NewLocalRpcRegistry(logger *zap.Logger) RpcRegistry

type RpcRoute

type RpcRoute struct {
	ID     string
	Handle RpcHandle
}

type Runtime

type Runtime interface {
	Shutdown()
	DB() *gorm.DB
	Context() context.Context
	GetConsoleLogger() *zap.Logger
	GetLogger() *zap.Logger
	GetConfig() Config
	GetRpcRegistry() RpcRegistry
	GetMetrics() Metrics
	GetSessionBan() SessionBan
	GetSessionRegistry() SessionRegistry
	GetTracker() Tracker
	GetPeer() Peer
	GetSocialClient() *social.Client
	GetWorker() *worker.WorkerPool
	GetMessageRouter() MessageRouter
}

func NewLocalRuntime

func NewLocalRuntime(ctx context.Context, consoleLogger, startupLogger *zap.Logger, db *gorm.DB, config Config) Runtime

type RuntimeConfig

type RuntimeConfig struct {
	Environment map[string]string `yaml:"-" json:"-"`
	Env         []string          `yaml:"env" json:"env" usage:"Values to pass into Runtime as environment variables."`
	HTTPKey     string            `yaml:"http_key" json:"http_key" usage:"Runtime HTTP Invocation key."`
	NumWorker   int               `yaml:"num_worker" json:"num_worker" usage:"Runtime Worker number. default:1024"`
}

RuntimeConfig is configuration relevant to the Runtimes.

func NewRuntimeConfig

func NewRuntimeConfig() *RuntimeConfig

type Session

type Session interface {
	Logger() *zap.Logger
	ID() uuid.UUID
	UserID() uuid.UUID
	Vars() map[string]string
	ClientIP() string
	ClientPort() string
	Lang() string

	Context() context.Context

	Username() string
	SetUsername(string)

	Expiry() int64
	Consume()

	Format() SessionFormat
	Send(envelope *pb.Bombus_ResponseWriter, reliable bool) error
	SendBytes(payload []byte, reliable bool) error

	Close(msg string, reason PresenceReason, envelopes ...*pb.Bombus_ResponseWriter)
}

func NewSessionWs

func NewSessionWs(logger *zap.Logger, format SessionFormat, sessionID, userID uuid.UUID, username string, vars map[string]string, expiry int64, clientIP, clientPort, lang string, conn *websocket.Conn, runtime Runtime) Session

type SessionBan

type SessionBan interface {
	Stop()

	// Check if a given user, expiry, and session token combination is valid.
	IsValidSession(userID uuid.UUID, exp int64, tokenId string) bool
	// Check if a given user, expiry, and refresh token combination is valid.
	IsValidRefresh(userID uuid.UUID, exp int64, tokenId string) bool
	// Add a valid session and/or refresh token for a given user.
	Add(userID uuid.UUID, sessionExp int64, sessionTokenId string, refreshExp int64, refreshTokenId string)
	// Remove a session and/or refresh token for a given user.
	Remove(userID uuid.UUID, sessionExp int64, sessionTokenId string, refreshExp int64, refreshTokenId string)
	// Remove all of a user's session and refresh tokens.
	RemoveAll(userID uuid.UUID)
	// Mark a set of users as banned.
	Ban(userIDs []uuid.UUID)
	// Unban a set of users.
	Unban(userIDs []uuid.UUID)
}

func NewLocalSessionBan

func NewLocalSessionBan(tokenExpirySec, refreshTokenExpirySec int64) SessionBan

type SessionConfig

type SessionConfig struct {
	EncryptionKey         string `yaml:"encryption_key" json:"encryption_key" usage:"The encryption key used to produce the client token."`
	TokenExpirySec        int64  `yaml:"token_expiry_sec" json:"token_expiry_sec" usage:"Token expiry in seconds."`
	RefreshEncryptionKey  string `` /* 128-byte string literal not displayed */
	RefreshTokenExpirySec int64  `yaml:"refresh_token_expiry_sec" json:"refresh_token_expiry_sec" usage:"Refresh token expiry in seconds."`
	SingleSocket          bool   `` /* 129-byte string literal not displayed */
	SingleMatch           bool   `` /* 158-byte string literal not displayed */
}

SessionConfig is configuration relevant to the session.

func NewSessionConfig

func NewSessionConfig() *SessionConfig

type SessionFormat

type SessionFormat uint8
const (
	SessionFormat_JSON SessionFormat = iota
	SessionFormat_PROTOBUF
)

type SessionRegistry

type SessionRegistry interface {
	Stop()
	Count() int
	Get(sessionID uuid.UUID) Session
	Add(session Session)
	Remove(sessionID uuid.UUID)
	Disconnect(ctx context.Context, sessionID uuid.UUID, ban bool, reason ...PresenceReason) error
	SingleSession(ctx context.Context, tracker Tracker, userID, sessionID uuid.UUID)
	Range(fn func(session Session) bool)
}

func NewLocalSessionRegistry

func NewLocalSessionRegistry(metrics Metrics) SessionRegistry

type SessionTokenClaims

type SessionTokenClaims struct {
	TokenId   string            `json:"tid,omitempty"`
	UserId    string            `json:"uid,omitempty"`
	Username  string            `json:"usn,omitempty"`
	Vars      map[string]string `json:"vrs,omitempty"`
	ExpiresAt int64             `json:"exp,omitempty"`
}

func (*SessionTokenClaims) Valid

func (stc *SessionTokenClaims) Valid() error

type SessionWs

type SessionWs struct {
	sync.Mutex
	// contains filtered or unexported fields
}

func (*SessionWs) ClientIP

func (s *SessionWs) ClientIP() string

func (*SessionWs) ClientPort

func (s *SessionWs) ClientPort() string

func (*SessionWs) Close

func (s *SessionWs) Close(msg string, reason PresenceReason, envelopes ...*pb.Bombus_ResponseWriter)

func (s *SessionWs) Close(msg string, reason PresenceReason, envelopes ...*rtapi.Envelope) {

func (*SessionWs) Consume

func (s *SessionWs) Consume()

func (*SessionWs) Context

func (s *SessionWs) Context() context.Context

func (*SessionWs) Expiry

func (s *SessionWs) Expiry() int64

func (*SessionWs) Format

func (s *SessionWs) Format() SessionFormat

func (*SessionWs) ID

func (s *SessionWs) ID() uuid.UUID

func (*SessionWs) Lang

func (s *SessionWs) Lang() string

func (*SessionWs) Logger

func (s *SessionWs) Logger() *zap.Logger

func (*SessionWs) Send

func (s *SessionWs) Send(envelope *pb.Bombus_ResponseWriter, reliable bool) error

func (*SessionWs) SendBytes

func (s *SessionWs) SendBytes(payload []byte, reliable bool) error

func (*SessionWs) SetUsername

func (s *SessionWs) SetUsername(username string)

func (*SessionWs) UserID

func (s *SessionWs) UserID() uuid.UUID

func (*SessionWs) Username

func (s *SessionWs) Username() string

func (*SessionWs) Vars

func (s *SessionWs) Vars() map[string]string

type SocialConfig

type SocialConfig struct {
	Steam                *SocialConfigSteam                `yaml:"steam" json:"steam" usage:"Steam configuration."`
	FacebookInstantGame  *SocialConfigFacebookInstantGame  `yaml:"facebook_instant_game" json:"facebook_instant_game" usage:"Facebook Instant Game configuration."`
	FacebookLimitedLogin *SocialConfigFacebookLimitedLogin `yaml:"facebook_limited_login" json:"facebook_limited_login" usage:"Facebook Limited Login configuration."`
	Apple                *SocialConfigApple                `yaml:"apple" json:"apple" usage:"Apple Sign In configuration."`
}

SocialConfig is configuration relevant to the social authentication providers.

func NewSocialConfig

func NewSocialConfig() *SocialConfig

type SocialConfigApple

type SocialConfigApple struct {
	BundleId string `yaml:"bundle_id" json:"bundle_id" usage:"Apple Sign In bundle ID."`
}

SocialConfigApple is configuration relevant to Apple Sign In.

type SocialConfigFacebookInstantGame

type SocialConfigFacebookInstantGame struct {
	AppSecret string `yaml:"app_secret" json:"app_secret" usage:"Facebook Instant App secret."`
}

SocialConfigFacebookInstantGame is configuration relevant to Facebook Instant Games.

type SocialConfigFacebookLimitedLogin

type SocialConfigFacebookLimitedLogin struct {
	AppId string `yaml:"app_id" json:"app_id" usage:"Facebook Limited Login App ID."`
}

SocialConfigFacebookLimitedLogin is configuration relevant to Facebook Limited Login.

type SocialConfigSteam

type SocialConfigSteam struct {
	PublisherKey string `yaml:"publisher_key" json:"publisher_key" usage:"Steam Publisher Key value."`
	AppID        int    `yaml:"app_id" json:"app_id" usage:"Steam App ID."`
}

SocialConfigSteam is configuration relevant to Steam.

type SocketConfig

type SocketConfig struct {
	ServerKey            string            `yaml:"server_key" json:"server_key" usage:"Server key to use to establish a connection to the server."`
	Port                 int               `` /* 154-byte string literal not displayed */
	Address              string            `` /* 156-byte string literal not displayed */
	Protocol             string            `` /* 198-byte string literal not displayed */
	MaxMessageSizeBytes  int64             `` /* 186-byte string literal not displayed */
	MaxRequestSizeBytes  int64             `` /* 180-byte string literal not displayed */
	ReadBufferSizeBytes  int               `` /* 136-byte string literal not displayed */
	WriteBufferSizeBytes int               `` /* 139-byte string literal not displayed */
	ReadTimeoutMs        int               `` /* 145-byte string literal not displayed */
	WriteTimeoutMs       int               `` /* 157-byte string literal not displayed */
	IdleTimeoutMs        int               `` /* 178-byte string literal not displayed */
	WriteWaitMs          int               `` /* 156-byte string literal not displayed */
	PongWaitMs           int               `` /* 156-byte string literal not displayed */
	PingPeriodMs         int               `` /* 204-byte string literal not displayed */
	PingBackoffThreshold int               `` /* 293-byte string literal not displayed */
	OutgoingQueueSize    int               `` /* 245-byte string literal not displayed */
	SSLCertificate       string            `` /* 192-byte string literal not displayed */
	SSLPrivateKey        string            `` /* 192-byte string literal not displayed */
	ResponseHeaders      []string          `` /* 219-byte string literal not displayed */
	LimiterBursts        int               `yaml:"limiter_bursts" json:"limiter_bursts" usage:"bursts of at most b tokens. Used for real-time connections."`
	LimiterRequestBursts int               ``                  /* 127-byte string literal not displayed */
	LimiterWait          int               ``                  /* 276-byte string literal not displayed */
	LimiterRequestWait   int               ``                  /* 293-byte string literal not displayed */
	MaxLimit             int               ``                  /* 126-byte string literal not displayed */
	MaxLimitRequest      int               ``                  /* 142-byte string literal not displayed */
	Headers              map[string]string `yaml:"-" json:"-"` // Created by parsing ResponseHeaders above, not set from input args directly.
	CertPEMBlock         []byte            `yaml:"-" json:"-"` // Created by fully reading the file contents of SSLCertificate, not set from input args directly.
	KeyPEMBlock          []byte            `yaml:"-" json:"-"` // Created by fully reading the file contents of SSLPrivateKey, not set from input args directly.
	TLSCert              []tls.Certificate `yaml:"-" json:"-"` // Created by processing CertPEMBlock and KeyPEMBlock, not set from input args directly.
}

SocketConfig is configuration relevant to the transport socket and protocol.

func NewSocketConfig

func NewSocketConfig() *SocketConfig

type Tracker

type Tracker interface {
	Stop()
	SetPeer(peer Peer)

	// Track returns success true/false, and new presence true/false.
	Track(ctx context.Context, sessionID uuid.UUID, stream PresenceStream, userID uuid.UUID, meta PresenceMeta, allowIfFirstForSession bool, nodeValue ...string) (bool, bool)
	TrackMulti(ctx context.Context, sessionID uuid.UUID, ops []*TrackerOp, userID uuid.UUID, allowIfFirstForSession bool, nodeValue ...string) bool
	Untrack(sessionID uuid.UUID, stream PresenceStream, userID uuid.UUID, nodeValue ...string)
	UntrackMulti(sessionID uuid.UUID, streams []*PresenceStream, userID uuid.UUID, nodeValue ...string)
	UntrackAll(sessionID uuid.UUID, reason PresenceReason, nodeValue ...string)
	// Update returns success true/false - will only fail if the user has no presence and allowIfFirstForSession is false, otherwise is an upsert.
	Update(ctx context.Context, sessionID uuid.UUID, stream PresenceStream, userID uuid.UUID, meta PresenceMeta, allowIfFirstForSession bool, nodeValue ...string) bool

	// Remove all presences on a stream, effectively closing it.
	UntrackByStream(stream PresenceStream)
	// Remove all presences on a stream from the local node.
	UntrackLocalByStream(stream PresenceStream)
	// Remove the given session from any streams matching the given mode, except the specified stream.
	UntrackByModes(sessionID uuid.UUID, modes map[uint8]struct{}, skipStream PresenceStream)
	// Remove the given session from any streams matching the given mode, except the specified stream.
	UntrackLocalByModes(sessionID uuid.UUID, modes map[uint8]struct{}, skipStream PresenceStream)

	// List the nodes that have at least one presence for the given stream.
	ListNodesForStream(stream PresenceStream) map[string]struct{}

	// Check if a stream exists (has any presences) or not.
	StreamExists(stream PresenceStream) bool
	// Get current total number of presences.
	Count() int
	// Get the number of presences in the given stream.
	CountByStream(stream PresenceStream) int
	// Get a snapshot of current presence counts for streams with one of the given stream modes.
	CountByStreamModeFilter(modes map[uint8]*uint8) map[*PresenceStream]int32
	// Check if a single presence on the current node exists.
	GetLocalBySessionIDStreamUserID(sessionID uuid.UUID, stream PresenceStream, userID uuid.UUID) *PresenceMeta
	// Check if a single presence on any node exists.
	GetBySessionIDStreamUserID(node string, sessionID uuid.UUID, stream PresenceStream, userID uuid.UUID) *PresenceMeta
	// List presences by stream, optionally include hidden ones and not hidden ones.
	ListByStream(stream PresenceStream, includeHidden bool, includeNotHidden bool) []*Presence

	// Fast lookup of local session IDs to use for message delivery.
	ListLocalSessionIDByStream(stream PresenceStream) []uuid.UUID
	// Fast lookup of node + session IDs to use for message delivery.
	ListPresenceIDByStream(stream PresenceStream) []*PresenceID

	// Fast lookup of node + session IDs to use for message delivery.
	ListLocalPresenceIDByStream(stream PresenceStream) []*PresenceID
	// Fast lookup of presences for a set of user IDs + stream mode.
	ListPresenceIDByStreams(fill map[PresenceStream][]*PresenceID)

	// Loop stream
	Range(fn func(sessionID uuid.UUID, presences []*Presence) bool)

	// MergeRemoteState
	MergeRemoteState(node string, presences []*pb.Bombus_Peer_Presence, join bool)

	// clear
	ClearTrackByNode(node string)

	// clear
	ClearRemoteTrack()
}

func NewLocalTracker

func NewLocalTracker(logger *zap.Logger, sessionRegistry SessionRegistry, metrics Metrics, config Config) Tracker

type TrackerConfig

type TrackerConfig struct {
	EventQueueSize int `` /* 210-byte string literal not displayed */
}

TrackerConfig is configuration relevant to the presence tracker.

func NewTrackerConfig

func NewTrackerConfig() *TrackerConfig

type TrackerOp

type TrackerOp struct {
	Stream PresenceStream
	Meta   PresenceMeta
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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