...

Package session

import "github.com/Diarkis/diarkis/session"
Overview
Index

Overview ▾

Package session ▷

Session Module

Session is compatible with Room, Group, Field, and DM.

Session

A session allows users to become members and all members may send and receive messages.

A session has maximum number of members allowed, you can invite members as many as you want but members cannot join the Session if it reached to the maximum number when they accept the invitation.

  • A session has a limitation of how many users may join.

  • A session raises an event when a new member joins, a member leaves, session is deleted.

  • A session allows sending and receiving broadcast messages to all session member users.

  • A session may store shared properties for as long as the session remains active.

Session Invite

As a owner (creator) of a session, you may invite any user by their user ID to join your session.

The invited user will receive an invitation message and will be able to accept the invitation by using Join function. An invitation has a TTL (in seconds) and once TTL is expired, accepting the invitation will not guarantee the invited user to be able to join the session.

Accepting Invite

A user that is invited to a session by session invite function may accept the invite and join the session by invoking Join.

Index ▾

func Broadcast(sessionType uint8, sessionID string, ver uint8, cmd uint16, msg []byte) error
func ExposeCommands()
func ExposePufferCommands()
func GetAllSessionMemberData(sessionType uint8, userData *user.User, cb func(err error, sud []*UserData))
func GetMemberIDs(sessionType uint8, userData *user.User, cb func(err error, memberIDs []string))
func GetMemberSIDs(sessionType uint8, userData *user.User, cb func(err error, memberSIDs []string))
func GetProperties(sessionType uint8, userData *user.User, keys []string, cb func(err error, props map[string]interface{}))
func GetProperty(sessionType uint8, userData *user.User, key string, cb func(err error, value interface{}, exists bool))
func GetSessionID(sessionType uint8, userData *user.User) string
func GetSessionIDByUser(sessionType uint8, userData *user.User) (string, bool)
func GetSessionInfo(sessionID string, cb func(err error, info *GetSessionInfoData))
func IsAcceptError(err error) bool
func IsInviteError(err error) bool
func IsJoinError(err error) bool
func IsKickError(err error) bool
func IsLeaveError(err error) bool
func IsMemberError(err error) bool
func IsOwner(sessionType uint8, userData *user.User, cb func(err error, isOwner bool))
func IsOwnerError(err error) bool
func IsPropertyGetError(err error) bool
func IsPropertySetError(err error) bool
func IsSendError(err error) bool
func IsSessionError(err error) bool
func JoinSessionByID(sessionType uint8, id string, userData *user.User, cb func(error))
func KickFromSession(sessionType uint8, sessionID string, targetUserID string, cb func(error))
func KickFromSessionWithUserData(sessionType uint8, userData *user.User, targetUserID string, cb func(error))
func LeaveSessionByID(sessionType uint8, id string, userData *user.User, cb func(error))
func MessageTo(sessionType uint8, sessionID string, senderUID string, recipientUIDs []string, ver uint8, cmd uint16, msg []byte) error
func SendInvite(sessionType uint8, id string, userData *user.User, targetUserIDs []string, ver uint8, cmd uint16, message []byte, cb func(err error))
func SetProperties(sessionType uint8, userData *user.User, kvList []*PropertyKeyValue, cb func(err error))
func SetProperty(sessionType uint8, userData *user.User, key string, value interface{}, cb func(err error, success bool))
func SetPropertyIfNotExists(sessionType uint8, userData *user.User, key string, value interface{}, cb func(err error, success bool))
func Setup()
type FindOwnerData
type GetMemberData
type GetSessionInfoData
type IsOwnerData
type IsOwnerReturnData
type JoinSessionData
type LeaveSessionData
type LeaveSessionReturnData
type MessageData
type PropertiesData
type PropertyData
type PropertyKeyValue
type PropertyReturnData
type Session
    func GetSessionByID(id string) (*Session, bool)
    func NewSession(userData *user.User, sessionType uint8, maxMembers uint16, ttl uint16) (*Session, error)
    func (s *Session) GetID() string
    func (s *Session) GetMemberIDs() []string
    func (s *Session) GetMemberMeshAddrByUID(uid string) string
    func (s *Session) GetMemberMeshAddrList() []string
    func (s *Session) GetMemberSIDByUID(uid string) string
    func (s *Session) GetMemberSIDs() []string
    func (s *Session) GetMemberUsers() []*user.User
    func (s *Session) GetOwnerUser() (*user.User, bool)
    func (s *Session) GetProperties(keys []string) map[string]interface{}
    func (s *Session) GetProperty(key string) (interface{}, bool)
    func (s *Session) GetType() uint8
    func (s *Session) IsJoinAllowed(memberCnt int) bool
    func (s *Session) IsMemberByUID(uid string) bool
    func (s *Session) SetOnDelete(cb func(id string)) bool
    func (s *Session) SetOnDeleted(cb func(id string)) bool
    func (s *Session) SetOnJoin(cb func(id string, userData *user.User) bool) bool
    func (s *Session) SetOnJoined(cb func(id string, userData *user.User)) bool
    func (s *Session) SetOnLeft(cb func(id string, userData *user.User)) bool
    func (s *Session) SetOnTick(interval uint16, cb func(id string)) bool
    func (s *Session) SetOnTickStop(interval uint16, cb func(id string)) bool
    func (s *Session) SetProperties(data map[string]interface{}) error
    func (s *Session) SetProperty(key string, value interface{})
    func (s *Session) SetPropertyIfNotExists(key string, value interface{}) bool
    func (s *Session) StopAllTicks() bool
    func (s *Session) UpdateProperties(data map[string]interface{}, cb func(bool, interface{}, interface{}) interface{})
    func (s *Session) UpdateProperty(key string, value interface{}, cb func(bool, interface{}, interface{}) interface{})
