protocol

package
v0.0.7 Latest Latest
Warning

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

Go to latest
Published: Mar 26, 2026 License: MIT Imports: 9 Imported by: 0

Documentation

Overview

Package protocol implements the XxSql communication protocols.

Index

Constants

View Source
const (
	MagicPrivate = "XXSQ"
	MagicLen     = 4
)

Magic bytes for protocol identification

View Source
const (
	MsgHandshakeRequest  byte = 0x01
	MsgHandshakeResponse byte = 0x02
	MsgAuthRequest       byte = 0x03
	MsgAuthResponse      byte = 0x04
	MsgQueryRequest      byte = 0x05
	MsgQueryResponse     byte = 0x06
	MsgPing              byte = 0x07
	MsgPong              byte = 0x08
	MsgError             byte = 0x09
	MsgClose             byte = 0x0A
	MsgBatchRequest      byte = 0x0B
	MsgBatchResponse     byte = 0x0C
)

Message types for private protocol

View Source
const (
	ProtocolV1 = 1 // Basic protocol
	ProtocolV2 = 2 // v1.1.0: Batch operations, compression
	ProtocolV3 = 3 // v1.2.0: Streaming queries
)

Protocol versions

View Source
const (
	StatusOK    byte = 0x00
	StatusError byte = 0x01
	StatusAuth  byte = 0x02
)

Status codes for responses

View Source
const HeaderSize = 13

Header size: Magic(4) + Length(4) + Type(1) + SeqID(4) = 13 bytes

View Source
const MaxMessageSize = 10 * 1024 * 1024

MaxMessageSize is the maximum allowed message size (10MB)

Variables

This section is empty.

Functions

func MessageType

func MessageType(t byte) string

MessageType returns a string representation of the message type.

func WriteMessage

func WriteMessage(w io.Writer, msgType byte, seqID uint32, payload []byte) error

WriteMessage writes a message to the writer.

Types

type AuthRequest

type AuthRequest struct {
	Username string
	Password []byte // Hashed or encrypted password
	Database string // Optional database to connect to
}

AuthRequest is sent by the client to authenticate.

func DecodeAuthRequest

func DecodeAuthRequest(payload []byte) (*AuthRequest, error)

DecodeAuthRequest decodes an auth request from bytes.

func (*AuthRequest) Encode

func (r *AuthRequest) Encode() []byte

Encode encodes the auth request to bytes.

type AuthResponse

type AuthResponse struct {
	Status     byte
	Message    string
	SessionID  string
	Permission uint32
}

AuthResponse is sent by the server in response to authentication.

func DecodeAuthResponse

func DecodeAuthResponse(payload []byte) (*AuthResponse, error)

DecodeAuthResponse decodes an auth response from bytes.

func (*AuthResponse) Encode

func (r *AuthResponse) Encode() []byte

Encode encodes the auth response to bytes.

type ColumnInfo

type ColumnInfo struct {
	Name     string
	Type     string
	Nullable bool
}

ColumnInfo describes a result column.

type ConnectionHandler

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

ConnectionHandler handles a single client connection.

func NewConnectionHandler

func NewConnectionHandler(conn net.Conn, opts ...ConnectionOption) *ConnectionHandler

NewConnectionHandler creates a new connection handler.

func (*ConnectionHandler) Close

func (h *ConnectionHandler) Close() error

Close closes the connection.

func (*ConnectionHandler) CreatedAt

func (h *ConnectionHandler) CreatedAt() time.Time

CreatedAt returns the connection creation time.

func (*ConnectionHandler) Database

func (h *ConnectionHandler) Database() string

Database returns the current database.

func (*ConnectionHandler) Handle

func (h *ConnectionHandler) Handle(ctx context.Context) error

Handle handles the connection lifecycle.

func (*ConnectionHandler) IsClosed

func (h *ConnectionHandler) IsClosed() bool

IsClosed returns whether the connection is closed.

func (*ConnectionHandler) LastActiveAt

func (h *ConnectionHandler) LastActiveAt() time.Time

LastActiveAt returns the last activity time.

func (*ConnectionHandler) LocalAddr

