Documentation
¶
Overview ¶
Package bercon implements BattlEye RCon v2 transport and supervises connections to multiple servers. It handles UDP framing, authentication, correlated multipart responses, and acknowledged server events.
Use Dial for one endpoint. Its context bounds socket setup and authentication; the resulting Client lives until Client.Close or a terminal transport failure. Commands are sent once. If cancellation happens after transmission, ErrCommandOutcomeUnknown means the server may still have executed the command. Command responses and unsolicited server events use separate APIs: Client.Command returns the response, while Client.Messages streams events.
For collectors, NewFleet supervises one independent Client and UDP socket per Target. Fleet.Run limits simultaneous logins and retries failed sessions with bounded jittered backoff. Fleet.Command uses the current session, while Fleet.Status and Fleet.Statuses expose connection and outage state.
Fleet.Messages combines events from all targets and identifies their source. Use one reader and fan events out in the application.
Client and Fleet event queues are bounded so slow consumers cannot block protocol processing. They drop new events by default. Set Options.DropOldestMessages or FleetOptions.DropOldestMessages to keep newer events instead. Read Client.DroppedMessages or Fleet.DroppedMessages to observe queue loss.
Index ¶
- Constants
- Variables
- type Client
- type Fleet
- func (f *Fleet) Command(ctx context.Context, targetID, command string) ([]byte, error)
- func (f *Fleet) DroppedMessages() uint64
- func (f *Fleet) Messages() <-chan FleetMessage
- func (f *Fleet) Run(ctx context.Context, handler SessionHandler) error
- func (f *Fleet) Status(targetID string) (TargetStatus, bool)
- func (f *Fleet) Statuses() []TargetStatus
- type FleetMessage
- type FleetOptions
- type Message
- type Options
- type SessionHandler
- type Target
- type TargetInfo
- type TargetState
- type TargetStatus
Examples ¶
Constants ¶
const ( // DefaultMinReconnectDelay is the shortest reconnect backoff window. DefaultMinReconnectDelay = time.Second // DefaultMaxReconnectDelay is the longest reconnect backoff window. DefaultMaxReconnectDelay = 10 * time.Minute // DefaultMaxConcurrentDials limits simultaneous login attempts. DefaultMaxConcurrentDials = 4 // DefaultStableSessionDuration resets backoff after a healthy session. DefaultStableSessionDuration = time.Minute )
Variables ¶
var ( // ErrClosed means the client has been closed. ErrClosed = errors.New("RCon client is closed") // ErrCommandOutcomeUnknown means a command may have reached the server, // but the client cannot confirm whether it was executed. ErrCommandOutcomeUnknown = errors.New("RCon command outcome is unknown") // ErrLoginFailed means the server rejected the supplied credentials. ErrLoginFailed = errors.New("RCon login failed") // ErrLoginTimeout means all configured login attempts timed out. ErrLoginTimeout = errors.New("RCon login timed out") // ErrResponseTimeout means the command may have executed without a response. ErrResponseTimeout = fmt.Errorf("RCon response timed out: %w", ErrCommandOutcomeUnknown) // ErrCommandTooLong means the command exceeds the compatibility datagram limit. ErrCommandTooLong = errors.New("RCon command exceeds datagram limit") // ErrResponseTooLarge means the response exceeds MaxResponseBytes. ErrResponseTooLarge = errors.New("RCon response exceeds configured limit") // ErrProtocol means the server returned a conflicting or invalid response. ErrProtocol = errors.New("invalid RCon protocol response") // ErrFleetRunning means Run is already active for this fleet. ErrFleetRunning = errors.New("RCon fleet is already running") ErrTargetUnavailable = errors.New("RCon fleet target is unavailable") )
Functions ¶
This section is empty.
Types ¶
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is an authenticated RCon connection.
func Dial ¶
Dial authenticates a connected UDP socket. The context bounds dialing and login only; after success, the returned Client has an independent lifetime controlled by Close.
Example ¶
package main
import (
"context"
"time"
"github.com/woozymasta/bercon"
)
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
client, err := bercon.Dial(ctx, "127.0.0.1:2305", "secret", nil)
if err != nil {
return
}
defer func() { _ = client.Close() }()
_, _ = client.Command(ctx, "players")
}
Output:
func (*Client) Command ¶
Command sends one application datagram and waits for its correlated response.
func (*Client) Done ¶
func (c *Client) Done() <-chan struct{}
Done closes after the client has stopped and all client-owned goroutines exit.
func (*Client) DroppedMessages ¶
DroppedMessages reports events dropped because an application or pre-login queue was full.
type Fleet ¶
type Fleet struct {
// contains filtered or unexported fields
}
Fleet supervises independent RCon clients, each with its own UDP socket. Construct it with NewFleet and run it until its context is canceled.
func NewFleet ¶
func NewFleet(targets []Target, options FleetOptions) (*Fleet, error)
NewFleet validates and copies targets for independent supervised sessions. Credentials remain in memory for the fleet lifetime so reconnects can log in.
Example ¶
package main
import (
"context"
"fmt"
"time"
"github.com/woozymasta/bercon"
)
func main() {
targets := []bercon.Target{
{ID: "eu-1", Address: "127.0.0.1:2305", Password: "secret"},
{ID: "eu-2", Address: "127.0.0.1:2306", Password: "secret"},
}
fleet, err := bercon.NewFleet(targets, bercon.FleetOptions{
MaxConcurrentDials: 2,
ExpireAfter: 30 * time.Minute,
})
if err != nil {
return
}
ctx, cancel := context.WithCancel(context.Background())
done := make(chan error, 1)
go func() { done <- fleet.Run(ctx, nil) }()
_, _ = fleet.Command(ctx, "eu-1", "players")
_, _ = fleet.Status("eu-1")
cancel()
if err := <-done; err != context.Canceled {
fmt.Printf("Fleet.Run returned %v after cancellation\n", err)
return
}
}
Output:
func (*Fleet) Command ¶
Command sends one command through the target's current authenticated client. A command is never replayed when the session changes during the call.
func (*Fleet) DroppedMessages ¶
DroppedMessages reports events discarded by the fleet-wide message queue.
func (*Fleet) Messages ¶
func (f *Fleet) Messages() <-chan FleetMessage
Messages returns the bounded stream of server events from every target session. The channel stays open across Run calls; stop readers with the Run context. Receives are shared between consumers, so use one reader and fan events out explicitly.
Example ¶
package main
import (
"fmt"
"github.com/woozymasta/bercon"
)
func main() {
fleet, err := bercon.NewFleet([]bercon.Target{
{ID: "eu-1", Address: "127.0.0.1:2305", Password: "secret"},
}, bercon.FleetOptions{
MessageBuffer: 512,
DropOldestMessages: true,
})
if err != nil {
panic(err)
}
select {
case event := <-fleet.Messages():
fmt.Printf("%s: %s\n", event.TargetID, event.Message.Data)
default:
fmt.Println("waiting for server events")
}
}
Output: waiting for server events
func (*Fleet) Run ¶
func (f *Fleet) Run(ctx context.Context, handler SessionHandler) error
Run starts one supervisor per target and returns when ctx is canceled. A handler return closes that target's client and schedules a fresh login. Run returns ctx.Err after all target workers have stopped.
func (*Fleet) Status ¶
func (f *Fleet) Status(targetID string) (TargetStatus, bool)
Status returns a copy of the latest state for targetID.
func (*Fleet) Statuses ¶
func (f *Fleet) Statuses() []TargetStatus
Statuses returns detached status snapshots in the same order as configured targets.
Example ¶
package main
import (
"fmt"
"github.com/woozymasta/bercon"
)
func main() {
fleet, err := bercon.NewFleet([]bercon.Target{
{ID: "eu-1", Address: "127.0.0.1:2305", Password: "secret"},
{ID: "eu-2", Address: "127.0.0.1:2405", Password: "secret"},
}, bercon.FleetOptions{})
if err != nil {
panic(err)
}
for _, status := range fleet.Statuses() {
fmt.Println(status.ID, status.State)
}
}
Output: eu-1 stopped eu-2 stopped
type FleetMessage ¶
type FleetMessage struct {
TargetID string `json:"target_id" yaml:"target_id"` // Stable Fleet target identifier.
Message Message `json:"message" yaml:"message"` // Event payload and wire sequence.
}
FleetMessage identifies the target that produced one server event.
type FleetOptions ¶
type FleetOptions struct {
// Capacity of the fleet-wide message queue; zero uses the sum of target buffers.
MessageBuffer int `json:"message_buffer,omitempty" yaml:"message_buffer,omitempty"`
// When the fleet message queue is full, discard its oldest item instead of the new item.
DropOldestMessages bool `json:"drop_oldest_messages,omitempty" yaml:"drop_oldest_messages,omitempty"`
// Lower bound for reconnect delays; zero selects the default.
MinReconnectDelay time.Duration `json:"min_reconnect_delay,omitempty" yaml:"min_reconnect_delay,omitempty"`
// Upper bound for exponential reconnect delays; zero selects the default.
MaxReconnectDelay time.Duration `json:"max_reconnect_delay,omitempty" yaml:"max_reconnect_delay,omitempty"`
// Maximum simultaneous Dial calls; zero selects the default.
MaxConcurrentDials int `json:"max_concurrent_dials,omitempty" yaml:"max_concurrent_dials,omitempty"`
// Session lifetime after which a failure resets backoff; zero selects the default.
StableSessionDuration time.Duration `json:"stable_session_duration,omitempty" yaml:"stable_session_duration,omitempty"`
// Continuous outage duration after which a target stops retrying; zero never expires.
ExpireAfter time.Duration `json:"expire_after,omitempty" yaml:"expire_after,omitempty"`
}
FleetOptions controls reconnect timing and concurrent login attempts.
type Message ¶
type Message struct {
Data []byte `json:"data" yaml:"data"` // Opaque event payload bytes.
Sequence byte `json:"sequence" yaml:"sequence"` // Independent sequence from the wire packet.
}
Message is an independently sequenced server event.
type Options ¶
type Options struct {
// Maximum wait for each login attempt.
LoginTimeout time.Duration `json:"login_timeout" yaml:"login_timeout"`
// Number of allowed login attempts.
LoginAttempts int `json:"login_attempts" yaml:"login_attempts"`
// Maximum wait for one command response.
ResponseTimeout time.Duration `json:"response_timeout" yaml:"response_timeout"`
// Empty-command interval; zero disables keepalive.
KeepAliveInterval time.Duration `json:"keepalive_interval" yaml:"keepalive_interval"`
// Consecutive failed keepalive exchanges before the client becomes terminal.
MaxKeepAliveFailures int `json:"max_keepalive_failures" yaml:"max_keepalive_failures"`
// Capacity shared by the application queue and bounded pre-login message buffer.
MessageBuffer int `json:"message_buffer" yaml:"message_buffer"`
// When the message queue is full, discard its oldest item instead of the new item.
DropOldestMessages bool `json:"drop_oldest_messages,omitempty" yaml:"drop_oldest_messages,omitempty"`
// Maximum assembled response size.
MaxResponseBytes int `json:"max_response_bytes" yaml:"max_response_bytes"`
// Quarantine applied after uncertain command completion.
SequenceReuseDelay time.Duration `json:"sequence_reuse_delay" yaml:"sequence_reuse_delay"`
}
Options configures client timeouts and bounded queues.
func DefaultOptions ¶
func DefaultOptions() Options
DefaultOptions returns conservative BattlEye RCon v2 client defaults.
type SessionHandler ¶
type SessionHandler func(ctx context.Context, target TargetInfo, client *Client) error
SessionHandler uses one authenticated client until it returns or ctx ends. A returned error ends only that session and causes the fleet to reconnect. Handlers should return on command or connection errors and honor ctx.
type Target ¶
type Target struct {
// Client options; nil selects DefaultOptions.
Options *Options `json:"options,omitempty" yaml:"options,omitempty"`
// Stable identifier used to retrieve this target's status.
ID string `json:"id" yaml:"id"`
// Hostname or IP address and UDP port of the RCon endpoint.
Address string `json:"address" yaml:"address"`
// Password retained for future login attempts and excluded from serialization.
Password string `json:"-" yaml:"-"`
}
Target configures one independently authenticated RCon endpoint.
type TargetInfo ¶
type TargetInfo struct {
// Stable target identifier.
ID string `json:"id" yaml:"id"`
// Configured remote address.
Address string `json:"address" yaml:"address"`
}
TargetInfo exposes endpoint identity to a handler without its credentials.
type TargetState ¶
type TargetState string
TargetState describes the latest connection lifecycle state for one target.
const ( // TargetStateConnecting means the fleet is opening or authenticating a session. TargetStateConnecting TargetState = "connecting" // TargetStateOnline means an authenticated session is running its handler. TargetStateOnline TargetState = "online" // TargetStateRetrying means the last session ended and a reconnect is scheduled. TargetStateRetrying TargetState = "retrying" // TargetStateExpired means the continuous outage passed ExpireAfter. TargetStateExpired TargetState = "expired" // TargetStateStopped means the fleet context ended for this target. TargetStateStopped TargetState = "stopped" )
type TargetStatus ¶
type TargetStatus struct {
// Time when the most recent login succeeded.
LastConnected *time.Time `json:"last_connected,omitempty" yaml:"last_connected,omitempty"`
// Start of the current continuous outage; remains stable across failed dials.
OfflineSince *time.Time `json:"offline_since,omitempty" yaml:"offline_since,omitempty"`
// Most recent reconnect attempt start.
LastAttempt *time.Time `json:"last_attempt,omitempty" yaml:"last_attempt,omitempty"`
// Scheduled next attempt, absent while online, stopped, or expired.
NextAttempt *time.Time `json:"next_attempt,omitempty" yaml:"next_attempt,omitempty"`
// Stable target identifier.
ID string `json:"id" yaml:"id"`
// Configured remote address.
Address string `json:"address" yaml:"address"`
// Current lifecycle state.
State TargetState `json:"state" yaml:"state"`
// Most recent dial or session-handler error, if any.
LastError string `json:"last_error,omitempty" yaml:"last_error,omitempty"`
// Number of consecutive dial/session failures in the current outage.
ConsecutiveFailures uint64 `json:"consecutive_failures" yaml:"consecutive_failures"`
// Selected delay before the currently scheduled reconnect.
ReconnectDelay time.Duration `json:"reconnect_delay" yaml:"reconnect_delay"`
}
TargetStatus is a point-in-time view of one target's connection lifecycle.
Directories
¶
| Path | Synopsis |
|---|---|
|
Package beconfig reads BattlEye server configuration files without modifying them.
|
Package beconfig reads BattlEye server configuration files without modifying them. |
|
internal
|
|
|
testnet
Package testnet contains deterministic UDP fault-injection helpers for tests.
|
Package testnet contains deterministic UDP fault-injection helpers for tests. |
|
wire
Package wire implements the private BattlEye RCon v2 datagram codec.
|
Package wire implements the private BattlEye RCon v2 datagram codec. |
|
Package parser defines errors shared by the game-specific response parsers used with BattlEye RCon.
|
Package parser defines errors shared by the game-specific response parsers used with BattlEye RCon. |
|
ef
Package ef parses the Enfusion response format observed in Arma Reforger.
|
Package ef parses the Enfusion response format observed in Arma Reforger. |
|
rv
Package rv parses the Real Virtuality response format observed in Arma 3 and DayZ. Arma 2 uses the same engine family, but its response compatibility has not been independently verified.
|
Package rv parses the Real Virtuality response format observed in Arma 3 and DayZ. Arma 2 uses the same engine family, but its response compatibility has not been independently verified. |
|
Package server implements a BattlEye RCon v2 UDP endpoint for applications that expose commands to RCon clients or need a controlled peer for client tests.
|
Package server implements a BattlEye RCon v2 UDP endpoint for applications that expose commands to RCon clients or need a controlled peer for client tests. |