type UserData
    func (sessionUser *UserData) CreateCopyUser() *user.User
type UserSessionData
    func GetSessionDataByUser(userData *user.User) []UserSessionData

func Broadcast

func Broadcast(sessionType uint8, sessionID string, ver uint8, cmd uint16, msg []byte) error

Broadcast sends a reliable message to all member users with the given ver, cmd, and message byte array.

[IMPORTANT] This function can be executed by any user as long as it is provided with a valid session ID..
[IMPORTANT] If the session no longer exists, it will not propagate the error, but silently fails internally.
[IMPORTANT] The function communicates with another server internally.
[IMPORTANT] This function works on any server.

Error Cases

+-----------------------+-------------------------------------------------+
| Error                 | Reason                                          |
+-----------------------+-------------------------------------------------+
| Session ID is invalid | The given session ID is not a valid session ID. |
| Session not found     | The session no longer exists.                   |
+-----------------------+-------------------------------------------------+

Parameters

sessionType - Type of the session.
sessionID   - Session ID.
ver         - Command ver to be used as the broadcast message.
cmd         - Command ID to be used as the broadcast message.
msg         - Broadcast message to be sent.

func ExposeCommands

func ExposeCommands()

ExposeCommands exposes built-in Session module commands to the client.

func ExposePufferCommands

func ExposePufferCommands()

ExposePufferCommands exposes built-in Session module puffer commands to the client.

func GetAllSessionMemberData

func GetAllSessionMemberData(sessionType uint8, userData *user.User, cb func(err error, sud []*UserData))

GetAllSessionMemberData collects and returns an array of UserData from the servers where Session members are. Since the client data in Members can be outdated, you might want to use this func when you need the latest data.

[IMPORTANT] The function communicates with another server internally.
[IMPORTANT] This function works on any server.
[IMPORTANT] The data you can get from UserData is a copy of the data when the user joined the session.

[NOTE] It works only when you are a member of Session specified with passed sessionType.

Error Cases:

+-----------------------+-------------------------------------------------------------------------------------------+
| Error                 | Reason                                                                                    |
+-----------------------+-------------------------------------------------------------------------------------------+
| Cannot get session ID | The passed sessionType is wrong or you are not a member of the Session anymore.           |
| Invalid session ID    | Session ID is wrong format. This normally does not happen as it is from userData.         |
+-----------------------+-------------------------------------------------------------------------------------------+

Parameters

sessionType - sessionType that you want to get the data from.
userData    - Sender user data: sender.
cb          - Callback invoked on get session member data. It returns an array of UserData.

func GetMemberIDs

func GetMemberIDs(sessionType uint8, userData *user.User, cb func(err error, memberIDs []string))

GetMemberIDs returns the list of member user IDs with the callback.

[IMPORTANT] The function communicates with another server internally.
[IMPORTANT] This function works on any server.

Error Cases

+--------------------------+-------------------------------------------------------------------------+
| Error                    | Reason                                                                  |
+--------------------------+-------------------------------------------------------------------------+
| User is not a member     | The given user is not a member of the session.                          |
| Failed to get member IDs | Session is no longer available.                                         |
| Failed to get member IDs | Server-to-server communication failed.                                  |
|                          | Possible cause maybe server load, incorrectly setup server cluster etc. |
+--------------------------+-------------------------------------------------------------------------+

Parameters

sessionType - Session Type.
userData    - Session member user.
cb          - Callback to be invoked when the operation is complete.
              func(err error, memberIDs []string)
              err       - Error when the operation fails.
              memberIDs - A list of session member IDs.

func GetMemberSIDs

func GetMemberSIDs(sessionType uint8, userData *user.User, cb func(err error, memberSIDs []string))

GetMemberSIDs returns the list of member user IDs with the callback.

[IMPORTANT] The function communicates with another server internally.
[IMPORTANT] This function works on any server.

Error Cases

+---------------------------+-------------------------------------------------------------------------+
| Error                     | Reason                                                                  |
+----------------------------+-------------------------------------------------------------------------+
| Session ID is invalid     | The given session ID is not a valid session ID.                         |
| User is not a member      | The given user is not a member of the session.                          |
| Failed to get member SIDs | Session is no longer available.                                         |
| Failed to get member SIDs | Server-to-server communication failed.                                  |
|                           | Possible cause maybe server load, incorrectly setup server cluster etc. |
+---------------------------+-------------------------------------------------------------------------+

Parameters

sessionType - Session type.
userData    - Session member user.
cb          - Callback to be invoked when the operation is complete.
              func(err error, memberIDs []string)
              err       - Error when the operation fails.
              memberSIDs - A list of session member SIDs.

