hub

package
v0.0.0 Latest Latest
Warning

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

Go to latest
Published: May 16, 2025 License: None detected not legal advice Imports: 0 Imported by: 0

README ΒΆ

Hub Package

The hub package is the central message coordinator in the chat server. It manages client connections, message routing, broadcasting, private messaging, and integration with both caching and persistence layers.

Architecture

Responsibilities
  • Track all active WebSocket clients.
  • Broadcast chat messages and user status updates to connected clients.
  • Whisper private messages between specific users.
  • Integrate with the cache package to temporarily store and rate-limit messages.
  • Record session data to the database via the db package.
Components
  • Hub Struct: Core state manager with:

    • Connections: map of active clients.
    • Register, Unregister: channels for client lifecycle.
    • Messages: channel for incoming messages.
    • MessageCache: reference to the Valkey-backed message cache.
    • db: PostgreSQL pool for recording session data.
  • Message Types: Supports:

    • Public chat messages
    • Private (whisper) messages
    • User connect/disconnect events
    • Requests for current user list

Workflow

  1. Client Registers:

    • On connect, a Client sends itself to the hub's Register channel.
    • The hub stores the client and begins tracking session time.
  2. Message Handling:

    • Chat messages are received via the Messages channel.
    • The hub delegates by:
      • Checking message type.
      • Adding a cacheID (via MessageCache).
      • Broadcasting to all clients or sending privately.
  3. Client Disconnects:

    • A client sends itself to the Unregister channel.
    • The hub removes the client, closes its channel, and writes session info to the database.

Configuration

  • The Hub is created via:

    NewHub(db *pgxpool.Pool, cache *MessageCache)
    
  • Message cache limits, flush intervals, and rate limits are configured in the cache package.

Setup & Usage

  1. Instantiate the Hub:

    hub := hub.NewHub(dbPool, messageCache)
    
  2. Start the Hub Loop:

    go hub.Run()
    
  3. Clients Interact Through Channels:

    • Register: hub.Register <- client
    • Unregister: hub.Unregister <- client
    • Send Message: hub.Messages <- msg

πŸ“ TODO

  • Graceful shutdown hook to flush sessions and broadcast disconnects.
  • Implement separate broadcast and whisper queues to:
    • Prevent the hub loop from blocking if a client’s Send channel is full or slow
    • Decouple message delivery from message processing logic
    • Enable future enhancements like:
      • Rate limiting broadcast and whisper delivery independently
      • Filtering or moderation before delivery
      • Monitoring queue depth to detect client lag or overload

Documentation ΒΆ

Index ΒΆ

Constants ΒΆ

This section is empty.

Variables ΒΆ

This section is empty.

Functions ΒΆ

This section is empty.

Types ΒΆ

type Hub ΒΆ

type Hub struct {
	Connections  map[string]interfaces.ClientInterface
	Messages     chan messages.BaseMessage
	Register     chan interfaces.ClientInterface
	Unregister   chan interfaces.ClientInterface
	MessageCache *cache.MessageCache
	// contains filtered or unexported fields
}

Hub manages all active client connections, routes messages, and handles broadcasting, registration, and unregistration.

func NewHub ΒΆ

func NewHub(db *pgxpool.Pool, cache *cache.MessageCache) *Hub

NewHub creates and returns a new Hub instance.

func (*Hub) Broadcast ΒΆ

func (h *Hub) Broadcast(msg messages.BaseMessage)

Broadcast sends the given message to all connected clients in the hub.

func (*Hub) FindUsernameByUserID ΒΆ

func (h *Hub) FindUsernameByUserID(userID string) (string, bool)

FindUsernameByUserID returns the username for a given user ID, if connected.

func (*Hub) GetCachedChatMessages ΒΆ

func (h *Hub) GetCachedChatMessages() []models.ChatMessage

GetCachedChatMessages returns a slice of chat messages from the message cache.

func (*Hub) GetConnectedUsers ΒΆ

func (h *Hub) GetConnectedUsers() []chat.UserStatusPayload

GetConnectedUsers returns a list of currently connected user payloads, excluding clients identified as "WebClient".

func (*Hub) RegisterClient ΒΆ

func (h *Hub) RegisterClient(client interfaces.ClientInterface, clientID string)

RegisterClient adds a client to the hub and tracks its connection start time.

func (*Hub) Run ΒΆ

func (h *Hub) Run()

Run starts the hub's main loop and handles registration, unregistration, and messages.

func (*Hub) SendMessage ΒΆ

func (h *Hub) SendMessage(msg messages.BaseMessage)

SendMessage sends a message into the hub’s internal message loop for handling.

func (*Hub) UnregisterClient ΒΆ

func (h *Hub) UnregisterClient(client interfaces.ClientInterface, clientID string)

UnregisterClient removes a client from the hub and logs the session duration.

func (*Hub) Whisper ΒΆ

func (h *Hub) Whisper(msg messages.BaseMessage)

Whisper sends a private message only to the sender and recipient clients.

Jump to

Keyboard shortcuts

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