Documentation
¶
Overview ¶
Package client is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.
Package client provides a reconnecting realtime WebSocket and notification inbox client for NSGo games on both native targets and the browser (GOOS=js GOARCH=wasm).
Call New followed by Start to maintain one authenticated WebSocket session in the background with exponential backoff. Inside the game loop's Update callback, call Poll or Drain without blocking to consume incoming notifications, online status updates, and connection lifecycle events. Follow, Unfollow, and SetStatus update the active session and are automatically replayed after reconnects. ListNotifications and DeleteNotification access the persistent notification inbox over HTTP.
Index ¶
- type Client
- func (c *Client) Buffered() int
- func (c *Client) Close() error
- func (c *Client) DeleteNotification(ctx context.Context, id uint64) error
- func (c *Client) Drain(fn func(Event)) int
- func (c *Client) Dropped() int
- func (c *Client) Follow(accounts ...string) error
- func (c *Client) ListNotifications(ctx context.Context, cursor string, limit int) (realtime.Page, error)
- func (c *Client) Poll() (Event, bool)
- func (c *Client) Request(ctx context.Context, msgType string, body any) (json.RawMessage, error)
- func (c *Client) Send(msgType string, body any) error
- func (c *Client) SetStatus(status string) error
- func (c *Client) Start(ctx context.Context)
- func (c *Client) State() State
- func (c *Client) Unfollow(accounts ...string) error
- type DialFunc
- type Event
- type EventKind
- type Options
- type ServerError
- type Socket
- type State
Examples ¶
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 maintains one reconnecting realtime WebSocket connection and exposes non-blocking event polling for a game loop, plus HTTP inbox helpers. It is safe for concurrent use.
func New ¶
New validates opts and returns a Client ready for Start.
Example ¶
New configures a reconnecting client whose events are drained on the game loop.
package main
import (
"context"
"fmt"
"github.com/nsgo-dev/game/pkg/online/realtime/client"
)
func main() {
cli, err := client.New(client.Options{
URL: "https://api.example.com",
Token: "account-jwt",
Device: "desktop-1",
})
if err != nil {
fmt.Println(err)
return
}
defer func() { _ = cli.Close() }()
// Inside game startup, call cli.Start(ctx); inside Update, call cli.Drain:
_ = context.Background()
fmt.Println(cli.State() == client.StateDisconnected, cli.Buffered())
}
Output: true 0
func (*Client) Close ¶
Close stops reconnecting, closes any active socket cleanly, and waits for the background goroutine to finish. It is safe to call multiple times.
func (*Client) DeleteNotification ¶
DeleteNotification deletes one persistent notification belonging to the signed-in account over HTTP (DELETE /v1/notifications/{id}).
func (*Client) Drain ¶
Drain pops every currently queued Event in arrival order and passes it to fn, returning how many events were drained.
func (*Client) Dropped ¶
Dropped returns how many queued events were dropped because the event queue reached Options.MaxEvents.
func (*Client) Follow ¶
Follow subscribes to online status updates for accounts. The followed set is remembered and automatically re-sent after reconnects.
func (*Client) ListNotifications ¶
func (c *Client) ListNotifications(ctx context.Context, cursor string, limit int) (realtime.Page, error)
ListNotifications fetches one cursor-paginated page of persistent notifications over HTTP (GET /v1/notifications).
func (*Client) Poll ¶
Poll pops the oldest queued Event without blocking, returning false when the queue is empty. Call Poll (or Drain) from the game loop's Update method.
func (*Client) Request ¶
Request transmits an application-level envelope (such as realtime.TypeParty) over the active WebSocket and waits for the matching server ack (returning AckBody.Data) or error envelope.
func (*Client) Send ¶
Send transmits an application-level envelope (such as realtime.TypeParty) over the active WebSocket without waiting for an acknowledgement.
func (*Client) SetStatus ¶
SetStatus sets the local user's short status string (up to 128 bytes) and replays it automatically after reconnects.
func (*Client) Start ¶
Start launches the background connection and reconnect loop. Calling Start more than once or after Close is a no-op.
type Event ¶
type Event struct {
Kind EventKind
Account string
Device string
Session string
MaxFollow int
Notification *realtime.Notification
Status *realtime.StatusEvent
Code string
Message string
CloseCode int
CloseReason string
Err error
}
Event is one game-loop event popped by Poll or visited by Drain.
type EventKind ¶
type EventKind int
EventKind identifies the type of an Event queued for the game loop.
const ( // EventConnected reports that the socket opened and completed its welcome handshake. EventConnected EventKind = iota + 1 // EventDisconnected reports that the socket closed or dropped. EventDisconnected // EventNotification carries a pushed realtime.Notification. EventNotification // EventStatus carries a pushed realtime.StatusEvent for a followed account. EventStatus // EventError carries a server error envelope or dial/protocol failure. EventError )
type Options ¶
type Options struct {
// URL is either the service base URL (http:// or https://, e.g. "https://api.example.com"
// or "https://api.example.com/realtime") or the full socket URL (ws:// or wss:// ending
// in /v1/socket).
URL string
// Token is a static bearer token used when TokenProvider is nil.
Token string
// TokenProvider returns a fresh bearer token for each dial and HTTP request.
// When set, it takes precedence over Token.
TokenProvider func(ctx context.Context) (string, error)
// Device is an optional device identifier bound to the session (one socket
// per account per device).
Device string
// InitialBackoff is the first reconnect delay after a failed dial or drop.
// Zero uses 250ms.
InitialBackoff time.Duration
// MaxBackoff caps exponential reconnect backoff. Zero uses 30s.
MaxBackoff time.Duration
// PollInterval sets how often the background pump checks wsclient.Client.Recv.
// Zero uses 5ms.
PollInterval time.Duration
// MaxEvents bounds queued game-loop events; when full, the oldest event is
// dropped and Dropped increments. Zero uses 256; negative is unbounded.
MaxEvents int
// HTTPClient is used by ListNotifications and DeleteNotification. Zero uses
// http.DefaultClient.
HTTPClient *http.Client
// Dial overrides wsclient.Dial when non-nil (useful for deterministic tests).
Dial DialFunc
}
Options configures a realtime Client.
type ServerError ¶
ServerError is returned by Client.Request when the server replies with an error envelope for that request ID.
func (*ServerError) Error ¶
func (e *ServerError) Error() string
Error implements the error interface.
type Socket ¶
type Socket interface {
SendText(text string) error
Recv() (wsclient.Message, bool)
State() wsclient.State
Err() error
CloseStatus() (code int, reason string)
Close(code int, reason string) error
}
Socket is the minimal WebSocket connection interface used by Client. *wsclient.Client satisfies it on both native targets and js/wasm; tests may supply an in-process implementation through Options.Dial.
type State ¶
type State int
State reports the client's current connection lifecycle state.
const ( // StateDisconnected means the client is not currently connected (either not started yet or waiting for a backoff retry). StateDisconnected State = iota // StateConnecting means a WebSocket dial or welcome handshake is in progress. StateConnecting // StateConnected means the WebSocket is open and has received its welcome frame. StateConnected // StateClosed means Close was called (or the session was permanently replaced) and no further reconnects will occur. StateClosed )