func GetProperties

func GetProperties(sessionType uint8, userData *user.User, keys []string, cb func(err error, props map[string]interface{}))

GetProperties returns key and value pairs as a map.

[IMPORTANT] Properties are only primitive values and does not support reference type data such as array and map.
[IMPORTANT] If a value of a given key does not exist, the returned map will not contain the key without the value.
[IMPORTANT] The returned property value is an interface{}, in order to type assert safely, please use Diarkis' util package functions.
[IMPORTANT] The function communicates with another server internally.
[IMPORTANT] This function works on any server.

Error Cases

+--------------------------+-------------------------------------------------------------------------+
| Error                    | Reason                                                                  |
+--------------------------+-------------------------------------------------------------------------+
| Session ID is invalid    | The given session ID is not a valid session ID.                         |
| User is not a member     | The given user is not a member of the session.                          |
| Failed to get properties | Session is no longer available.                                         |
| Failed to get properties | Server-to-server communication failed.                                  |
|                          | Possible cause maybe server load, incorrectly setup server cluster etc. |
+--------------------------+-------------------------------------------------------------------------+

Parameters

sessionType - Session type of the session.
userData    - Session member user.
keys        - An array of property keys to fetch.
cb          - Callback to be invoked when the fetch operation is complete.
              func(err error, props map[string]interface{})
              err   - Error to inform if the fetch operation fails.
              props - A map of property keys and values.

Example

GetProperties(sessionType, userData, []string{ "someKey" }, func(err error, props map[string]interface{}) {

  if !ok {
    // handle error here
  }

  for key, v := range props {
    // If the value data type is an uint8, of course ;)
    value, ok := util.ToUint8(v)
  }
})

func GetProperty

func GetProperty(sessionType uint8, userData *user.User, key string, cb func(err error, value interface{}, exists bool))

GetProperty returns the value of the given key and if the key does not exist, the second return value will be a false.

[IMPORTANT] Properties are only primitive values and does not support reference type data such as array and map.
[IMPORTANT] The returned property value is an interface{}, in order to type assert safely, please use Diarkis' util package functions.
[IMPORTANT] The function communicates with another server internally.
[IMPORTANT] This function works on any server.

Error Cases

+------------------------+-------------------------------------------------------------------------+
| Error                  | Reason                                                                  |
+------------------------+-------------------------------------------------------------------------+
| Session ID is invalid  | The given session ID is not a valid session ID.                         |
| User is not a member   | The given user is not a member of the session.                          |
| Failed to get property | Session is no longer available.                                         |
| Failed to get property | Server-to-server communication failed.                                  |
|                        | Possible cause maybe server load, incorrectly setup server cluster etc. |
+------------------------+-------------------------------------------------------------------------+

Parameters

sessionType - Session type of the session.
userData    - Session member user.
key         - Property key.
cb          - Callback to be invoked when fetching the property is complete.
              func(err error, value interface{}, exists bool)
              err    - Error when fetching of the property fails.
              value  - Value of the property key.
              exists - If the property key is not found, it is false.

Example

GetProperty(sessionType, userData, "someKey", func(err error, value interface{}, exists bool)) {

	if err != nil {
		// handle error here...
	}

	if !exists {
		// key does not exist...
	}

	// If the value data type is an uint8, of course ;)
	v, ok := util.ToUint8(v)
})

func GetSessionID

func GetSessionID(sessionType uint8, userData *user.User) string

GetSessionID returns a session of the given session type that the given user is a member of.

[IMPORTANT] It returns an empty string if the user is not a member of any session by the given type.

[NOTE] If the user is not a member of any session of the given sessionType, it returns an empty string.

func GetSessionIDByUser

func GetSessionIDByUser(sessionType uint8, userData *user.User) (string, bool)

GetSessionIDByUser returns the session ID of the session that the user is member of.

[IMPORTANT] this function works only if the session exists on the same server.

[IMPORTANT] If the second returned value is false, it means that the user is not a member of any session by the given type.

func GetSessionInfo

func GetSessionInfo(sessionID string, cb func(err error, info *GetSessionInfoData))

GetSessionInfo returns the information of the session with callback.

[IMPORTANT] The function communicates with another server internally.
[IMPORTANT] This function works on any server.

Error Cases

+----------------------------+-------------------------------------------------------------------------+
| Error                      | Reason                                                                  |
+----------------------------+-------------------------------------------------------------------------+
| Session ID is invalid      | The given session ID is not a valid session ID.                         |
| Failed to get session info | Server-to-server communication failed.                                  |
|                            | Possible cause maybe server load, incorrectly setup server cluster etc. |
+----------------------------+-------------------------------------------------------------------------+

Parameters

sessionID - Session ID.
cb        - Callback to be invoked when the operation is complete.
            func(err error, info *GetSessionInfoData)
            err  - Error when the operation fails.
            info - The information of the session.

func IsAcceptError

func IsAcceptError(err error) bool

IsAcceptError returns true if the given error is or contain Accept error.

func IsInviteError

func IsInviteError(err error) bool

IsInviteError returns true if the given error is or contain Invite error.

func IsJoinError

func IsJoinError(err error) bool

