server

package
v0.14.3 Latest Latest
Warning

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

Go to latest
Published: Jan 26, 2026 License: MIT Imports: 29 Imported by: 0

Documentation

Overview

CRC: crc-BackendSocket.md, crc-ProtocolDetector.md, crc-PacketProtocol.md Spec: deployment.md

CRC: crc-HTTPEndpoint.md Spec: interfaces.md, deployment.md

CRC: crc-PendingResponseQueue.md Spec: deployment.md

CRC: crc-LuaSession.md (Server owns luaSessions map) Spec: deployment.md, interfaces.md Sequence: seq-server-startup.md, seq-session-create-backend.md, seq-lua-session-init.md

Server implements per-session Lua isolation via luaSessions map[string]*lua.LuaSession. It creates/destroys LuaSessions via SessionManager callbacks and implements PathVariableHandler to route HandleFrontendCreate/Update to per-session LuaSession.

Package server implements the UI server communication layer. CRC: crc-WebSocketEndpoint.md Spec: interfaces.md

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DefaultSocketPath

func DefaultSocketPath() string

DefaultSocketPath returns the platform-specific default socket path.

func RunSvc added in v0.9.0

func RunSvc(s ChanSvc)

Run a service. Close the channel to stop it.

func Svc added in v0.9.0

func Svc(s ChanSvc, code func())

func SvcSync added in v0.9.0

func SvcSync[T any](s ChanSvc, code func() (T, error)) (T, error)

Types

type AfterBatchCallback

type AfterBatchCallback func(sessionID string)

AfterBatchCallback is called after processing a message batch to trigger change detection.

type BackendSocket

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

BackendSocket handles the backend API socket.

func NewBackendSocket

func NewBackendSocket(cfg *config.Config, socketPath string, handler *protocol.Handler, httpHandler *HTTPEndpoint) *BackendSocket

NewBackendSocket creates a new backend socket handler.

func (*BackendSocket) Broadcast

func (bs *BackendSocket) Broadcast(msg *protocol.Message) error

Broadcast sends a message to all connected backends.

func (*BackendSocket) Close

func (bs *BackendSocket) Close() error

Close closes the socket and all connections.

func (*BackendSocket) GetSocketPath

func (bs *BackendSocket) GetSocketPath() string

GetSocketPath returns the socket path.

func (*BackendSocket) Listen

func (bs *BackendSocket) Listen() error

Listen starts listening on the backend socket.

func (*BackendSocket) Log

func (bs *BackendSocket) Log(level int, format string, args ...interface{})

Log logs a message via the config.

type ChanSvc added in v0.9.0

type ChanSvc chan func()

type DebugDataProvider added in v0.9.0

type DebugDataProvider func(sessionID string) ([]DebugVariable, error)

DebugDataProvider is called to get variable data for the debug page.

type DebugVariable added in v0.9.0

type DebugVariable struct {
	ID         int64             `json:"id"`
	ParentID   int64             `json:"parentId"`
	Type       string            `json:"type,omitempty"`
	Path       string            `json:"path,omitempty"`
	Value      interface{}       `json:"value,omitempty"`
	Properties map[string]string `json:"properties,omitempty"`
	ChildIDs   []int64           `json:"childIds,omitempty"`
}

DebugVariable represents a variable for the debug tree view.

type DisconnectCallback added in v0.9.0

type DisconnectCallback func(sessionID string)

DisconnectCallback is called when a connection disconnects. Used to clear sent-tracking so reconnections resync state.

type HTTPEndpoint

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

HTTPEndpoint handles HTTP requests.

func NewHTTPEndpoint

func NewHTTPEndpoint(sessions *session.Manager, handler *protocol.Handler, wsEndpoint *WebSocketEndpoint) *HTTPEndpoint

NewHTTPEndpoint creates a new HTTP endpoint.

func (*HTTPEndpoint) HandleProtocolCommand

func (h *HTTPEndpoint) HandleProtocolCommand(msg *protocol.Message) (*protocol.Response, error)

