service

package
v0.0.0-...-25a5272 Latest Latest
Warning

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

Go to latest
Published: Apr 30, 2022 License: Unlicense Imports: 27 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// BridgeMessageSent is event type for message sent event.
	BridgeMessageSent = BridgeEventType(MessageSent)

	// BridgeUserLeft is event type fired when user's leaving chat.
	BridgeUserJoin = BridgeEventType("user-join")

	// BridgeUserJoin is event type fired when user's joining chat.
	BridgeUserLeft = BridgeEventType("user-left")
)

Types for bridge events.

View Source
const (

	// ConfigSystemFile is the path for default system wide
	// config file. It is the first config file loaded
	// by the szmaterlok.
	ConfigSystemFile = "/etc/szmaterlok/config.env"

	// ConfigLocalFile is the path for the default local
	// config file. It is the second config file loaded
	// by the szmaterlok. Any configure variables saved
	// in this file will overwrite config variables from
	// ConfigSystemFile.
	ConfigLocalFile = ".env"
)

Pathts of configuration files.

View Source
const (

	// ConfigAddressVarName is env variable for listening address.
	ConfigAddressVarName = "S8K_ADDR"

	// ConfigSessionSecretVarName is env variable for secret session password.
	ConfigSessionSecretVarName = "S8K_SESSION_SECRET"

	// ConfigTokenizerVarName is env variable for tokenizer type used by szmaterlok.
	ConfigTokenizerVarName = "S8K_TOKENIZER"

	// ConfigDatabasePathVarName is env variable for database connection string
	// (filepath to sqlite file).
	ConfigDatabasePathVarName = "S8K_DB"

	// ConfigLastMessagesBufferSizeVarName is env variable for size of last messages buffer.
	ConfigLastMessagesBufferSizeVarName = "S8K_LAST_MSG_BUFFER_SIZE"

	// ConfigMaxMessageSizeVarName is env variable for maximum message size.
	ConfigMaxMessageSizeVarName = "S8K_MAX_MSG_SIZE"
)

Names of configuration environmental variables.

View Source
const (

	// ConfigAddressDefaultVal is default value for address
	// configuration variable.
	ConfigAddressDefaultVal = "0.0.0.0:8080"

	// ConfigSessionSecretDefaultVal is default value for session
	// secret variable. Remember to change this value during
	// production deployment of szmaterlok!
	ConfigSessionSecretDefaultVal = "secret_password"

	// ConfigTokenizerSimple is name for simple tokenizer backend type.
	ConfigTokenizerSimple = "simple"

	// ConfigTokenizerAge is name for age tokenizer backend type.
	ConfigTokenizerAge = "age"

	// ConfigTokenizerAES is name for AES tokenizer backend type.
	ConfigTokenizerAES = "aes"

	// ConfigTokenizerDefaultVal is default value for tokenizer type.
	ConfigTokenizerDefaultVal = ConfigTokenizerSimple

	// ConfigDatabasePathDefaultVal is default filepath for sqlite3 szmaterlok
	// database.
	ConfigDatabasePathDefaultVal = "szmaterlok.sqlite3"

	// ConfigLastMessagesBufferSizeDefaultVal is default value for maximal
	// last message buffer size.
	ConfigLastMessagesBufferSizeDefaultVal = 10

	// ConfigMaxMessageSizeDefaultVal is default value for maximum
	// message size (in bytes).
	ConfigMaxMessageSizeDefaultVal = 255
)

Default values for configuration variables.

View Source
const MessageSent = "message-sent"

MessageSent is SSE event type for message sent event.

Variables

View Source
var ErrInvalidTokenizerType = errors.New("session: invalid tokenizer type name")
View Source
var ErrMissingSessionToken = errors.New("session: missing token")
View Source
var ErrNoSuchUser = errors.New("state: there is no such user")
View Source
var ErrSessionStateExpire = errors.New("session state expired")

Functions

func ConfigLoad

func ConfigLoad(ctx context.Context) error

