server

package
v0.0.0-...-3061286 Latest Latest
Warning

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

Go to latest
Published: Jul 21, 2025 License: Apache-2.0 Imports: 28 Imported by: 0

Documentation

Overview

Package server provides the HTTP server implementation for TurboScript.

This package implements a high-performance HTTP server using FastHTTP that handles routing, request processing, and integration with the TypeScript execution engine. It provides the core runtime environment for TurboScript applications.

Key Features:

  • Dynamic routing based on configuration
  • TypeScript code execution via JavaScript VM
  • Database query execution with security restrictions
  • Request/response transformation
  • Error handling and logging
  • Performance monitoring integration

The server acts as a bridge between HTTP requests and TypeScript business logic, executing TypeScript functions in a secure sandboxed environment and managing database operations through a controlled interface.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func SanitizeJSONForHTML

func SanitizeJSONForHTML(jsonData string) string

SanitizeJSONForHTML sanitizes JSON data to prevent XSS attacks when embedding in HTML. It escapes HTML characters that could be used for script injection.

Types

type HybridData

type HybridData struct {
	Route  string
	Data   string            // JSON-encoded data
	Assets map[string]string // Asset path to versioned URL mapping
}

HybridData represents the data structure passed to hybrid frontend app template.

type KafkaManager

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

KafkaManager provides comprehensive Kafka integration for scaling WebSocket and SSE.

func NewKafkaManager

func NewKafkaManager(brokers []string, topic string) *KafkaManager

NewKafkaManager creates a new Kafka manager for real-time message distribution.

func (*KafkaManager) IsHealthy

func (km *KafkaManager) IsHealthy() bool

IsHealthy checks if Kafka is reachable and functional.

func (*KafkaManager) PublishSSEMessage

func (km *KafkaManager) PublishSSEMessage(event string, data interface{}, userID string) error

PublishSSEMessage publishes an SSE message to Kafka for multi-instance scaling.

func (*KafkaManager) PublishWebSocketMessage

func (km *KafkaManager) PublishWebSocketMessage(msg WebSocketMessage) error

PublishWebSocketMessage publishes a WebSocket message to Kafka for multi-instance scaling.

func (*KafkaManager) SetManagers

func (km *KafkaManager) SetManagers(wsManager *WebSocketManager, sseManager *SSEManager)

SetManagers sets the WebSocket and SSE managers for message routing.

func (*KafkaManager) Start

func (km *KafkaManager) Start() error

Start begins consuming Kafka messages for cross-instance communication.

func (*KafkaManager) Stop

func (km *KafkaManager) Stop() error

Stop stops the Kafka manager and closes connections.

type KafkaMessage

type KafkaMessage struct {
	Type       string      `json:"type"`        // "websocket" or "sse"
	Action     string      `json:"action"`      // "broadcast", "user_message", "room_message"
	InstanceID string      `json:"instance_id"` // Unique instance identifier
	Timestamp  time.Time   `json:"timestamp"`
	Data       interface{} `json:"data"`
}

KafkaMessage represents a message for cross-instance communication.

type SSEConnection

type SSEConnection struct {
	ID           string                 `json:"id"`
	UserID       string                 `json:"user_id"`
	UserData     map[string]interface{} `json:"user_data"`
	ConnectedAt  time.Time              `json:"connected_at"`
	LastActivity time.Time              `json:"last_activity"`
	RemoteAddr   string                 `json:"remote_addr"`
	UserAgent    string                 `json:"user_agent"`
	Channel      chan SSEMessage        `json:"-"`
	Done         chan bool              `json:"-"`
	IsActive     bool                   `json:"is_active"`
}

SSEConnection represents a Server-Sent Events connection.

type SSEManager

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

SSEManager manages all Server-Sent Events connections.

func NewSSEManager

func NewSSEManager(server *Server, sseConfig *config.SSEConfig) *SSEManager

NewSSEManager creates a new Server-Sent Events manager.