IsJoinError returns true if the given error is or contain Join error.

func IsKickError

func IsKickError(err error) bool

IsKickError returns true if the given error is or contain Kick error.

func IsLeaveError

func IsLeaveError(err error) bool

IsLeaveError returns true if the given error is or contain Leave error.

func IsMemberError

func IsMemberError(err error) bool

IsMemberError returns true if the given error is or contain Member error.

func IsOwner

func IsOwner(sessionType uint8, userData *user.User, cb func(err error, isOwner bool))

IsOwner checks if the given user is the owner of the session or not.

[IMPORTANT] The owner user is used internally,
            and it may change when the current owner user disconnects or leaves the session.
[IMPORTANT] The function communicates with another server internally.
[IMPORTANT] This function works on any server.

Error Cases

+----------------------------------------------+---------------------------------------------------------------------------------------+
| Error                                        | Reason                                                                                |
+----------------------------------------------+---------------------------------------------------------------------------------------+
| Failed to ascertain if the user is the owner | The given user is not a member of the session or session being not available anymore. |
| Failed to ascertain if the user is the owner | Internal server-to-server communication failed due to either from server load         |
|                                              | and/or incorrectly setup Diarkis cluster.                                             |
+----------------------------------------------+---------------------------------------------------------------------------------------+

Parameters

sessionType - Session type.
userData    - Session member user to be checked if the user is the internal owner of the session or not.
cb          - Callback.
              func(err error, isOwner bool)
              err     - Error to indicate the failure of the operation.
              isOwner - If true, the given user is the internal owner of the session.

func IsOwnerError

func IsOwnerError(err error) bool

IsOwnerError returns true if the given error is or contain Owner error.

func IsPropertyGetError

func IsPropertyGetError(err error) bool

IsPropertyGetError returns true if the given error is or contain PropertyGet error.

func IsPropertySetError

func IsPropertySetError(err error) bool

IsPropertySetError returns true if the given error is or contain PropsetySet error.

func IsSendError

func IsSendError(err error) bool

IsSendError returns true if the given error is or contain Send error.

func IsSessionError

func IsSessionError(err error) bool

IsSessionError returns true if the given error is or contain NewSession error.

func JoinSessionByID

func JoinSessionByID(sessionType uint8, id string, userData *user.User, cb func(error))

JoinSessionByID joins a session as a member by session's type and ID.

[IMPORTANT] The function communicates with another server internally.
[IMPORTANT] This function works on any server.

Error Cases

+----------------+-------------------------------------------------------------------------------+
| Error          | Reason                                                                        |
+----------------+-------------------------------------------------------------------------------+
| Failed to join | Internal server-to-server communication failed due to either from server load |
|                | and/or incorrectly setup Diarkis cluster.                                     |
| Failed to join | Session is no longer available.                                               |
| Failed to join | User is rejected by On join callback check.                                   |
+----------------+-------------------------------------------------------------------------------+

Parameters

sessionType       - The session type.
id                - The session ID.
userData          - The user that will join the session.
cb                - Callback to be invoked when join operation completes regardless of success or failure.

func KickFromSession

func KickFromSession(sessionType uint8, sessionID string, targetUserID string, cb func(error))

KickFromSession kicks out a user from a session.

[IMPORTANT] The function communicates with another server internally.
[IMPORTANT] This function works on any server.

Error Cases

+----------------------+--------------------------------------------------------------------------------+
| Error                | Reason                                                                         |
+----------------------+--------------------------------------------------------------------------------+
| User is not a member | The target user to kick out is not a member of the session.                    |
| Kick out failed      | Session ID is invalid.                                                         |
|                      | The most likely cause is internal bug.                                         |
| Kick out failed      | Internal server-to-server communication failed due to either from server load. |
|                      | and/or incorrectly setup Diarkis cluster.                                      |
+----------------------+--------------------------------------------------------------------------------+

Parameters

sessionType  - Session type.
sessionID    - Session ID.
targetUserID - User ID to kick out.
cb           - Callback.

func KickFromSessionWithUserData

func KickFromSessionWithUserData(sessionType uint8, userData *user.User, targetUserID string, cb func(error))

KickFromSessionWithUserData kicks out a user from a session.

This gets sessionID out of userData and passes it to KickFromSession.

[IMPORTANT] The function communicates with another server internally.
[IMPORTANT] This function works on any server.

[NOTE] See the doc for session.KickFromSession for more Error Cases.

Error Cases

+-----------------+--------------------------------------+
| Error           | Reason                               |
+-----------------+--------------------------------------+
| Kick out failed | User is not a member of the session. |
+-----------------+--------------------------------------+

Parameters

sessionType  - Session type.
userData     - Session member user.
targetUserID - User ID to kick out.
cb           - Callback.

func LeaveSessionByID

func LeaveSessionByID(sessionType uint8, id string, userData *user.User, cb func(error))

LeaveSessionByID leaves from the session by its type and ID.

[IMPORTANT] The function communicates with another server internally.
[IMPORTANT] This function works on any server.

Error Cases