HandleProtocolCommand processes CLI protocol commands.

func (*HTTPEndpoint) ServeHTTP

func (h *HTTPEndpoint) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements http.Handler.

func (*HTTPEndpoint) SetDebugDataProvider added in v0.9.0

func (h *HTTPEndpoint) SetDebugDataProvider(provider DebugDataProvider)

SetDebugDataProvider sets the callback for getting debug variable data.

func (*HTTPEndpoint) SetEmbeddedSite

func (h *HTTPEndpoint) SetEmbeddedSite(site fs.FS)

SetEmbeddedSite sets the embedded site filesystem.

func (*HTTPEndpoint) SetRootSessionProvider added in v0.9.0

func (h *HTTPEndpoint) SetRootSessionProvider(provider RootSessionProvider)

SetRootSessionProvider sets a provider for the root path "/" session. If the provider returns a session ID, that session is used instead of creating a new one.

func (*HTTPEndpoint) SetStaticDir

func (h *HTTPEndpoint) SetStaticDir(dir string)

SetStaticDir sets a custom directory for static files.

type PendingQueueManager

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

PendingQueueManager manages pending queues per connection.

func NewPendingQueueManager

func NewPendingQueueManager() *PendingQueueManager

NewPendingQueueManager creates a new pending queue manager.

func (*PendingQueueManager) Enqueue

func (m *PendingQueueManager) Enqueue(connectionID string, msg *protocol.Message)

Enqueue implements protocol.PendingQueuer interface.

func (*PendingQueueManager) EnqueueTo

func (m *PendingQueueManager) EnqueueTo(msg *protocol.Message, connectionIDs []string)

EnqueueTo enqueues a message to specific connections.

func (*PendingQueueManager) EnqueueToAll

func (m *PendingQueueManager) EnqueueToAll(msg *protocol.Message)

EnqueueToAll enqueues a message to all queues.

func (*PendingQueueManager) GetQueue

func (m *PendingQueueManager) GetQueue(connectionID string) *PendingResponseQueue

GetQueue returns the queue for a connection, creating if needed.

func (*PendingQueueManager) Poll

func (m *PendingQueueManager) Poll(connectionID string, wait time.Duration) []*protocol.Message

Poll implements protocol.PendingQueuer interface.

func (*PendingQueueManager) RemoveQueue

func (m *PendingQueueManager) RemoveQueue(connectionID string)

RemoveQueue removes a connection's queue.

type PendingResponseQueue

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

PendingResponseQueue accumulates push messages for polling clients.

func NewPendingResponseQueue

func NewPendingResponseQueue() *PendingResponseQueue

NewPendingResponseQueue creates a new pending response queue.

func (*PendingResponseQueue) Drain

func (q *PendingResponseQueue) Drain() []*protocol.Message

Drain returns all pending messages and clears the queue.

func (*PendingResponseQueue) Enqueue

func (q *PendingResponseQueue) Enqueue(msg *protocol.Message)

Enqueue adds a message to the pending queue. Valid message types: update, error, destroy

func (*PendingResponseQueue) IsEmpty

func (q *PendingResponseQueue) IsEmpty() bool

IsEmpty checks if the queue has pending messages.

func (*PendingResponseQueue) Len

func (q *PendingResponseQueue) Len() int

Len returns the number of pending messages.

func (*PendingResponseQueue) Poll

Poll returns pending messages, optionally waiting for availability. If wait is 0, returns immediately. Otherwise waits up to the duration.

type RootSessionProvider added in v0.9.0

type RootSessionProvider func() string

RootSessionProvider returns the session ID to use for the root path "/". If it returns an empty string, the default behavior (create new session and redirect) is used. If it returns a session ID, index.html is served with a session cookie set.

type Server

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

Server is the main UI server. CRC: crc-Server.md

func New

func New(cfg *config.Config) *Server

New creates a new server with the given configuration.

func (*Server) AfterBatch

func (s *Server) AfterBatch(internalSessionID string)