func (*SSEManager) AssociateUserWithConnection

func (sm *SSEManager) AssociateUserWithConnection(connectionID, userID string) error

AssociateUserWithConnection associates a user ID with an SSE connection.

func (*SSEManager) Broadcast

func (sm *SSEManager) Broadcast(event string, data interface{}) error

Broadcast sends a message to all active SSE connections.

func (*SSEManager) GetConnectionCount

func (sm *SSEManager) GetConnectionCount() int

GetConnectionCount returns the total number of active SSE connections.

func (*SSEManager) GetUserConnectionCount

func (sm *SSEManager) GetUserConnectionCount(userID string) int

GetUserConnectionCount returns the number of connections for a specific user.

func (*SSEManager) HandleSSE

func (sm *SSEManager) HandleSSE(ctx *fasthttp.RequestCtx, ep config.EndpointConfig)

HandleSSE handles Server-Sent Events endpoint.

func (*SSEManager) SendToConnection

func (sm *SSEManager) SendToConnection(connectionID string, event string, data interface{}) error

SendToConnection sends a message to a specific SSE connection.

func (*SSEManager) SendToUser

func (sm *SSEManager) SendToUser(userID string, event string, data interface{}) error

SendToUser sends a message to all SSE connections for a specific user.

func (*SSEManager) SetKafkaManager

func (sm *SSEManager) SetKafkaManager(kafkaManager *KafkaManager)

SetKafkaManager sets the Kafka manager for SSE scaling.

type SSEMessage

type SSEMessage struct {
	ID      string      `json:"id"`      // Message ID
	Event   string      `json:"event"`   // Event type
	Data    interface{} `json:"data"`    // Message data
	Retry   int         `json:"retry"`   // Retry interval in milliseconds
	Comment string      `json:"comment"` // Comment (not sent to client)
	Raw     bool        `json:"raw"`     // Send as raw data without JSON encoding
}

SSEMessage represents a Server-Sent Events message.

type Server

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

Server represents the main HTTP server instance for TurboScript.

It handles incoming HTTP requests, routes them to appropriate TypeScript handlers, manages database connections, and provides performance monitoring capabilities.

func NewServerWithServices

func NewServerWithServices(cfg *config.Config, dbManager *config.DatabaseManager, jobManager any, emailService any) *Server

NewServerWithServices creates a new HTTP server instance with job manager and email service.

This function initializes the server with full isolation support for concurrent request processing.

func (*Server) BroadcastSSEToAll

func (s *Server) BroadcastSSEToAll(event string, data map[string]interface{}, messageID string) int

BroadcastSSEToAll broadcasts an SSE message to all connections.

func (*Server) BroadcastSSEToConnection

func (s *Server) BroadcastSSEToConnection(connectionID string, event string, data map[string]interface{}, messageID string) int

BroadcastSSEToConnection broadcasts an SSE message to a specific connection.

func (*Server) BroadcastSSEToUser

func (s *Server) BroadcastSSEToUser(userID string, event string, data map[string]interface{}, messageID string) int

BroadcastSSEToUser broadcasts an SSE message to all connections for a specific user.

func (*Server) BroadcastToAll

func (s *Server) BroadcastToAll(msgType string, data map[string]interface{}) int

BroadcastToAll broadcasts a message to all WebSocket connections.

func (*Server) BroadcastToConnection

func (s *Server) BroadcastToConnection(connectionID string, msgType string, data map[string]interface{}) int

BroadcastToConnection broadcasts a message to a specific WebSocket connection.

func (*Server) BroadcastToRoom

func (s *Server) BroadcastToRoom(roomName string, msgType string, data map[string]interface{}) int

BroadcastToRoom broadcasts a message to all WebSocket connections in a room.

func (*Server) FindMatchingEndpoint

func (s *Server) FindMatchingEndpoint(requestURL string, method string) *config.EndpointConfig