+-----------------------+-------------------------------------------------------------------------+
| Error                 | Reason                                                                  |
+-----------------------+-------------------------------------------------------------------------+
| Session ID is invalid | The given session ID is not a valid session ID.                         |
| User is not a member  | The given user is not a member of the session.                          |
| Failed to leave       | Session is no longer available.                                         |
| Failed to leave       | Server-to-server communication failed.                                  |
|                       | Possible cause maybe server load, incorrectly setup server cluster etc. |
+-----------------------+-------------------------------------------------------------------------+

Parameters

sessionType - The session type.
id          - The session ID.
userData    - The user that will leave from the session.
cb          - Callback to be invoked when leave operation completes regardless of success or failure.

func MessageTo

func MessageTo(sessionType uint8, sessionID string, senderUID string, recipientUIDs []string, ver uint8, cmd uint16, msg []byte) error

MessageTo sends a reliable message to specified member users with the given ver, cmd, recipient UIDs and message byte array.

[IMPORTANT] This function can be executed by any user as long as it is provided with a valid session ID..
[IMPORTANT] The function communicates with another server internally.
[IMPORTANT] This function works on any server.

Error Cases

+-----------------------+-------------------------------------------------+
| Error                 | Reason                                          |
+-----------------------+-------------------------------------------------+
| Session ID is invalid | The given session ID is not a valid session ID. |
| Session not found     | The session no longer exists.                   |
| User    not found     | A recipient was not found in the session.       |
+-----------------------+-------------------------------------------------+k

Parameters

sessionType   - Type of the session.
sessionID     - Session ID.
senderUID     - Sender user ID.
recipientUIDs - An array of recipient user IDs to send the message to.
ver           - Command ver to be used as the message command.
cmd           - Command ID to be used as the message command.
msg           - Message to be sent.

func SendInvite

func SendInvite(sessionType uint8, id string,
    userData *user.User, targetUserIDs []string,
    ver uint8, cmd uint16, message []byte,
    cb func(err error))

SendInvite sends an invitation to a user to join the session.

The invitation message (sessionType, sessionID, and custom invitation message) is sent to the user client device.

The user may join the session by accepting the invite via Join.

[IMPORTANT] Invitation does NOT guarantee the invited user to be able to join the session.
            If the session is full or no longer available when the invited user accepts the session,
            joining the session will fail.
[IMPORTANT] The function communicates with another server internally.
[IMPORTANT] This function works on any server.

Error Cases

+------------------------------+--------------------------------------------------------------------------------------+
| Error                        | Reason                                                                               |
+------------------------------+--------------------------------------------------------------------------------------+
| Must a member                | Only the member of the session may send an invitation.                               |
| Cannot invite yourself       | You may not invite yourself.                                                         |
| Failed to deliver invitation | Invitation failed to be delivered to the intended user. e.i. User is not found etc.  |
|                              | If you send invitations to multiple users and only one fails,                        |
|                              | the callback will return with an error.                                              |
+------------------------------+--------------------------------------------------------------------------------------+

Parameters

sessionType  - The session type.
id           - The session ID.
userData     - The member user of the session to send an invite.
targetUserID - The user ID to be sent the invitation to.
ver          - Command version of the invitation message to be sent.
cmd          - Command ID of the invitation message to be sent.
message      - Message of the invitation to be sent.
cb           - Callback to be invoked when the invitation is sent
               (not to the client device but when the server finishes the send operation).

func SetProperties

func SetProperties(sessionType uint8, userData *user.User, kvList []*PropertyKeyValue, cb func(err error))

SetProperties stores a collection of keys and their values to ticket as properties.

[IMPORTANT] If the same key exists, it overwrites the existing value of the same key.
[IMPORTANT] Properties are only primitive values and does not support reference type data such as array and map.
[IMPORTANT] If there is an error no properties will be set.
[IMPORTANT] This function is asynchronous.
[IMPORTANT] The function communicates with another server internally.
[IMPORTANT] This function works on any server.

Error Cases

+--------------------------+-------------------------------------------------------------------------+
| Error                    | Reason                                                                  |
+--------------------------+-------------------------------------------------------------------------+
| Session ID is invalid    | The given session ID is not a valid session ID.                         |
| User is not a member     | The given user is not a member of the session.                          |
| Failed to set properties | Session is no longer available.                                         |
| Failed to set properties | Server-to-server communication failed.                                  |
|                          | Possible cause maybe server load, incorrectly setup server cluster etc. |
+--------------------------+-------------------------------------------------------------------------+

Parameters

sessionType - Session type of the session.
userData    - Session member user.
kvList      - A list of property key and value pair to be set.
cb          - Callback to be invoked when the operation is completed.
              func(err error)
              err - Error if the operation fails.

func SetProperty

func SetProperty(sessionType uint8, userData *user.User, key string, value interface{}, cb func(err error, success bool))

SetProperty stores a key and a value as a property to the ticket.

[IMPORTANT] If the same key exists, it overwrites the existing value of the same key.
[IMPORTANT] Properties are only primitive values and does not support reference type data such as array and map.
[IMPORTANT] This function is asynchronous.
[IMPORTANT] The function communicates with another server internally.
[IMPORTANT] This function works on any server.

Error Cases