func (h *ConnectionHandler) LocalAddr() net.Addr

LocalAddr returns the local address.

func (*ConnectionHandler) RemoteAddr

func (h *ConnectionHandler) RemoteAddr() net.Addr

RemoteAddr returns the remote address.

func (*ConnectionHandler) SessionID

func (h *ConnectionHandler) SessionID() string

SessionID returns the session ID.

func (*ConnectionHandler) Username

func (h *ConnectionHandler) Username() string

Username returns the authenticated username.

type ConnectionOption

type ConnectionOption func(*ConnectionHandler)

ConnectionOption is a functional option for ConnectionHandler.

func WithAuthHandler

func WithAuthHandler(fn func(conn *ConnectionHandler, req *AuthRequest) (*AuthResponse, error)) ConnectionOption

WithAuthHandler sets the auth handler.

func WithCloseHandler

func WithCloseHandler(fn func(conn *ConnectionHandler)) ConnectionOption

WithCloseHandler sets the close handler.

func WithHandshakeHandler

func WithHandshakeHandler(fn func(conn *ConnectionHandler, req *HandshakeRequest) (*HandshakeResponse, error)) ConnectionOption

WithHandshakeHandler sets the handshake handler.

func WithMaxMessageSize

func WithMaxMessageSize(size uint32) ConnectionOption

WithMaxMessageSize sets the maximum message size.

func WithQueryHandler

func WithQueryHandler(fn func(conn *ConnectionHandler, req *QueryRequest) (*QueryResponse, error)) ConnectionOption

WithQueryHandler sets the query handler.

func WithReadTimeout

func WithReadTimeout(d time.Duration) ConnectionOption

WithReadTimeout sets the read timeout.

func WithWriteTimeout

func WithWriteTimeout(d time.Duration) ConnectionOption

WithWriteTimeout sets the write timeout.

type ConnectionState

type ConnectionState int32

ConnectionState represents the state of a connection.

const (
	StateInit      ConnectionState = iota // Initial state
	StateHandshake                        // Waiting for handshake
	StateAuth                             // Waiting for authentication
	StateReady                            // Authenticated and ready
	StateQuery                            // Executing a query
	StateClosing                          // Connection closing
	StateClosed                           // Connection closed
)

func (ConnectionState) String

func (s ConnectionState) String() string

String returns a string representation of the connection state.

type ErrorPayload

type ErrorPayload struct {
	Code    uint32
	Message string
	Detail  string
}

ErrorPayload represents an error message payload.

func DecodeErrorPayload

func DecodeErrorPayload(payload []byte) (*ErrorPayload, error)

DecodeErrorPayload decodes an error payload from bytes.

func (*ErrorPayload) Encode

func (e *ErrorPayload) Encode() []byte

Encode encodes the error payload to bytes.

type HandshakeRequest

type HandshakeRequest struct {
	ProtocolVersion uint16
	ClientVersion   string
	ClientInfo      string
	Extensions      []string // Supported extensions
}

HandshakeRequest is sent by the client to initiate a connection.

func DecodeHandshakeRequest

func DecodeHandshakeRequest(payload []byte) (*HandshakeRequest, error)

DecodeHandshakeRequest decodes a handshake request from bytes.

func (*HandshakeRequest) Encode

func (r *HandshakeRequest) Encode() []byte

Encode encodes the handshake request to bytes.

type HandshakeResponse

type HandshakeResponse struct {
	ProtocolVersion uint16
	ServerVersion   string
	Supported       bool
	Downgrade       bool
	AuthChallenge   []byte // Challenge for authentication
	Extensions      []string
}

HandshakeResponse is sent by the server in response to a handshake.

func DecodeHandshakeResponse

func DecodeHandshakeResponse(payload []byte) (*HandshakeResponse, error)

DecodeHandshakeResponse decodes a handshake response from bytes.

func (*HandshakeResponse) Encode

func (r *HandshakeResponse) Encode() []byte

Encode encodes the handshake response to bytes.

type Header struct {
	Magic  [MagicLen]byte
	Length uint32
	Type   byte
	SeqID  uint32
}

Header represents a message header.

func ReadHeader