FindMatchingEndpoint finds the endpoint that matches the request URL.

func (*Server) GetConnectionStats

func (s *Server) GetConnectionStats(filter string) map[string]interface{}

GetConnectionStats returns statistics about active connections.

func (*Server) GetSSEManager

func (s *Server) GetSSEManager() *SSEManager

GetSSEManager returns the SSE manager instance.

func (*Server) GetWebSocketManager

func (s *Server) GetWebSocketManager() *WebSocketManager

GetWebSocketManager returns the WebSocket manager instance.

func (*Server) Start

func (s *Server) Start()

Start initializes and starts the HTTP server.

This method sets up performance monitoring if enabled, compiles route patterns, and starts the FastHTTP server listening on the configured port.

type SessionAffinityManager

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

SessionAffinityManager manages sticky sessions for horizontal scaling.

func NewSessionAffinityManager

func NewSessionAffinityManager(instanceID string) *SessionAffinityManager

NewSessionAffinityManager creates a new session affinity manager.

func (*SessionAffinityManager) CreateSession

func (sam *SessionAffinityManager) CreateSession(userID string) *SessionInfo

CreateSession creates a new session with affinity to this instance.

func (*SessionAffinityManager) GenerateSessionID

func (sam *SessionAffinityManager) GenerateSessionID() string

GenerateSessionID creates a new unique session ID.

func (*SessionAffinityManager) GetActiveSessionCount

func (sam *SessionAffinityManager) GetActiveSessionCount() int

GetActiveSessionCount returns the number of active sessions on this instance.

func (*SessionAffinityManager) GetInstanceLoad

func (sam *SessionAffinityManager) GetInstanceLoad() map[string]interface{}

GetInstanceLoad returns load information for this instance.

func (*SessionAffinityManager) GetSession

func (sam *SessionAffinityManager) GetSession(sessionID string) (*SessionInfo, bool)

GetSession retrieves session information.

func (*SessionAffinityManager) GetStickyCookie

func (sam *SessionAffinityManager) GetStickyCookie(sessionID string) string

GetStickyCookie generates a sticky session cookie value.

func (*SessionAffinityManager) GetUserSessions

func (sam *SessionAffinityManager) GetUserSessions(userID string) []*SessionInfo

GetUserSessions returns all active sessions for a specific user.

func (*SessionAffinityManager) IsSessionAffine

func (sam *SessionAffinityManager) IsSessionAffine(sessionID string) bool

IsSessionAffine checks if a session belongs to this instance.

func (*SessionAffinityManager) ParseStickyCookie

func (sam *SessionAffinityManager) ParseStickyCookie(cookie string) (instanceID, sessionID string)

ParseStickyCookie parses a sticky session cookie to extract instance and session.

func (*SessionAffinityManager) RemoveSession

func (sam *SessionAffinityManager) RemoveSession(sessionID string)

RemoveSession removes a session.

func (*SessionAffinityManager) ShouldHandleRequest

func (sam *SessionAffinityManager) ShouldHandleRequest(req *SessionRequest) bool

ShouldHandleRequest determines if this instance should handle the request.

func (*SessionAffinityManager) StartCleanup

func (sam *SessionAffinityManager) StartCleanup(maxIdleTime time.Duration)

StartCleanup starts the cleanup routine for expired sessions.

func (*SessionAffinityManager) StopCleanup

func (sam *SessionAffinityManager) StopCleanup()

StopCleanup stops the cleanup routine.

func (*SessionAffinityManager) TransferSession

func (sam *SessionAffinityManager) TransferSession(sessionID, targetInstanceID string) bool

TransferSession marks a session for transfer to another instance.

func (*SessionAffinityManager) UpdateLastSeen

func (sam *SessionAffinityManager) UpdateLastSeen(sessionID string)

UpdateLastSeen updates the last seen timestamp for a session.

type SessionInfo

