realtime

package
v0.1.21 Latest Latest
Warning

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

Go to latest
Published: Sep 28, 2026 License: MIT Imports: 11 Imported by: 0

Documentation

Index

Constants

View Source
const (
	TargetUser      = "user"
	TargetRoom      = "room"
	TargetBroadcast = "broadcast"
)
View Source
const DefaultTopic = "rt:events"
View Source
const KeyRealtime runtime.Key = "realtime"

Variables

View Source
var (
	ErrNilClient                = errors.New("realtime: nil client")
	ErrEmptyClientID            = errors.New("realtime: empty client id")
	ErrEmptyEvent               = errors.New("realtime: empty event")
	ErrNilPublisher             = errors.New("realtime: nil publisher")
	ErrNilGateway               = errors.New("realtime: nil gateway")
	ErrNilSubscriber            = errors.New("realtime: nil subscriber")
	ErrNilRouter                = errors.New("realtime: nil router")
	ErrNilActionCodec           = errors.New("realtime: nil action codec")
	ErrNilActionHandler         = errors.New("realtime: nil action handler")
	ErrEmptyAction              = errors.New("realtime: empty action")
	ErrEmptyIdentity            = errors.New("realtime: empty identity")
	ErrClientNotFound           = errors.New("realtime: client not found")
	ErrClientChannelUnavailable = errors.New("realtime: client channel unavailable")
	ErrClientBufferFull         = errors.New("realtime: client buffer full")
	ErrActionAlreadyRegistered  = errors.New("realtime: action already registered")
	ErrActionNotFound           = errors.New("realtime: action not found")
	ErrInvalidAction            = errors.New("realtime: invalid action")
	ErrDefaultNotReady          = errors.New("realtime: default not initialized")
	ErrUnsupportedTopic         = errors.New("realtime: unsupported topic")
	ErrClosed                   = errors.New("realtime: closed")
)
View Source
var ErrUnauthorized = errors.New("realtime unauthorized")

Functions

func Bind

func Bind(app *runtime.App, publisher Publisher) error

func Broadcast

func Broadcast(ctx context.Context, action string, data any) error

func ClearDefaultPublisher

func ClearDefaultPublisher(publisher Publisher)

func PublishToUser

func PublishToUser(ctx context.Context, userID string, action string, data any) error

func PushRoom

func PushRoom(ctx context.Context, roomID string, action string, data any) error

func PushUser

func PushUser(ctx context.Context, userID string, action string, data any) error

func SetDefaultPublisher

func SetDefaultPublisher(publisher Publisher)

func ValidatePublisherConfig

func ValidatePublisherConfig(cfg PublisherConfig) error

Types

type ActionCodec

type ActionCodec interface {
	DecodeAction(payload []byte) (ActionMessage, error)
	EncodeAction(message ActionMessage) ([]byte, error)
}

type ActionContext

type ActionContext struct {
	Client   *Client
	Identity *Identity
	Event    *Event
	Gateway  Gateway
	Values   map[string]any

	Message ActionMessage
	Raw     []byte
	// contains filtered or unexported fields
}

func (*ActionContext) Abort

func (a *ActionContext) Abort()

func (*ActionContext) ActionError

func (a *ActionContext) ActionError(code string, message string, err error) error

func (*ActionContext) Bind

func (a *ActionContext) Bind(v any) error

func (*ActionContext) ClientID

func (a *ActionContext) ClientID() string

func (*ActionContext) Context

func (a *ActionContext) Context() context.Context

func (*ActionContext) Control

func (a *ActionContext) Control(event string, data any) error

func (*ActionContext) Get

func (a *ActionContext) Get(key string) any

func (*ActionContext) IsAborted

func (a *ActionContext) IsAborted() bool

func (*ActionContext) Next

func (a *ActionContext) Next() error

func (*ActionContext) PushRoom

func (a *ActionContext) PushRoom(roomID string, evt *Event) error

func (*ActionContext) PushUser

func (a *ActionContext) PushUser(userID string, evt *Event) error

func (*ActionContext) Reply

func (a *ActionContext) Reply(action string, data any) error

func (*ActionContext) RunHandlers

func (a *ActionContext) RunHandlers(handlers ...HandlerFunc) error

func (*ActionContext) Set

func (a *ActionContext) Set(key string, value any)

func (*ActionContext) SetContext

func (a *ActionContext) SetContext(ctx context.Context)

func (*ActionContext) SetHandlers

func (a *ActionContext) SetHandlers(handlers ...HandlerFunc)

