rustrecon

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jul 30, 2026 License: MIT Imports: 9 Imported by: 0

README

RustRecon 🦀🎮

Go Version License Protocol

RustRecon é uma biblioteca Go idiomática e de alta performance desenhada exclusivamente para integração com a interface WebRCON de servidores do jogo Rust. Desenvolvida focando em estabilidade e segurança para ambientes de produção.

Ao invés do legado RCON TCP bruto, o Rust moderno exige WebSocket. Esta biblioteca abstrai a complexidade dos WebSockets e gerencia automaticamente as reconexões, o roteamento de mensagens (híbrido síncrono/assíncrono) e proteção estrita contra limites de taxa (rate limiting).

✨ Características

  • Roteamento Híbrido Avançado: A biblioteca sabe separar as respostas diretas dos comandos que você envia (ex: serverinfo) das mensagens soltas do servidor (broadcasts, logs e chats de jogadores). Comandos são síncronos e retornam na mesma Goroutine, eventos soltos caem num callback assíncrono.
  • Auto-Reconexão com Backoff: Se o servidor reiniciar ou houver instabilidade na rede, o RustRecon tentará reconectar continuamente utilizando intervalos exponenciais sem derrubar a sua aplicação.
  • Proteção DDoS Embutida (Rate Limiting): A engine de pacotes utiliza uma janela deslizante / token bucket (golang.org/x/time/rate) por padrão para garantir que comandos excessivos nunca flodem a porta TCP do Rust, mantendo-se dentro dos limites saudáveis.
  • Design Livre de Data-Races (Gorilla WebSocket): Separa o loop de leitura (ReadPump) e gravação (WritePump) assegurando o tráfego full-duplex permitido pelo pacote de nível de produção gorilla/websocket.
  • Sistemas de Ping/Pong: O envio rotineiro de Heartbeats evita o encerramento prematuro de conexões TCP ociosas em provedores cloud e firewalls.
  • Observabilidade: Baseado em log/slog nativo, injete seu próprio Logger para centralizar os diagnósticos.

🚀 Instalação

go get github.com/Infinity-Rust/RustRecon
Dependências

A biblioteca baseia-se em pacotes padronizados e extensivamente testados:

  • github.com/gorilla/websocket
  • golang.org/x/time/rate

(Requer Go 1.25.0+ devido à atualização da dependência x/time)


🛠️ Como Usar (Guia Rápido)

1. Inicializando e Conectando

O RustRecon usa opções amigáveis por padrão, mas é perfeitamente customizável.

package main

import (
	"context"
	"fmt"
	"time"

	rustrecon "github.com/Infinity-Rust/RustRecon"
)

func main() {
	// 1. Defina os dados de acesso: IP, Porta do WebRCON e Senha
	opts := rustrecon.DefaultOptions("127.0.0.1", 28016, "SuaSenhaSegura")
	
	// Crie o cliente com as opções
	client := rustrecon.NewClient(opts)

	// Registre um callback assíncrono para escutar eventos globais 
	// (como mensagens no console e chat de jogadores)
	client.SetBroadcastCallback(func(payload rustrecon.RustPayload) {
		fmt.Printf(" [EVENTO BROADCAST] Mensagem do Servidor: %s\n", payload.Message)
	})

	// Inicia a conexão de forma não-bloqueante
	client.Connect()
	defer client.Close()

	// Aguarde alguns instantes apenas para a rede conectar no exemplo
	time.Sleep(2 * time.Second)

	// ... continue para o envio de comandos
}
2. Enviando Comandos (Modo Síncrono)

Use a função SendCommand para executar instruções nativas do Rust. A função vai suspender a rotina até que o servidor devolva a exata resposta ligada a esse comando.

	// Cria um contexto com timeout para não travar a aplicação infinitamente
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	fmt.Println("Enviando comando 'serverinfo'...")
	resposta, err := client.SendCommand(ctx, "serverinfo")
	if err != nil {
		fmt.Printf("❌ Falha ao tentar executar o comando: %v\n", err)
		return
	}

	fmt.Printf("✅ Sucesso! Resposta do servidor:\n%s\n", resposta)

⚙️ Configuração Avançada

Se você quiser customizar configurações de memória e rede, sobrescreva os campos de ClientOptions após carregar os padrões:

opts := rustrecon.DefaultOptions("127.0.0.1", 28016, "SuaSenhaSegura")

// Alterar o tempo máximo de espera no reconnect backoff para 1 minuto
opts.MaxRetryBackoff = 60 * time.Second

// Configurar o Rate Limiter. 
// Exemplo: Capacidade de estourar 50 comandos instantâneos, restaurando 15 por segundo
opts.RateLimiter = rustrecon.NewDefaultRateLimiter(50, 15.0)

// Configurar um Logger Personalizado que salva em JSON (via log/slog)
opts.Logger = slog.New(slog.NewJSONHandler(os.Stdout, nil))