AfterBatch triggers Lua change detection after processing a message batch. internalSessionID is the full UUID session ID (used in URLs/WebSocket bindings). This method looks up the vended ID and calls the Lua session's AfterBatch, then sends any detected changes to watching frontends. CRC: crc-Server.md Sequence: seq-relay-message.md, seq-backend-refresh.md

func (*Server) CreateLuaBackendForSession

func (s *Server) CreateLuaBackendForSession(vendedID string, sess *session.Session) error

CreateLuaBackendForSession creates a LuaBackend and LuaSession for a new frontend session. vendedID is the compact integer ID (e.g., "1", "2") for backend communication. Each frontend session gets its own isolated Lua state. CRC: crc-LuaBackend.md Sequence: seq-session-create-backend.md

func (*Server) DestroyLuaBackendForSession

func (s *Server) DestroyLuaBackendForSession(vendedID string, sess *session.Session)

DestroyLuaBackendForSession destroys a session's LuaBackend and LuaSession. vendedID is the compact integer ID (e.g., "1", "2") for backend communication.

func (*Server) ExecuteInSession added in v0.9.0

func (s *Server) ExecuteInSession(vendedID string, fn func() (interface{}, error)) (interface{}, error)

ExecuteInSession executes code within a session's context. This queues through the session's executor to serialize with WebSocket operations. AfterBatch is called after execution to detect and push any changes. Also sets up the Lua session context so session:getApp() etc. work. vendedID is the compact session ID ("1", "2", etc.)

func (*Server) GetHandler

func (s *Server) GetHandler() *protocol.Handler

GetHandler returns the protocol handler.

func (*Server) GetLuaSession added in v0.9.0

func (s *Server) GetLuaSession(vendedID string) *lua.LuaSession

GetLuaSession returns a Lua session by vended ID (for testing/advanced use).

func (*Server) GetSessionIDs added in v0.9.0

func (s *Server) GetSessionIDs() []string

GetSessionIDs returns all active vended session IDs. Implements viewdef.SessionPusher.

func (*Server) GetSessions

func (s *Server) GetSessions() *session.Manager

GetSessions returns the session manager.

func (*Server) GetViewdefManager added in v0.9.0

func (s *Server) GetViewdefManager() *viewdef.ViewdefManager

GetViewdefManager returns the viewdef manager.

func (*Server) HandleFrontendCreate added in v0.9.0

func (s *Server) HandleFrontendCreate(sessionID string, parentID int64, properties map[string]string) (int64, json.RawMessage, map[string]string, error)

HandleFrontendCreate implements PathVariableHandler. It delegates to the per-session LuaSession.

func (*Server) HandleFrontendUpdate added in v0.9.0

func (s *Server) HandleFrontendUpdate(sessionID string, varID int64, value json.RawMessage) error

HandleFrontendUpdate implements PathVariableHandler. It delegates to the per-session LuaSession.

func (*Server) PushViewdefs added in v0.9.0

func (s *Server) PushViewdefs(vendedID string, viewdefs map[string]string)

PushViewdefs pushes updated viewdefs to a session. This triggers AfterBatch to detect and send the changes. Implements viewdef.SessionPusher. CRC: crc-ViewdefStore.md Sequence: seq-viewdef-hotload.md

func (*Server) SetRootSessionProvider added in v0.9.0

func (s *Server) SetRootSessionProvider(provider RootSessionProvider)

SetRootSessionProvider sets a provider for the root path "/" session. If the provider returns a session ID, that session is used instead of creating a new one. This allows MCP-style servers to serve an existing session at "/" without redirect.

func (*Server) SetSiteFS

func (s *Server) SetSiteFS(siteFS fs.FS)

SetSiteFS sets a custom filesystem for serving static files.

func (*Server) Shutdown

func (s *Server) Shutdown(ctx context.Context) error

Shutdown gracefully shuts down the server.

func (*Server) Start

func (s *Server) Start() error

Start starts the server.

func (*Server) StartAsync added in v0.9.0