func (*ActionContext) ShouldBindJSON

func (a *ActionContext) ShouldBindJSON(dst any) error

func (*ActionContext) UserID

func (a *ActionContext) UserID() string

type ActionError

type ActionError struct {
	Code    string
	Message string
	Err     error
}

func NewActionError

func NewActionError(code string, message string, err error) *ActionError

func (*ActionError) Error

func (e *ActionError) Error() string

func (*ActionError) Unwrap

func (e *ActionError) Unwrap() error

type ActionHandlerFunc

type ActionHandlerFunc = HandlerFunc

type ActionMessage

type ActionMessage struct {
	Action    string
	RequestID string
	Headers   map[string]string
	Payload   []byte
}

type AllowAnonymousAuthenticator

type AllowAnonymousAuthenticator struct{}

func (AllowAnonymousAuthenticator) Authenticate

type AuthOptions

type AuthOptions struct {
	Enabled     bool
	TokenQuery  string
	AllowCookie bool
	JWTSecret   string
}

type AuthResult

type AuthResult struct {
	UserID   string
	TenantID int64
}

func (*AuthResult) Identity

func (r *AuthResult) Identity() *Identity

type Authenticator

type Authenticator interface {
	Authenticate(ctx context.Context, r *http.Request) (*AuthResult, error)
}

type Client

type Client struct {
	ID       string
	Identity *Identity
	Metadata map[string]any

	UserID       string
	TenantID     int64
	Events       map[string]bool
	Ch           chan Event
	CreatedAt    time.Time
	LastActiveAt time.Time
}

func (*Client) Authenticated

func (c *Client) Authenticated() bool

func (*Client) CurrentIdentity

func (c *Client) CurrentIdentity() *Identity

func (*Client) IdentityState

func (c *Client) IdentityState() IdentityState

func (*Client) Subscribed

func (c *Client) Subscribed(event string) bool

type Config

type Config struct {
	Topic            string
	ClientBufferSize int
	Logger           Logger
}

func DefaultConfig

func DefaultConfig() Config

func (Config) Options

func (c Config) Options() Options

type Context

type Context = ActionContext

type Dispatcher

type Dispatcher interface {
	DispatchEvent(ctx context.Context, evt *Event) error
	DispatchLocal(ctx context.Context, evt *Event) error
	DispatchClient(ctx context.Context, clientID string, evt *Event) error
	PushUser(ctx context.Context, userID string, evt *Event) error
	PushClient(ctx context.Context, clientID string, evt *Event) error
	PushRoom(ctx context.Context, roomID string, evt *Event) error
	Broadcast(ctx context.Context, evt *Event) error
}

type Event

type Event struct {
	Action    string            `json:"action"`
	RequestID string            `json:"request_id,omitempty"`
	TraceID   string            `json:"trace_id,omitempty"`
	Timestamp int64             `json:"timestamp,omitempty"`
	Headers   map[string]string `json:"headers,omitempty"`
	Data      any               `json:"data,omitempty"`

	Event    string          `json:"event,omitempty"`
	Module   string          `json:"module,omitempty"`
	Target   *Target         `json:"target,omitempty"`
	TenantID int64           `json:"tenant_id,omitempty"`
	RoomID   string          `json:"room_id,omitempty"`
	Payload  json.RawMessage `json:"payload,omitempty"`
	Time     int64           `json:"time,omitempty"`
}

func NewEvent

func NewEvent(action string, data any) *Event

func (*Event) Normalize

func (e *Event) Normalize() *Event

type EventWriter

type EventWriter interface {
	WriteEvent(w io.Writer, event Event) error
}

type Gateway

type Gateway interface {
	Handle(ctx *ActionContext) error
	Publish(ctx context.Context, evt *Event) error
	PushUser(ctx context.Context, userID string, evt *Event) error
	PushClient(ctx context.Context, clientID string, evt *Event) error
	PushRoom(ctx context.Context, roomID string, evt *Event) error
	Broadcast(ctx context.Context, evt *Event) error
}

type HandlerFunc

type HandlerFunc func(action *ActionContext) error

type Identity

type Identity struct {
	ID       string         `json:"id"`
	Type     string         `json:"type,omitempty"`
	DeviceID string         `json:"device_id,omitempty"`
	Platform string         `json:"platform,omitempty"`
	Metadata map[string]any `json:"metadata,omitempty"`

	TenantID int64        `json:"-"`
	Kind     IdentityKind `json:"-"`
	Subject  string       `json:"-"`
}

func IdentityFromAuthResult