+------------------------+-------------------------------------------------------------------------+
| Error                  | Reason                                                                  |
+------------------------+-------------------------------------------------------------------------+
| Session ID is invalid  | The given session ID is not a valid session ID.                         |
| User is not a member   | The given user is not a member of the session.                          |
| Failed to set property | Session is no longer available.                                         |
| Failed to set property | Server-to-server communication failed.                                  |
|                        | Possible cause maybe server load, incorrectly setup server cluster etc. |
+------------------------+-------------------------------------------------------------------------+

Parameters

sessionType - Type of session.
userData    - Session member user.
key         - Property key.
value       - Property value to set.
cb          - Callback to be invoked when the operation is finished.
              func(err error, success bool)
              err     - If not nil, operation error out.
              success - If true, setting of the key and value was a success.

func SetPropertyIfNotExists

func SetPropertyIfNotExists(sessionType uint8, userData *user.User, key string, value interface{}, cb func(err error, success bool))

SetPropertyIfNotExists stores a key and a value as a property to the ticket if the same key does not exist.

[IMPORTANT] Properties are only primitive values and does not support reference type data such as array and map.
[IMPORTANT] This function is asynchronous.
[IMPORTANT] The function communicates with another server internally.
[IMPORTANT] This function works on any server.

Error Cases

+------------------------+-------------------------------------------------------------------------+
| Error                  | Reason                                                                  |
+------------------------+-------------------------------------------------------------------------+
| Session ID is invalid  | The given session ID is not a valid session ID.                         |
| User is not a member   | The given user is not a member of the session.                          |
| Failed to set property | Session is no longer available.                                         |
| Failed to set property | Server-to-server communication failed.                                  |
|                        | Possible cause maybe server load, incorrectly setup server cluster etc. |
| Failed to set property | The property with the same key already exists.                          |
+------------------------+-------------------------------------------------------------------------+

Parameters

sessionType - Type of session.
userData    - Session member user.
key         - Property key.
value       - Property value to set.
cb          - Callback to be invoked when the operation is finished.
              func(err error, success bool)
              err     - If not nil, operation error out.
              success - If true, setting of the key and value was a success.

func Setup

func Setup()

Setup must be invoked before calling diarkis.Start in order to use session package.

type FindOwnerData

FindOwnerData represents internally used data

type FindOwnerData struct {
    SID string `json:"sid"`
}

type GetMemberData

GetMemberData represents internally used data

type GetMemberData struct {
    ID   string   `json:"id"`
    List []string `json:"list"`
}

type GetSessionInfoData

GetSessionInfoData represents internally used data

type GetSessionInfoData struct {
    ID             string   `json:"id"`
    SessionType    uint8    `json:"sessionType"`
    CurrentMembers uint16   `json:"currentMembers"`
    MaxMembers     uint16   `json:"maxMembers"`
    MemberIDs      []string `json:"memberIDs"`
    OwnerID        string   `json:"ownerID"`
}

type IsOwnerData

IsOwnerData represents internally used data

type IsOwnerData struct {
    ID  string `json:"id"`
    UID string `json:"uid"`
}

type IsOwnerReturnData

IsOwnerReturnData represents internally used data

type IsOwnerReturnData struct {
    IsOwner bool `json:"isOwner"`
}

type JoinSessionData

JoinSessionData represents internally used data

type JoinSessionData struct {
    ID       string                 `json:"id"`
    UID      string                 `json:"uid"`
    SID      string                 `json:"sid"`
    MeshAddr string                 `json:"meshAddr"`
    UserData map[string]interface{} `json:"userData"`
}

type LeaveSessionData

LeaveSessionData represents internally used data

type LeaveSessionData struct {
    Type uint8  `json:"sessionType"`
    ID   string `json:"id"`
    UID  string `json:"uid"`
    SID  string `json:"sid"`
}

type LeaveSessionReturnData

LeaveSessionReturnData represents internally used data

type LeaveSessionReturnData struct {
    LockKey string `json:"lockKey"`
}

type MessageData

MessageData represents internally used broadcast message data

type MessageData struct {
    ID         string   `json:"id"`
    Ver        uint8    `json:"ver"`
    Cmd        uint16   `json:"cmd"`
    Msg        []byte   `json:"msg"`
    MemberSIDs []string `json:"memberSIDs"`
}

type PropertiesData

PropertiesData represents internally used data

type PropertiesData struct {
    ID     string              `json:"id"`
    KVList []*PropertyKeyValue `json:"kvList"`
}

type PropertyData

PropertyData represents internally used data

type PropertyData struct {
    ID    string      `json:"id"`
    Key   string      `json:"key"`
    Value interface{} `json:"value"`
    Flag  bool        `json:"flag"`
}

type PropertyKeyValue

PropertyKeyValue represents session property key value pair.

type PropertyKeyValue struct {
    Key   string      `json:"key"`
    Value interface{} `json:"value"`
}

type PropertyReturnData

PropertyReturnData represents internally used data

type PropertyReturnData struct {
    Success bool        `json:"success"`
    Key     string      `json:"key"`
    Value   interface{} `json:"value"`
}

type Session

Session represents session.

A session allows multiple users join a members up to the pre-determines.

All session members may send and receive messages and set and get shared properties within the session.

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

func GetSessionByID

func GetSessionByID(id string) (*Session, bool)