ConfigLoad loads all the config files with environmental variables.

func ConfigRead

func ConfigRead(c *ConfigVariables) error

ConfigRead overwrites fields of given config variables with their environmental correspondent values (when they're set).

func ContextWithLastEventID

func ContextWithLastEventID(ctx context.Context, lastEventID string) context.Context

ContextWithLastEventID stores given event ID within the context.

func HandlerChat

func HandlerChat(f fs.FS) http.HandlerFunc

HandlerChat renders chat application view of szmaterlok.

func HandlerIndex

func HandlerIndex(f fs.FS) http.HandlerFunc

HandlerIndex renders main page of szmaterlok.

func HandlerLogout

func HandlerLogout(cs *SessionCookieStore) http.HandlerFunc

func HandlerOnlineUsers

func HandlerOnlineUsers(log *logrus.Logger, store AllChatUsersStore) http.HandlerFunc

HandlerOnlineUsers sends list of online users, which are using chat.

func HandlerSendMessage

func HandlerSendMessage(deps HandlerSendMessageDependencies) http.HandlerFunc

HandlerSendMessage handles sending message to all current listeners.

func HandlerStream

func HandlerStream(deps HandlerStreamDependencies) http.HandlerFunc

HandlerStream is SSE event stream handler, which sends event notifications to clients. It requires authentication.

See SessionRequired middleware.

func LastEventIDMiddleware

func LastEventIDMiddleware(next http.Handler) http.Handler

LastEventIDMiddleware injects Last-Event-ID header value into the requests context.

func LoggerDefault

func LoggerDefault() *logrus.Logger

LoggerDefault return default general purpose logger that can be used everywhere across project.

It should be initialized once and then reused or modified in different areas.

func NewRouter

func NewRouter(deps RouterDependencies) *chi.Mux

NewRouter returns new configured chi mux router.

func SessionLoginGuard

func SessionLoginGuard(cs *SessionCookieStore, rediretUri string) func(http.Handler) http.Handler

SessionLoginGuard guards given handler from being accessed with request which contains valid session. If any valid session exists, client is being redirect to given rediretUri.

func SessionRequired

func SessionRequired(cs *SessionCookieStore) func(http.Handler) http.Handler

SessionRequired is http middleware which checks for presence of session state in current request. It return request without auth header set or with invalid value of session token.

If token is present, SessionRequired saves given token within request context. It can be retrieved with SessionContextState function.

Types

type AllChatUsersStore

type AllChatUsersStore interface {

	// AllChatUsers returns all online users which are currently using chat.
	AllChatUsers(ctx context.Context) ([]OnlineChatUser, error)
}

AllChatUsersStore stores information about current online users.

type Bridge

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

Bridge is asynchronous queue for events. It can process events from different sources spread all across szmaterlok application and handles them with event hooks represented as event handlers.

Single event type can have multiple event handlers.

func NewBridge

func NewBridge(ctx context.Context, args BridgeBuilder) *Bridge

NewBridge is constructor for event bridge. It returns default instance of event bridge.

func (*Bridge) SendEvent

func (b *Bridge) SendEvent(evt BridgeEvent)

SendEvent sends event to event bridge. It blocks, so it's a good idea to run it in a separate goroutine.

func (*Bridge) Shutdown

func (b *Bridge) Shutdown(ctx context.Context)

Shutdown closes event bridge and waits for current events being processed to finish.

type BridgeBuilder

type BridgeBuilder struct {
	Handler BridgeEventHandler
	Logger  *logrus.Logger
	Storage BridgeStorage
}

BridgeBuilder holds arguments for building event bridge.

type BridgeEvent

type BridgeEvent struct {
	// Name is event type.
	Name BridgeEventType `json:"type"`

	// ID is unique event identifier.
	ID string `json:"id"`

	// CreatedAt is date of event creation expressed
	// as unix epoch.
	CreatedAt int64 `json:"createdAt"`

	// Headers holds event metadata such as. For
	// example: one's could use headers to store
	// event data content type.
	Headers BridgeHeaders `json:"headers"`

	// Data sent or stored with event.
	Data []byte `json:"data"`
}

BridgeEvent is single event data model and commont interface for all events.

type BridgeEventHandler

type BridgeEventHandler interface {
	// EventHook can implement any generic operation which uses
	// data from BridgeEvent type.
	EventHook(context.Context, BridgeEvent)
}

BridgeEventHandler implements behaviour for dealing with events from szmaterlok event bridge.

type BridgeEventHandlerFunc

type BridgeEventHandlerFunc func(context.Context, BridgeEvent)

BridgeEventHandlerFunc is functional interface of BridgeEventHandler.

func StateUserJoinHook

func StateUserJoinHook(log *logrus.Logger, s *StateOnlineUsers) BridgeEventHandlerFunc

StateUserJoinHook adds new user to state online users storage when such joins the chat.

func StateUserLeftHook

func StateUserLeftHook(log *logrus.Logger, s *StateOnlineUsers) BridgeEventHandlerFunc

StateUserLeftHook removes user from state online users storage when such lefts the chat.

func (BridgeEventHandlerFunc) EventHook

func (f BridgeEventHandlerFunc) EventHook(ctx context.Context, evt BridgeEvent)

type BridgeEventProducer

type BridgeEventProducer[T any] struct {
	EventBridge *Bridge
	Type        BridgeEventType
	Log         *logrus.Logger
	Clock
}

BridgeEventProducer publishes events with given T type to event bridge.

func (*BridgeEventProducer[T]) SendEvent

func (p *BridgeEventProducer[T]) SendEvent(ctx context.Context, id string, evt T)

SendEvent publishes event with given data of T type and unique ID.

type BridgeEventRouter

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

BridgeEventRouter delegates different event types into their associated hook handlers.

func NewBridgeEventRouter

func NewBridgeEventRouter() *BridgeEventRouter

func (*BridgeEventRouter) EventHook

func (r *BridgeEventRouter) EventHook(ctx context.Context, evt BridgeEvent)

func (*BridgeEventRouter) Hook

Hook adds given event handler to hook list for given event type. Given hook will be fired when router receives new event with matching event type.

All hooks should be added before mounting event router to bridge.

type BridgeEventType

type BridgeEventType string

BridgeEventType represents event name by which events can be grouped by. Events of one type should have the same data scheme.

const BridgeEventGlob BridgeEventType = "*"

BridgeEventGlob matches all event types. It can be used to listen to all possible events.

type BridgeHeaders

type BridgeHeaders map[string]string

BridgeHeaders store event store metadata.

func (BridgeHeaders) Get

func (h BridgeHeaders) Get(key string) string

Get returns value for given key. If there is no value associated with given key, get returns empty string.

type BridgeMessageHandler

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

BridgeMessageHandler handles sending, subscribing and receiving of message-sent type events.

func NewBridgeMessageHandler

func NewBridgeMessageHandler(log *logrus.Logger) *BridgeMessageHandler

NewBridgeMessageHandler is default and safe constructor for BridgeMessageHandler.

func (*BridgeMessageHandler) EventHook

func (a *BridgeMessageHandler) EventHook(_ context.Context, evt BridgeEvent)

EventHook for SSE events sent to browsers.

func (*BridgeMessageHandler) Subscribe

func (a *BridgeMessageHandler) Subscribe(ctx context.Context, req MessageSubscribeRequest) func()

Subscribe given ID for SSE events. Returns unsubscribe func.

type BridgeStorage

type BridgeStorage interface {
	// StoreEvent stores given bridge event in event storage.
	StoreEvent(context.Context, BridgeEvent) error
}

BridgeStorage pushes events to event store.

type ChatUser

type ChatUser struct {
	ID       string `json:"id"`
	Nickname string `json:"nickname"`
}

ChatUser is author of single message sent.

type Clock

type Clock interface {

	// Now returns current time.
	Now() time.Time
}

Clock is system clock.

type ClockFunc

type ClockFunc func() time.Time

ClockFunc is functional interface of Clock.

func (ClockFunc) Now

func (f ClockFunc) Now() time.Time

type ConfigVariables

type ConfigVariables struct {
	// Address is combination of IP addres and port
	// which is used for listening to TCP/IP connections.
	Address string

	// Tokenizer is name of tokenizer type backend that should be
	// used by application.
	Tokenizer string

	// SessionSecret is secret password which is used to encrypt
	// and decrypt session state data if tokenizer age was chose.
	SessionSecret string

	// Database holds connection string for szmaterlok event storage.
	Database string

	// LastMessagesBufferSize describes maximal number stored in last
	// messages buffer that is sent to the users, when they're joining chat.
	LastMessagesBufferSize int

	// MaximumMessageSize is maximal number of runes for single message.
	MaximumMessageSize int
}

ConfigVariables represents state read from environmental variables, which are used for configuration of szmaterlok.

func ConfigDefault

func ConfigDefault() ConfigVariables

ConfigDefault returns default configuration for szmaterlok.

type EventAnnouncer

type EventAnnouncer struct {
	MessageNotifier

	UserJoinProducer *BridgeEventProducer[EventUserJoin]
	UserLeftProducer *BridgeEventProducer[EventUserLeft]

	Clock
	IDGenerator
}

EventAnnouncer wraps MessageNotifier and user activities producers and announces user presence to every event listener during single subscribe and unsubscribe action.

func (*EventAnnouncer) Subscribe

func (ea *EventAnnouncer) Subscribe(ctx context.Context, args MessageSubscribeRequest) func()

Subscribe given ID for SSE events. Returns unsubscribe func.

type EventSentMessage

type EventSentMessage struct {
	ID      string    `json:"id"`
	From    ChatUser  `json:"from"`
	Content string    `json:"content"`
	SentAt  time.Time `json:"sentAt"`
}

EventSentMessage is model for event of single sent message by client to all listeners.

type EventUserJoin

type EventUserJoin struct {
	ID       string    `json:"id"`
	User     ChatUser  `json:"user"`
	JoinedAt time.Time `json:"joinedAt"`
}

EventUserJoin is model for event of single user joining chat.

type EventUserLeft

type EventUserLeft struct {
	ID     string    `json:"id"`
	User   ChatUser  `json:"user"`
	LeftAt time.Time `json:"leftAt"`
}

EventUserJoin is model for event of single user leaving chat.

type HandlerLoginDependencies

type HandlerLoginDependencies struct {
	StateFactory *SessionStateFactory
	Logger       *logrus.Logger
	SessionStore *SessionCookieStore
}

HandlerLoginDependencies holds behavioral dependencies for login http handler.

type HandlerSendMessageDependencies

type HandlerSendMessageDependencies struct {
	MaxMessageSize int
	Sender         *BridgeEventProducer[EventSentMessage]
	IDGenerator
	Clock
}

HandlerLoginDependencies holds behavioral dependencies for http handler for sending messages.

type HandlerStreamDependencies

type HandlerStreamDependencies struct {
	MessageNotifier
	IDGenerator
	Clock
}

HandlerStreamDependencies holds arguments for HandlerStream http handler.

type IDGenerator

type IDGenerator interface {

	// GenerateID return unique ID.
	GenerateID() string
}

IDGenerator generates unique IDs.

type IDGeneratorFunc

type IDGeneratorFunc func() string

IDGeneratorFunc is functional interface of IDGenerator.

func (IDGeneratorFunc) GenerateID

func (f IDGeneratorFunc) GenerateID() string

type LastMessagesBuffer

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

LastMessagesBuffer keeps fixed number of messages that can be send to users to give them a little brief overview about current discussion.

func NewLastMessagesBuffer

func NewLastMessagesBuffer(size int, log *logrus.Logger) *LastMessagesBuffer

NewLastMessagesBuffer returns last message buffer of given size.

func (*LastMessagesBuffer) EventHook

func (b *LastMessagesBuffer) EventHook(ctx context.Context, evt BridgeEvent)

EventHook listens for message-sent events and appends them to the last messages circular buffer.

func (*LastMessagesBuffer) LastMessages

func (b *LastMessagesBuffer) LastMessages(ctx context.Context, lastMessageID string) []EventSentMessage

LastMessages returns all messages stored in LastMessagesBuffer that happened after event with given last message ID.

type LoggerLogFormatter

type LoggerLogFormatter struct {
	*logrus.Logger
}

LoggerLogFormatter is adapter which implements chi LogFormatter interface for logrus Logger.

func (*LoggerLogFormatter) NewLogEntry

func (log *LoggerLogFormatter) NewLogEntry(r *http.Request) middleware.LogEntry

NewLogEntry returns local LogEntry instance for the scope of given request.

type MessageCircularBuffer

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

MessageCircularBuffer is thread-safe data structure which holds fixed number of events. When buffer is full, push overwrites oldest item.

func NewMessageCircularBuffer

func NewMessageCircularBuffer(size int) *MessageCircularBuffer

NewMessageCircularBuffer returns address of circular buffer with given size.

func (*MessageCircularBuffer) BufferedEvents

func (mb *MessageCircularBuffer) BufferedEvents(ctx context.Context) []EventSentMessage

BufferedEvents returns all of events stored in the buffer.

func (*MessageCircularBuffer) PushEvent

func (mb *MessageCircularBuffer) PushEvent(ctx context.Context, evt EventSentMessage)

PushEvent appends given sent message event to the circular buffer. If buffer is full: push overwrites oldest item.

type MessageNotifier

type MessageNotifier interface {
	// Subscribe given ID for SSE events. Returns unsubscribe func.
	Subscribe(ctx context.Context, args MessageSubscribeRequest) func()
}

MessageNotifier sends SSE events notifications to client.

type MessageNotifierWithBuffer

type MessageNotifierWithBuffer struct {
	Notifier MessageNotifier
	Buffer   *LastMessagesBuffer
	Logger   *logrus.Logger
}

MessageNotifierWithBuffer is adapter for MessageNotifier which sends messages from last messages buffer to subscribed clients.

func (*MessageNotifierWithBuffer) Subscribe

func (m *MessageNotifierWithBuffer) Subscribe(ctx context.Context, args MessageSubscribeRequest) func()

Subscribe given ID for SSE events. Returns unsubscribe func.

type MessageSubscribeRequest

type MessageSubscribeRequest struct {
	// ID is chat (channel, user or any other chat entity) ID.
	ID string

	// RequestID is unique request ID. One client, with the same ID,
	// can have multiple request IDs.
	RequestID string

	// Channel for sending SSE events.
	Channel chan<- sse.Event
}

MessageSubscribeRequest holds arguments for subscribe method of MessageNotifier.

type OnlineChatUser

type OnlineChatUser struct {
	ID       string `json:"id"`
	Nickname string `json:"nickname"`
}

OnlineChatUser holds information about single user, which is currently using chat

type RouterDependencies

type RouterDependencies struct {
	Logger       *logrus.Logger
	SessionStore *SessionCookieStore
	Bridge       *Bridge

	MaximumMessageSize int

	AllChatUsersStore
	MessageNotifier
	IDGenerator
	Clock
}

RouterDependencies holds all configurated dependencies for new http router.

type SessionAESTokenizer

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

SessionAESTokenizer implements stateless SessionTokenizer interface with AES/CFB encryption.

func NewSessionAESTokenizer

func NewSessionAESTokenizer(secret []byte) (*SessionAESTokenizer, error)

NewSessionAESTokenizer returns AES session tokenizer. It is only safe constructor and the default one also.

The secret argument should be the AES key, either 16, 24, or 32 bytes to select AES-128, AES-192, or AES-256.

func (*SessionAESTokenizer) TokenDecode

func (st *SessionAESTokenizer) TokenDecode(token string) (*SessionState, error)

TokenDecode decodes given string token into valid session state.

func (*SessionAESTokenizer) TokenEncode

func (st *SessionAESTokenizer) TokenEncode(state SessionState) (string, error)

TokenEncode returns tokenized string which represents session state and can be decoded with the same interface implementation.

type SessionAgeTokenizer

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

SessionAgeTokenizer encodes and decodes session state token.

func NewSessionAgeTokenizer

func NewSessionAgeTokenizer(secret string) (*SessionAgeTokenizer, error)

NewSessionAgeTokenizer returns SessionAgeTokenizer which encrypts and decrypts tokens with given secret. Make sure secret is long enough and has high entropy.

func (*SessionAgeTokenizer) TokenDecode

func (st *SessionAgeTokenizer) TokenDecode(token string) (*SessionState, error)

TokenDecode decodes given base64 encoded and encrypted token into SessionState.

func (*SessionAgeTokenizer) TokenEncode

func (st *SessionAgeTokenizer) TokenEncode(state SessionState) (string, error)

TokenEncode encodes given session state into encrypted and base64 encoded token string, which can be used to safely store session state in users browser.

type SessionCookieSetRequest

type SessionCookieSetRequest struct {
	Writer    http.ResponseWriter
	Request   *http.Request
	Tokenizer *SessionTokenizer
	State     SessionState
	Clock
}

SessionCookieSetRequest contains dependencies and arguments for saving session cookie.

type SessionCookieStore

type SessionCookieStore struct {
	// ExpirationTime of http cookie. It can differ from session
	// state expiration date, but session state's one is more
	// important. Valid cookie with expired session state will be
	// invalid.
	ExpirationTime time.Duration

	// Tokenizer handles encoding and decoding of session state.
	Tokenizer SessionTokenizer

	// Clock returns current time.
	Clock
}

SessionCookieStore handles save and read operation of session state token within http cookies.

func (*SessionCookieStore) ClearState

func (cs *SessionCookieStore) ClearState(w http.ResponseWriter)

ClearState deletes current session state stored in http cookies.

func (*SessionCookieStore) SaveSessionState

func (cs *SessionCookieStore) SaveSessionState(
	w http.ResponseWriter, s SessionState,
) error

SaveSessionState overwrites szmaterlok session cookie with given SessionState.

func (*SessionCookieStore) SessionState

func (cs *SessionCookieStore) SessionState(r *http.Request) (*SessionState, error)

SessionState returns current session state retrieved from http cookies.

type SessionSimpleTokenizer

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

SessionSimpleTokenizer is a simple key/value storage for string tokens and session state of users.

func NewSessionSimpleTokenizer

func NewSessionSimpleTokenizer() *SessionSimpleTokenizer

NewSessionSimpleTokenizer is default and safe constructor for SessionSimpleTokenizer.

func (*SessionSimpleTokenizer) TokenDecode

func (t *SessionSimpleTokenizer) TokenDecode(token string) (*SessionState, error)

TokenDecode decodes given string token into valid session state.

func (*SessionSimpleTokenizer) TokenEncode

func (t *SessionSimpleTokenizer) TokenEncode(state SessionState) (string, error)

TokenEncode returns tokenized string which represents session state and can be decoded with the same interface implementation.

type SessionState

type SessionState struct {
	Nickname  string    `json:"nck"`
	ID        string    `json:"id"`
	CreatedAt time.Time `json:"cat"`
	ExpireAt  time.Time `json:"eat"`
}

SessionState is model for user sessions stored in browser or any other storage.

func SessionContextState

func SessionContextState(ctx context.Context) *SessionState

SessionContextState retrieves session state from context. It returns nil context, if there is no session state saved within context.

type SessionStateFactory

type SessionStateFactory struct {
	ExpirationTime time.Duration
	IDGenerator
	Clock
}

SessionStateFactory creates new unique session states.

func DefaultSessionStateFactory

func DefaultSessionStateFactory() *SessionStateFactory

DefaultSessionStateFactory is default constructor for SessionStateFactory.

func (SessionStateFactory) MakeState

func (ssf SessionStateFactory) MakeState(nickname string) SessionState

MakeState creates new unique session state for given nickname.

type SessionTokenizer

type SessionTokenizer interface {
	// TokenEncode returns tokenized string which represents session state and
	// can be decoded with the same interface implementation.
	TokenEncode(state SessionState) (string, error)

	// TokenDecode decodes given string token into valid session state.
	TokenDecode(token string) (*SessionState, error)
}

SessionTokenizer encodes and decodes session token.

type SessionTokenizerCache

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

SessionTokenizerCache wraps SessionTokenizer interface and extends it with concurrent-safe in-memory cache storage.

func NewSessionTokenizerCache

func NewSessionTokenizerCache(b SessionTokenizerCacheBuilder) *SessionTokenizerCache

NewSessionTokenizerCache is default and safe constructor for SessionTokenizerCache.

func (*SessionTokenizerCache) TokenDecode

func (c *SessionTokenizerCache) TokenDecode(token string) (*SessionState, error)

TokenDecode decodes given string token into valid session state.

func (*SessionTokenizerCache) TokenEncode

func (c *SessionTokenizerCache) TokenEncode(state SessionState) (string, error)

TokenEncode returns tokenized string which represents session state and can be decoded with the same interface implementation.

type SessionTokenizerCacheBuilder

type SessionTokenizerCacheBuilder struct {
	Wrapped SessionTokenizer
	Timeout time.Duration
	Logger  *logrus.Logger
}

SessionTokenizerCacheBuilder holds build arguments for SessionTokenizerCache.

type SessionTokenizerFactory

type SessionTokenizerFactory struct {
	Timeout time.Duration
	Logger  *logrus.Logger
}

SessionTokenizerFactory initiates tokenizer for szmaterlok based on configuration variables.

func (*SessionTokenizerFactory) Tokenizer

Tokenizer builds session tokenizer wrapped with cache based on the environmental variable from configuration.

type StateArchive

type StateArchive interface {
	// Events sends all events from state archive through given channels
	// grouped by their creation date.
	Events(context.Context, chan<- BridgeEvent) error
}

StateArchive stores events from past. With state archive application is able to rebuild its state.

type StateBuilder

type StateBuilder struct {
	// Archive stores past events.
	Archive StateArchive

	// Handler rebuilds state by applying hook to events
	// from archive.
	Handler BridgeEventHandler
}

StateBuilder rebuilds state of application with events from state archive.

func (*StateBuilder) Rebuild

func (sb *StateBuilder) Rebuild(ctx context.Context) error

Rebuild whole state of application.

type StateChatUser

type StateChatUser struct {
	ID       string
	Nickname string
}

StateChatUser contains data of single user who is currently logged in into the chat.

type StateOnlineUsers

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

StateOnlineUsers contains data for users, which are currently using chat.

func NewStateOnlineUsers

func NewStateOnlineUsers() *StateOnlineUsers

NewStateOnlineUsers is constructor for StateOnlineUsers. Using NewStateOnlineUsers is the only safe way to construct StateOnlineUsers.

func (*StateOnlineUsers) AllChatUsers

func (s *StateOnlineUsers) AllChatUsers(ctx context.Context) ([]OnlineChatUser, error)

AllChatUsers returns all users which are using currently chat.

func (*StateOnlineUsers) PushChatUser

func (s *StateOnlineUsers) PushChatUser(ctx context.Context, u StateChatUser) error

PushChatUser saves data of user which is logging in.

func (*StateOnlineUsers) RemoveChatUser

func (s *StateOnlineUsers) RemoveChatUser(ctx context.Context, id string) error

RemoveChatUser removes user with given id from state storage.

Directories

Path Synopsis
Package sse implements Server Sent Event API for szmaterlok backend server.
Package sse implements Server Sent Event API for szmaterlok backend server.

Jump to

Keyboard shortcuts

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