type SessionInfo struct {
	SessionID  string    `json:"session_id"`
	InstanceID string    `json:"instance_id"`
	UserID     string    `json:"user_id,omitempty"`
	CreatedAt  time.Time `json:"created_at"`
	LastSeen   time.Time `json:"last_seen"`
	Active     bool      `json:"active"`
}

SessionInfo holds session affinity data.

type SessionRequest

type SessionRequest struct {
	SessionID string
	UserID    string
	Path      string
	Headers   map[string]string
}

ValidateSessionRequest checks if a request should be handled by this instance.

type WebSocketConnection

type WebSocketConnection struct {
	ID          string                 `json:"id"`
	Conn        *websocket.Conn        `json:"-"`
	Room        string                 `json:"room"`
	UserID      string                 `json:"user_id"`
	UserData    map[string]interface{} `json:"user_data"`
	ConnectedAt time.Time              `json:"connected_at"`
	LastPing    time.Time              `json:"last_ping"`
	IsAlive     bool                   `json:"is_alive"`
	RemoteAddr  string                 `json:"remote_addr"`
	UserAgent   string                 `json:"user_agent"`
	// contains filtered or unexported fields
}

WebSocketConnection represents a WebSocket connection with metadata.

type WebSocketManager

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

WebSocketManager manages all WebSocket connections and rooms.

func NewWebSocketManager

func NewWebSocketManager(server *Server, channels []config.WebSocketChannelConfig, wsConfig *config.WebSocketConfig) *WebSocketManager

NewWebSocketManager creates a new WebSocket manager.

func (*WebSocketManager) BroadcastToRoom

func (wm *WebSocketManager) BroadcastToRoom(roomName string, msg interface{}) error

BroadcastToRoom broadcasts a message to all connections in a room (public API).

func (*WebSocketManager) GetRoomConnections

func (wm *WebSocketManager) GetRoomConnections(roomName string) []*WebSocketConnection

GetRoomConnections returns the list of connections in a room.

func (*WebSocketManager) GetRoomCount

func (wm *WebSocketManager) GetRoomCount(roomName string) int

GetRoomCount returns the number of connections in a room.

func (*WebSocketManager) HandleWebSocket

func (wm *WebSocketManager) HandleWebSocket(ctx *fasthttp.RequestCtx, ep config.EndpointConfig)

HandleWebSocket handles WebSocket upgrade and connection management.

func (*WebSocketManager) StartKafka

func (wm *WebSocketManager) StartKafka(sseManager *SSEManager) error

StartKafka starts the Kafka integration for cross-instance scaling.

func (*WebSocketManager) StopKafka

func (wm *WebSocketManager) StopKafka() error

StopKafka stops the Kafka integration.

type WebSocketMessage

type WebSocketMessage struct {
	Type      string                 `json:"type"`       // Message type (join, leave, message, broadcast, etc.)
	Room      string                 `json:"room"`       // Target room
	Data      interface{}            `json:"data"`       // Message payload
	UserID    string                 `json:"user_id"`    // Sender user ID
	MessageID string                 `json:"message_id"` // Unique message ID
	Timestamp time.Time              `json:"timestamp"`  // Message timestamp
	Metadata  map[string]interface{} `json:"metadata"`   // Additional metadata
}

WebSocketMessage represents a WebSocket message structure.

type WebSocketRoom

type WebSocketRoom struct {
	Name        string                          `json:"name"`
	Type        string                          `json:"type"`        // public, private, presence
	Connections map[string]*WebSocketConnection `json:"connections"` // Connection ID -> Connection
	MaxConns    int                             `json:"max_conns"`   // Maximum connections (0 = unlimited)
	Handler     string                          `json:"handler"`     // TypeScript handler path
	Pattern     *regexp.Regexp                  `json:"-"`           // Compiled regex pattern
	CreatedAt   time.Time                       `json:"created_at"`
	// contains filtered or unexported fields
}

WebSocketRoom manages connections for a specific room.

Jump to

Keyboard shortcuts

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