func (s *Server) StartAsync(port int) (string, error)

StartAsync starts the HTTP server in a goroutine and returns the URL. Use this for MCP mode where the server runs alongside stdio MCP.

func (*Server) StartCleanupWorker

func (s *Server) StartCleanupWorker(interval time.Duration)

StartCleanupWorker starts a background worker to clean up inactive sessions.

type WebSocketEndpoint

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

WebSocketEndpoint handles WebSocket connections.

func NewWebSocketEndpoint

func NewWebSocketEndpoint(cfg *config.Config, sessions *session.Manager, handler *protocol.Handler) *WebSocketEndpoint

NewWebSocketEndpoint creates a new WebSocket endpoint.

func (*WebSocketEndpoint) Broadcast

func (ws *WebSocketEndpoint) Broadcast(sessionID string, msg *protocol.Message) error

Broadcast sends a message to all connections in a session.

func (*WebSocketEndpoint) ExecuteInSession added in v0.9.0

func (ws *WebSocketEndpoint) ExecuteInSession(sessionID string, fn func() (interface{}, error)) (interface{}, error)

ExecuteInSession executes a function within a session's executor. This serializes the execution with WebSocket message processing for the session. AfterBatch is called after execution to detect and push any changes, but only if there are active browser connections to receive the updates. Returns the result and any error from the function.

func (*WebSocketEndpoint) GenerateReconnectToken

func (ws *WebSocketEndpoint) GenerateReconnectToken(sessionID string) string

GenerateReconnectToken creates a token for validating reconnection.

func (*WebSocketEndpoint) GetSessionID

func (ws *WebSocketEndpoint) GetSessionID(connectionID string) (string, bool)

GetSessionID returns the session ID for a connection.

func (*WebSocketEndpoint) GetSessionIDForConnection

func (ws *WebSocketEndpoint) GetSessionIDForConnection(connectionID string) string

GetSessionIDForConnection returns the session ID for a connection. Returns empty string if connection is not found.

func (*WebSocketEndpoint) HandleWebSocket

func (ws *WebSocketEndpoint) HandleWebSocket(w http.ResponseWriter, r *http.Request, sessionID string)

HandleWebSocket handles incoming WebSocket connections.

func (*WebSocketEndpoint) HasConnectionsForSession added in v0.9.0

func (ws *WebSocketEndpoint) HasConnectionsForSession(sessionID string) bool

HasConnectionsForSession returns true if the session has any active connections.

func (*WebSocketEndpoint) IsConnected

func (ws *WebSocketEndpoint) IsConnected(connectionID string) bool

IsConnected checks if a connection is active.

func (*WebSocketEndpoint) IsSessionReconnectable

func (ws *WebSocketEndpoint) IsSessionReconnectable(sessionID string) bool

IsSessionReconnectable checks if a session can be rejoined. A session can be rejoined if it exists and hasn't timed out.

func (*WebSocketEndpoint) Log

func (ws *WebSocketEndpoint) Log(level int, format string, args ...interface{})

Log logs a message via the config.

func (*WebSocketEndpoint) Send

func (ws *WebSocketEndpoint) Send(connectionID string, msg *protocol.Message) error

Send sends a message to a specific connection.

func (*WebSocketEndpoint) SetAfterBatch

func (ws *WebSocketEndpoint) SetAfterBatch(callback AfterBatchCallback)

SetAfterBatch sets the callback for change detection after message processing.

func (*WebSocketEndpoint) SetOnDisconnect added in v0.9.0

func (ws *WebSocketEndpoint) SetOnDisconnect(callback DisconnectCallback)

SetOnDisconnect sets the callback for when a connection disconnects. This is used to clear sent-tracking so page refreshes resync all state.

func (*WebSocketEndpoint) ValidateReconnectToken

func (ws *WebSocketEndpoint) ValidateReconnectToken(sessionID, token string) bool

ValidateReconnectToken validates a reconnection token.

Jump to

Keyboard shortcuts

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