GetSessionByID corresponding session to passed id.

[IMPORTANT] this function works only if the session exists on the same server.

func NewSession

func NewSession(userData *user.User, sessionType uint8, maxMembers uint16, ttl uint16) (*Session, error)

NewSession creates a new session instance with the given session type.

[IMPORTANT] The user given becomes a member of the session automatically.
[IMPORTANT] You may not create a new session if the server is in offline state.

Error Cases

+-----------------------------+------------------------------------------------------------------------------------------------------+
| Error                       | Reason                                                                                               |
+-----------------------------+------------------------------------------------------------------------------------------------------+
| Server is offline           | No session can be created on a server that is in offline state due to receiving SIGTERM.             |
| Max member of session       | Max member of session must be greater than 1.                                                        |
| Failed to create session ID | When the server fails to generate UUID v4 ID string and/or invalid internal server address is found. |
+-----------------------------+------------------------------------------------------------------------------------------------------+

When it fails to generate session ID, it most likely is caused by the incorrect setup of Diarkis server cluster or a server.

Parameters

userData    - A user that creates a new session and becomes the first member.
sessionType - A session type that the new session will be identified by.
              A user cannot be a member of multiple sessions with the same session type.
maxMembers  - Maximum allowed number of session members.
ttl         - TTL of the session instance when it becomes empty (no members) in seconds.
              TTL count is not exact that the deletion of an empty session may happen earlier or later than TTL.
              Value smaller than 30s for TTL will automatically be changed to 30s.

func (*Session) GetID

func (s *Session) GetID() string

GetID returns the session ID.

func (*Session) GetMemberIDs

func (s *Session) GetMemberIDs() []string

GetMemberIDs returns an array of member IDs ordered by the time they joined.

func (*Session) GetMemberMeshAddrByUID

func (s *Session) GetMemberMeshAddrByUID(uid string) string

GetMemberMeshAddrByUID returns a mesh address of a member.

Returns an empty string if the member is not found or invalid.

func (*Session) GetMemberMeshAddrList

func (s *Session) GetMemberMeshAddrList() []string

GetMemberMeshAddrList returns an array of internal server address of each user.

func (*Session) GetMemberSIDByUID

func (s *Session) GetMemberSIDByUID(uid string) string

GetMemberSIDByUID returns the member's SID.

It returns and empty string if the member is not found or invalid.

func (*Session) GetMemberSIDs

func (s *Session) GetMemberSIDs() []string

GetMemberSIDs returns an array of member SIDs.

func (*Session) GetMemberUsers

func (s *Session) GetMemberUsers() []*user.User

GetMemberUsers returns an array of member user copies.

[IMPORTANT] The return array contains copies of member users.

func (*Session) GetOwnerUser

func (s *Session) GetOwnerUser() (*user.User, bool)

GetOwnerUser returns the ticket owner user.

[IMPORTANT] Returned owner user is NOT a copy.

func (*Session) GetProperties

func (s *Session) GetProperties(keys []string) map[string]interface{}

GetProperties returns key and value pairs as a map.

Properties are only primitive values and does not support reference type data such as array and map.

If a value of a given key does not exist, the returned map will have a nil as a value of the key.

The returned property value is an interface{}, in order to type assert safely, please use Diarkis' util package functions.

Example:

values, ok := r.GetProperties([]string{ "someKey" })

if !ok {
  // handle error here
}

for key, v := range values {
  // If the value data type is an uint8, of course ;)
  value, ok := util.ToUint8(v)
}

func (*Session) GetProperty

func (s *Session) GetProperty(key string) (interface{}, bool)

GetProperty returns the value of the given key and if the key does not exist, the second return value will be a false.

Properties are only primitive values and does not support reference type data such as array and map.

The returned property value is an interface{}, in order to type assert safely, please use Diarkis' util package functions.

Example:

v, ok := r.GetProperty("someKey")

if !ok {
  // handle error here
}

// If the value data type is an uint8, of course ;)
v, ok := util.ToUint8(v)

func (*Session) GetType

func (s *Session) GetType() uint8

GetType returns the type of the session.

func (*Session) IsJoinAllowed

func (s *Session) IsJoinAllowed(memberCnt int) bool

IsJoinAllowed returns true if the session has room to add another user.

func (*Session) IsMemberByUID

func (s *Session) IsMemberByUID(uid string) bool

IsMemberByUID returns true if the given user ID is the UID of the session member user.

func (*Session) SetOnDelete

func (s *Session) SetOnDelete(cb func(id string)) bool

SetOnDelete assigns a callback on session deletion that is invoked before the session is deleted.

[IMPORTANT] Only one callback can be assigned to a session.

func (*Session) SetOnDeleted

func (s *Session) SetOnDeleted(cb func(id string)) bool

SetOnDeleted assigns a callback on session deletion that is invoked after the session is deleted.

[IMPORTANT] Only one callback can be assigned to a session.

func (*Session) SetOnJoin

func (s *Session) SetOnJoin(cb func(id string, userData *user.User) bool) bool

SetOnJoin assigns a callback on session to be invoked when a new member is attempting to join the session.

The callback returns a bool and if you return false, the user will be rejected and will not join the session.