🏗️ Estrutura de Rate Limit (Proteção)

A propriedade RateLimiter nas ClientOptions é uma Interface Go. Isso significa que, se sua aplicação operar num ecossistema distribuído (vários processos acessando o mesmo servidor de Rust simultaneamente), você pode abandonar o modelo "Em-Memória" e injetar sua própria classe baseada em Redis:

type RateLimiter interface {
	Wait(ctx context.Context) error
}

Basta implementar o método Wait com qualquer driver Redis no seu app e injetá-lo nas options.


📜 Licença

Desenvolvido para a comunidade Rust 🦀 e distribuído via MIT License. Sinta-se livre para utilizar, modificar e fazer deploy em suas aplicações comerciais.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Client

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

Client represents a WebRCON connection to a Rust server. It manages the connection lifecycle, sending commands, and handling background tasks like reconnections and pings.

func NewClient

func NewClient(opts ClientOptions) *Client

NewClient initializes a new WebRCON client with the given options. If the provided options lack a Logger, it falls back to the DefaultOptions.

func (*Client) Close

func (c *Client) Close()

Close gracefully terminates the connection and background routines. It cancels the internal context, causing the read and write pumps to shut down safely.

func (*Client) Connect

func (c *Client) Connect()

Connect starts the background connection and event loops. This function initializes the connection asynchronously and manages its own reconnections via the ConnectionManager.

func (*Client) SendCommand

func (c *Client) SendCommand(ctx context.Context, cmd string) (string, error)

SendCommand sends a command synchronously, waiting for a response with the same Identifier. It returns the exact string response from the server or an error if the context times out or the connection drops.

func (*Client) SetBroadcastCallback

func (c *Client) SetBroadcastCallback(callback func(RustPayload))

SetBroadcastCallback registers a function to be called when an unsolicited message is received. Unsolicited messages include server chat, console logs, and any payload that does not match a pending synchronous command's Identifier.

type ClientOptions

type ClientOptions struct {
	IP          string
	Port        int
	Password    string
	Name        string // Application name to send in payloads
	RateLimiter RateLimiter
	Logger      *slog.Logger
	// MaxRetryBackoff is the maximum time to wait before retrying a connection.
	MaxRetryBackoff time.Duration
	// ReadBufferSize limits the size of the buffer for reading responses.
	ReadBufferSize int
	// WriteBufferSize limits the size of the buffer for sending requests.
	WriteBufferSize int
}

ClientOptions defines configuration for the WebRCON client. It includes connection credentials, rate limiting settings, logging, and buffer sizes.

func DefaultOptions

func DefaultOptions(ip string, port int, password string) ClientOptions

DefaultOptions returns ClientOptions with sensible defaults. It configures an in-memory rate limiter (20 burst, 10 events/sec), standard slog logger, and a 30-second max reconnection backoff.

type ConnectionManager

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

ConnectionManager handles the lifecycle of the WebSocket connection.

func (*ConnectionManager) Start

func (cm *ConnectionManager) Start()

type DefaultRateLimiter

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

DefaultRateLimiter uses the standard x/time/rate package to provide an in-memory sliding window/token bucket rate limiter.

func NewDefaultRateLimiter

func NewDefaultRateLimiter(burst int, eventsPerSecond float64) *DefaultRateLimiter

NewDefaultRateLimiter creates a new in-memory rate limiter. burst specifies maximum burst size, and eventsPerSecond specifies operations per second.

func (*DefaultRateLimiter) Wait

func (d *DefaultRateLimiter) Wait(ctx context.Context) error

Wait blocks until a token is available.

type Engine

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

Engine manages pending synchronous requests and async event dispatching.

func (*Engine) Dispatch

func (e *Engine) Dispatch(payload RustPayload)

Dispatch processes an incoming payload from the read pump.

func (*Engine) SendCommandSync

func (e *Engine) SendCommandSync(ctx context.Context, payload RustPayload) (string, error)

SendCommandSync enqueues a command and waits for the specific response.

func (*Engine) SetBroadcastCallback

func (e *Engine) SetBroadcastCallback(cb func(RustPayload))

SetBroadcastCallback sets the callback.

type RateLimiter

type RateLimiter interface {
	// Wait blocks until a rate limit token is available or context is cancelled.
	Wait(ctx context.Context) error
}

RateLimiter defines the interface for rate limiting outbound commands. It allows users to plug in custom implementations (e.g., Redis-based limiters for distributed setups) or use the default in-memory token bucket.

type RustPayload

type RustPayload struct {
	Identifier int    `json:"Identifier"`
	Message    string `json:"Message"`
	Name       string `json:"Name"`
}

RustPayload represents the exact JSON structure required by Rust's WebRCON. The Identifier field is used to map server responses to the original client requests.

Jump to

Keyboard shortcuts

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