server

package
v1.4.3 Latest Latest
Warning

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

Go to latest
Published: Mar 12, 2026 License: MIT Imports: 21 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CreateError

func CreateError(err string) []byte

CreateError creates a JSON-encoded error response with the given error message. The returned byte slice is ready to be sent over the connection.

func InitError

func InitError(err error) []byte

InitError creates a JSON-encoded error response from the given error. If err is nil, it returns an error response with "Unknown" as the message.

func MakeResult

func MakeResult(utype common.UpdateType, res any) []byte

MakeResult creates a JSON-encoded success response with the given update type and result data. The returned byte slice is ready to be sent over the connection.

Types

type AddParams added in v1.4.1

type AddParams struct {
	URL         string          `json:"url"`
	FileName    string          `json:"fileName,omitempty"`
	Dir         string          `json:"dir,omitempty"`
	Headers     warplib.Headers `json:"headers,omitempty"`
	Connections int32           `json:"connections,omitempty"`
	SSHKeyPath  string          `json:"sshKeyPath,omitempty"`
}

AddParams is the input for download.add.

type AddResult added in v1.4.1

type AddResult struct {
	GID string `json:"gid"`
}

AddResult is the response for download.add.

type DownloadCompleteNotification added in v1.4.1

type DownloadCompleteNotification struct {
	GID         string `json:"gid"`
	TotalLength int64  `json:"totalLength"`
}

DownloadCompleteNotification is sent when a download completes.

type DownloadErrorNotification added in v1.4.1

type DownloadErrorNotification struct {
	GID   string `json:"gid"`
	Error string `json:"error"`
}

DownloadErrorNotification is sent when a download encounters an error.

type DownloadProgressNotification added in v1.4.1

type DownloadProgressNotification struct {
	GID             string `json:"gid"`
	CompletedLength int64  `json:"completedLength"`
}

DownloadProgressNotification is sent during download progress.

type DownloadStartedNotification added in v1.4.1

type DownloadStartedNotification struct {
	GID         string `json:"gid"`
	FileName    string `json:"fileName"`
	TotalLength int64  `json:"totalLength"`
}

DownloadStartedNotification is sent when a download begins.

type EmptyResult added in v1.4.1

type EmptyResult struct{}

EmptyResult is a placeholder for methods that return no data.

type Error

type Error struct {
	Type    ErrorType `json:"error_type"`
	Message string    `json:"message"`
}

Error represents a download error with a severity type and descriptive message. It implements the error interface for use with standard Go error handling.

func (*Error) Error

func (e *Error) Error() string

Error returns the error message string, implementing the error interface.

type ErrorType

type ErrorType int

ErrorType represents the severity level of a download error.

const (
	// ErrorTypeCritical indicates a fatal error that stops the download.
	ErrorTypeCritical ErrorType = iota
	// ErrorTypeWarning indicates a non-fatal error that allows the download to continue.
	ErrorTypeWarning
)

type GIDParam added in v1.4.1

type GIDParam struct {
	GID string `json:"gid"`
}

GIDParam is a common input with just a download GID.

type HandlerFunc

type HandlerFunc func(
	conn *SyncConn,
	pool *Pool,
	body json.RawMessage,
) (
	common.UpdateType,
	any,
	error,
)

HandlerFunc defines the signature for RPC request handlers. It receives a synchronized connection, connection pool, and the raw JSON message body. It returns the update type for the response, the response payload, and any error encountered.

type ListItem added in v1.4.1

type ListItem struct {
	GID             string `json:"gid"`
	Status          string `json:"status"`
	TotalLength     int64  `json:"totalLength"`
	CompletedLength int64  `json:"completedLength"`
	FileName        string `json:"fileName"`
}

ListItem is a single entry in the download.list response.

type ListParams added in v1.4.1

type ListParams struct {
	Status string `json:"status,omitempty"` // "active", "waiting", "complete", "all" (default)
}

ListParams is the input for download.list.

type ListResult added in v1.4.1

type ListResult struct {
	Downloads []*ListItem `json:"downloads"`
}

ListResult is the response for download.list.

type Pool

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

Pool manages active download connections and their associated errors. It provides thread-safe operations for tracking which downloads are active, broadcasting messages to all connections watching a download, and storing errors that occur during downloads.