[IMPORTANT] Only one callback can be assigned to a session.
[IMPORTANT] userData passed to the callback is a copy of the actual user is attempting to join.

func (*Session) SetOnJoined

func (s *Session) SetOnJoined(cb func(id string, userData *user.User)) bool

SetOnJoined assigns a callback on session to be invoked when a new member joins.

[IMPORTANT] Only one callback can be assigned to a session.
[IMPORTANT] If you need to use Broadcast in the callback,
            you must pass the owner user to Broadcast because the newly joined user does not have the session ID yet.
[IMPORTANT] userData passed to the callback is a copy of the actual user that joined.

func (*Session) SetOnLeft

func (s *Session) SetOnLeft(cb func(id string, userData *user.User)) bool

SetOnLeft assigns a callback on session to be invoked when a member of user leaves the session.

[IMPORTANT] Only one callback can be assigned to a session.
[IMPORTANT] If you need to use Broadcast in the callback,
            you must pass the owner user to Broadcast because the user left no longer has the session ID.
[IMPORTANT] userData passed to the callback is a copy of the actual user that left.

func (*Session) SetOnTick

func (s *Session) SetOnTick(interval uint16, cb func(id string)) bool

SetOnTick assigns a callback to be invoked at every given interval.

[IMPORTANT] A single callback may be assigned per tick interval.
            You may not assign multiple callbacks a tick with the same interval.

Parameters

interval - Tick interval in seconds.
cb       - Callback to be invoked at every tick.

func (*Session) SetOnTickStop

func (s *Session) SetOnTickStop(interval uint16, cb func(id string)) bool

SetOnTickStop assigns a callback to be invoked when a tick of the session stops.

[IMPORTANT] Only one callback can be assigned to a session.

func (*Session) SetProperties

func (s *Session) SetProperties(data map[string]interface{}) error

SetProperties stores a collection of keys and their values to session.

If the same key exists, it overwrites the existing value of the same key.

Properties are only primitive values and does not support reference type data such as array and map.

func (*Session) SetProperty

func (s *Session) SetProperty(key string, value interface{})

SetProperty stores a key and value data to session.

If the same key exists, it overwrites the existing value of the same key.

Properties are only primitive values and does not support reference type data such as array and map.

func (*Session) SetPropertyIfNotExists

func (s *Session) SetPropertyIfNotExists(key string, value interface{}) bool

SetPropertyIfNotExists stores a key and value data to session if the same key does not exist.

Properties are only primitive values and does not support reference type data such as array and map.

func (*Session) StopAllTicks

func (s *Session) StopAllTicks() bool

StopAllTicks stops all tick loops.

func (*Session) UpdateProperties

func (s *Session) UpdateProperties(data map[string]interface{}, cb func(bool, interface{}, interface{}) interface{})

UpdateProperties changes the existing property values of session.

The callback is invoked while the internal lock is still held, locking inside the callback may cause mutex deadlock.

Properties are only primitive values and does not support reference type data such as array and map.

data - A map of key and value pair to be stored as properties.
cb   - Callback to be invoked on every key and value pair to handle the update.
       func(exists bool, storedValue interface{}, updateValue interface{}) (updatedValue interface{})
         - exists      - Indicates if the same key already exists or not
         - storedValue - Existing value that is stored as a property. If the key does not exist it is a nil.
         - updateValue - The value to be used to update/replace or set.

func (*Session) UpdateProperty

func (s *Session) UpdateProperty(key string, value interface{}, cb func(bool, interface{}, interface{}) interface{})

UpdateProperty changes the existing property value of session.

The callback is invoked while the internal lock is still held, locking inside the callback may cause mutex deadlock.

Properties are only primitive values and does not support reference type data such as array and map.

key   - A key of the property to be updated.
value - A value of the property to be updated with.
cb    - Callback to be invoked on every key and value pair to handle the update.
        func(exists bool, storedValue interface{}, updateValue interface{}) (updatedValue interface{})
         - exists      - Indicates if the same key already exists or not
         - storedValue - Existing value that is stored as a property. If the key does not exist it is a nil.
         - updateValue - The value to be used to update/replace or set.

type UserData

UserData represents internally used user data update [IMPORTANT] UserData is a copy of the user data when the user joins the session.

type UserData struct {
    SessionID        string                 `json:"id"`
    UserID           string                 `json:"ID"`
    SID              string                 `json:"SID"`
    PublicAddr       string                 `json:"PublicAddr"`
    PrivateAddrBytes []byte                 `json:"PrivateAddrBytes"`
    MeshAddr         string                 `json:"meshAddr"`
    UserData         map[string]interface{} `json:"userData"`
}

func (*UserData) CreateCopyUser

func (sessionUser *UserData) CreateCopyUser() *user.User

CreateCopyUser creates a copy of the user data from the session user data.

type UserSessionData

UserSessionData represents a set of session information that contains session type and ID.

type UserSessionData struct {
    Type uint8
    ID   string
}

func GetSessionDataByUser

func GetSessionDataByUser(userData *user.User) []UserSessionData

GetSessionDataByUser returns an array of UserSessionData{ Type, ID } that the given user is member of.

[NOTE] If the user is not a member of any session, the returned array will be empty