func IdentityFromAuthResult(result *AuthResult) *Identity

func NewUserIdentity

func NewUserIdentity(userID string, tenantID int64) *Identity

func (*Identity) Anonymous

func (i *Identity) Anonymous() bool

func (*Identity) Authenticated

func (i *Identity) Authenticated() bool

func (*Identity) Normalize

func (i *Identity) Normalize() *Identity

func (*Identity) State

func (i *Identity) State() IdentityState

type IdentityKind

type IdentityKind string
const (
	IdentityKindUser   IdentityKind = "user"
	IdentityKindDevice IdentityKind = "device"
)

type IdentityState

type IdentityState string
const (
	IdentityStateAnonymous     IdentityState = "anonymous"
	IdentityStateAuthenticated IdentityState = "authenticated"
)

type Lifecycle

type Lifecycle interface {
	Close() error
}

type Logger

type Logger interface {
	Warn(msg string, fields ...any)
}

type MiddlewareFunc

type MiddlewareFunc func(HandlerFunc) HandlerFunc

type Option

type Option func(*Options)

func WithClientBufferSize

func WithClientBufferSize(size int) Option

func WithLogger

func WithLogger(log Logger) Option

type Options

type Options struct {
	ClientBufferSize int
	Logger           Logger
}

func NewOptions

func NewOptions(opts ...Option) Options

type Presence

type Presence interface {
	Online(ctx context.Context, clientID string, identity *Identity) error
	Offline(ctx context.Context, clientID string) error
	Heartbeat(ctx context.Context, clientID string) error
	IsOnline(ctx context.Context, clientID string) (bool, error)
}

type Publisher

type Publisher interface {
	PushUser(ctx context.Context, userID string, evt *Event) error
	PushRoom(ctx context.Context, roomID string, evt *Event) error
	Broadcast(ctx context.Context, evt *Event) error
}

func DefaultPublisher

func DefaultPublisher() Publisher

func From

func From(app *runtime.App) Publisher

func NewConfiguredPublisher

func NewConfiguredPublisher(cfg PublisherConfig, logName string) (Publisher, string, error)

type PublisherConfig

type PublisherConfig struct {
	Driver        string `mapstructure:"driver" yaml:"driver"`
	Addr          string `mapstructure:"addr" yaml:"addr"`
	Topic         string `mapstructure:"topic" yaml:"topic"`
	TopicPrefix   string `mapstructure:"topic_prefix" yaml:"topic_prefix"`
	SubjectPrefix string `mapstructure:"subject_prefix" yaml:"subject_prefix"`
	NodeName      string `mapstructure:"node_name" yaml:"node_name"`
	StreamMaxLen  int64  `mapstructure:"stream_max_len" yaml:"stream_max_len"`
}

type Registry

type Registry interface {
	Add(client *Client) error
	Remove(clientID string) error
	Get(clientID string) (*Client, bool)
	GetUserClients(userID string) []*Client
	GetRoomClients(roomID string) []*Client
}

type Room

type Room interface {
	Join(ctx context.Context, roomID string, clientID string) error
	Leave(ctx context.Context, roomID string, clientID string) error
	Clients(ctx context.Context, roomID string) ([]string, error)
	Rooms(ctx context.Context, clientID string) ([]string, error)
}

type Route

type Route struct {
	Action     string
	Middleware []MiddlewareFunc
	Handler    HandlerFunc
	Compiled   HandlerFunc
	Handlers   []HandlerFunc
}

type Router

type Router interface {
	Use(middleware ...MiddlewareFunc)
	On(action string, handlers ...HandlerFunc)
	Group(prefix string, middleware ...MiddlewareFunc) Router
	Match(action string) (*Route, bool)
}

type Runner

type Runner interface {
	Run(ctx context.Context) error
}

type ServerOptions

type ServerOptions struct {
	Addr              string
	Path              string
	HeartbeatInterval time.Duration
	WriteTimeout      time.Duration
	ClientBufferSize  int
	AllowEvents       []string
	Auth              AuthOptions
	EventBusDriver    string
	EventBusTopic     string
	EventBusPrefix    string
	StreamMaxLen      int64
	NodeName          string
}

type Service

type Service interface {
	Publisher
}

type Target

type Target struct {
	Type     string `json:"type"`
	ID       string `json:"id,omitempty"`
	UserID   string `json:"user_id,omitempty"`
	TenantID int64  `json:"tenant_id,omitempty"`
	RoomID   string `json:"room_id,omitempty"`
	ClientID string `json:"client_id,omitempty"`
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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