func NewPool

func NewPool(l *log.Logger) *Pool

NewPool creates a new Pool instance with the given logger. The pool is initialized with empty connection and error maps.

func (*Pool) AddConnection

func (p *Pool) AddConnection(uid string, sconn *SyncConn)

AddConnection adds a new connection to an existing download's connection list. The connection will receive broadcast messages for the specified download. Fixed Race 5: Single write lock instead of RLock-unlock-Lock to prevent TOCTOU.

func (*Pool) AddDownload

func (p *Pool) AddDownload(uid string, sconn *SyncConn)

AddDownload registers a new download in the pool with the given unique identifier. If sconn is nil, an empty connection slice is created for later connections to join. If sconn is provided, it becomes the first connection watching this download.

func (*Pool) Broadcast

func (p *Pool) Broadcast(uid string, data []byte)

Broadcast sends the given data to all connections watching the specified download. Connections that fail to receive the message are automatically removed from the pool. Fixed Race 6: Copy slice before iteration, batch removals to prevent corruption.

func (*Pool) ForceWriteError

func (p *Pool) ForceWriteError(uid string, errType ErrorType, errMessage string)

ForceWriteError stores an error for the specified download, overwriting any existing error. Unlike WriteError, this always overwrites regardless of error severity.

func (*Pool) GetError

func (p *Pool) GetError(uid string) *Error

GetError retrieves the stored error for the specified download. Returns nil if no error has been recorded for the download.

func (*Pool) HasDownload

func (p *Pool) HasDownload(uid string) bool

HasDownload reports whether a download with the given unique identifier exists in the pool.

func (*Pool) StopDownload

func (p *Pool) StopDownload(uid string)

StopDownload removes a download from the pool by its unique identifier. This should be called when a download completes or is cancelled.

func (*Pool) WriteError

func (p *Pool) WriteError(uid string, errType ErrorType, errMessage string)

WriteError stores an error for the specified download. If a critical error already exists and the new error is not critical, the existing critical error is preserved. Fixed Race bonus: Single write lock to prevent TOCTOU.

type RPCConfig added in v1.4.1

type RPCConfig struct {
	Secret    string // Auth token (required -- empty means RPC disabled)
	ListenAll bool   // If true, bind to 0.0.0.0 instead of 127.0.0.1
	Version   string // Daemon version
	Commit    string // Git commit
	BuildType string // Build type
}

RPCConfig holds configuration for the JSON-RPC endpoint.

type RPCNotifier added in v1.4.1

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

RPCNotifier maintains a set of connected jrpc2 WebSocket servers and broadcasts push notifications to all of them.

func NewRPCNotifier added in v1.4.1

func NewRPCNotifier(l *log.Logger) *RPCNotifier

NewRPCNotifier creates a new notifier.

func (*RPCNotifier) Broadcast added in v1.4.1

func (n *RPCNotifier) Broadcast(method string, params any)

Broadcast sends a push notification to all registered servers. Servers that fail to receive (e.g., disconnected) are unregistered.

func (*RPCNotifier) Count added in v1.4.1

func (n *RPCNotifier) Count() int

Count returns the number of registered servers (for testing).

func (*RPCNotifier) Register added in v1.4.1

func (n *RPCNotifier) Register(srv *jrpc2.Server)

Register adds a server to the broadcast set.

func (*RPCNotifier) Unregister added in v1.4.1

func (n *RPCNotifier) Unregister(srv *jrpc2.Server)

Unregister removes a server from the broadcast set.

type RPCServer added in v1.4.1

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

RPCServer manages the JSON-RPC 2.0 bridge and method handlers.

func NewRPCServer added in v1.4.1

func NewRPCServer(cfg *RPCConfig, m *warplib.Manager, client *http.Client, pool *Pool, router *warplib.SchemeRouter, l *log.Logger) *RPCServer

NewRPCServer creates a new RPCServer with method handlers and HTTP bridge.

func (*RPCServer) Close added in v1.4.1

func (rs *RPCServer) Close()

Close shuts down the jrpc2 bridge, releasing internal goroutines.

type Request