func ReadHeader(r io.Reader) (*Header, error)

ReadHeader reads and parses a message header from the reader.

type Message

type Message struct {
	Header  Header
	Payload []byte
}

Message represents a complete protocol message.

func DecodeMessage

func DecodeMessage(data []byte) (*Message, error)

DecodeMessage decodes a message from bytes.

func NewMessage

func NewMessage(msgType byte, seqID uint32, payload []byte) *Message

NewMessage creates a new message with the given type and payload.

func ReadMessage

func ReadMessage(r io.Reader) (*Message, error)

ReadMessage reads a complete message from the reader.

func (*Message) Encode

func (m *Message) Encode() ([]byte, error)

Encode encodes the message to bytes.

type QueryRequest

type QueryRequest struct {
	SQL       string
	Params    [][]byte // Prepared statement parameters
	BatchMode bool     // Is this part of a batch?
}

QueryRequest is sent by the client to execute a query.

func DecodeQueryRequest

func DecodeQueryRequest(payload []byte) (*QueryRequest, error)

DecodeQueryRequest decodes a query request from bytes.

func (*QueryRequest) Encode

func (r *QueryRequest) Encode() []byte

Encode encodes the query request to bytes.

type QueryResponse

type QueryResponse struct {
	Status       byte
	Message      string
	Columns      []ColumnInfo
	Rows         [][]interface{}
	RowCount     uint32
	Affected     uint32
	LastInsertID uint64
	ExecuteTime  uint32 // milliseconds
}

QueryResponse is sent by the server with query results.

func DecodeQueryResponse

func DecodeQueryResponse(payload []byte) (*QueryResponse, error)

DecodeQueryResponse decodes a query response from bytes.

func (*QueryResponse) Encode

func (r *QueryResponse) Encode() []byte

Encode encodes the query response to bytes.

type Server

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

Server is a TCP server for the private protocol.

func NewServer

func NewServer(config *ServerConfig) *Server

NewServer creates a new TCP server.

func (*Server) Addr

func (s *Server) Addr() net.Addr

Addr returns the server address.

func (*Server) Broadcast

func (s *Server) Broadcast(msgType byte, payload []byte) error

Broadcast sends a message to all active connections.

func (*Server) ConnectionCount

func (s *Server) ConnectionCount() int

ConnectionCount returns the current connection count.

func (*Server) Connections

func (s *Server) Connections() []*ConnectionHandler

Connections returns a slice of active connections.

func (*Server) IsRunning

func (s *Server) IsRunning() bool

IsRunning returns whether the server is running.

func (*Server) SetAuthHandler

func (s *Server) SetAuthHandler(fn func(conn *ConnectionHandler, req *AuthRequest) (*AuthResponse, error))

SetAuthHandler sets the auth handler.

func (*Server) SetConnectHandler

func (s *Server) SetConnectHandler(fn func(conn *ConnectionHandler))

SetConnectHandler sets the connect handler.

func (*Server) SetDisconnectHandler

func (s *Server) SetDisconnectHandler(fn func(conn *ConnectionHandler))

SetDisconnectHandler sets the disconnect handler.

func (*Server) SetHandshakeHandler

func (s *Server) SetHandshakeHandler(fn func(conn *ConnectionHandler, req *HandshakeRequest) (*HandshakeResponse, error))

SetHandshakeHandler sets the handshake handler.

func (*Server) SetQueryHandler

func (s *Server) SetQueryHandler(fn func(conn *ConnectionHandler, req *QueryRequest) (*QueryResponse, error))

SetQueryHandler sets the query handler.

func (*Server) Start

func (s *Server) Start() error

Start starts the server.

func (*Server) Stop

func (s *Server) Stop() error

Stop stops the server.

type ServerConfig

type ServerConfig struct {
	Bind           string
	Port           int
	MaxConnections int
	ReadTimeout    time.Duration
	WriteTimeout   time.Duration
	MaxMessageSize uint32
	AcceptBacklog  int
}

ServerConfig holds server configuration.

func DefaultServerConfig

func DefaultServerConfig() *ServerConfig

DefaultServerConfig returns the default server configuration.

Jump to

Keyboard shortcuts

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