type Request struct {
	Method  common.UpdateType `json:"method"`
	Message json.RawMessage   `json:"message,omitempty"`
}

Request represents an incoming RPC request from a CLI client. It contains the method to invoke and an optional JSON message payload.

func ParseRequest

func ParseRequest(b []byte) (*Request, error)

ParseRequest deserializes a JSON byte slice into a Request struct. It returns an error if the JSON is malformed or cannot be unmarshaled.

type Response

type Response struct {
	Ok     bool    `json:"ok"`
	Error  string  `json:"error,omitempty"`
	Update *Update `json:"update,omitempty"`
}

Response represents an RPC response sent to CLI clients. A successful response has Ok set to true and contains an Update. A failed response has Ok set to false and contains an Error message.

type Server

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

Server manages RPC connections from CLI clients over a Unix socket or named pipe. It dispatches incoming requests to registered handlers and manages the connection pool for active downloads. Transport priority (platform-specific): - Unix: Unix socket > TCP - Windows: Named pipe > TCP

func NewServer

func NewServer(l *log.Logger, m *warplib.Manager, port int, client *http.Client, router *warplib.SchemeRouter, rpcCfg *RPCConfig) *Server

NewServer creates a new Server instance with the given logger, download manager, and port number. The server uses platform-specific IPC as the primary transport, falling back to TCP on the specified port if the primary transport fails.

func (*Server) RegisterHandler

func (s *Server) RegisterHandler(method common.UpdateType, handler HandlerFunc)

RegisterHandler associates a handler function with a specific update type method. When a request with the given method is received, the corresponding handler is invoked.

func (*Server) Shutdown added in v1.2.0

func (s *Server) Shutdown() error

Shutdown gracefully stops the server by closing the listener and cleaning up resources. It uses common.ShutdownTimeout for the web server shutdown timeout.

func (*Server) Start

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

Start begins listening for incoming connections and blocks until the context is canceled. It first starts the web server in a separate goroutine, then creates a platform-specific listener (Unix socket/named pipe with TCP fallback) and accepts connections in a loop. Each connection is handled in its own goroutine.

type StatusResult added in v1.4.1

type StatusResult struct {
	GID             string `json:"gid"`
	Status          string `json:"status"`
	TotalLength     int64  `json:"totalLength"`
	CompletedLength int64  `json:"completedLength"`
	Percentage      int64  `json:"percentage"`
	FileName        string `json:"fileName"`
}

StatusResult is the response for download.status.

type SyncConn

type SyncConn struct {
	Conn net.Conn
	// contains filtered or unexported fields
}

SyncConn wraps a net.Conn with mutex-protected read and write operations. It ensures thread-safe access to the underlying connection when multiple goroutines need to read from or write to the same connection.

func NewSyncConn

func NewSyncConn(conn net.Conn) *SyncConn

NewSyncConn creates a new SyncConn wrapping the given network connection. The returned SyncConn is ready for concurrent read and write operations.

func (*SyncConn) Read

func (s *SyncConn) Read() ([]byte, error)

Read receives data from the connection in a thread-safe manner. It acquires a read lock before reading to prevent concurrent reads.

func (*SyncConn) Write

func (s *SyncConn) Write(b []byte) error

Write sends the given byte slice to the connection in a thread-safe manner. It acquires a write lock before writing to prevent concurrent writes.

type Update

type Update struct {
	Type    common.UpdateType `json:"type"`
	Message any               `json:"message,omitempty"`
}

Update contains the payload of a successful response. It wraps the update type and the associated message data.

type VersionResult added in v1.4.1

type VersionResult struct {
	Version   string `json:"version"`
	Commit    string `json:"commit,omitempty"`
	BuildType string `json:"buildType,omitempty"`
}

VersionResult is the response for system.getVersion.

type WebServer

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

func NewWebServer

func NewWebServer(l *log.Logger, m *warplib.Manager, pool *Pool, port int, client *http.Client, router *warplib.SchemeRouter, rpcCfg *RPCConfig) *WebServer

func (*WebServer) Shutdown added in v1.2.0

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

Shutdown gracefully stops the web server and cleans up RPC resources.

func (*WebServer) Start

func (s *WebServer) Start() error

Jump to

Keyboard shortcuts

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