client

package
v0.4.0-rc.3 Latest Latest
Warning

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

Go to latest
Published: Dec 4, 2026 License: Apache-2.0 Imports: 15 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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

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

func New(opts Options) (*Client, error)

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) Buffered

func (c *Client) Buffered() int

Buffered returns the number of queued events waiting for Poll or Drain.

func (*Client) Close

func (c *Client) Close() error

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

func (c *Client) DeleteNotification(ctx context.Context, id uint64) error

DeleteNotification deletes one persistent notification belonging to the signed-in account over HTTP (DELETE /v1/notifications/{id}).

func (*Client) Drain

func (c *Client) Drain(fn func(Event)) int

Drain pops every currently queued Event in arrival order and passes it to fn, returning how many events were drained.

func (*Client) Dropped

func (c *Client) Dropped() int

Dropped returns how many queued events were dropped because the event queue reached Options.MaxEvents.

func (*Client) Follow

func (c *Client) Follow(accounts ...string) error

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

func (c *Client) Poll() (Event, bool)

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

func (c *Client) Request(ctx context.Context, msgType string, body any) (json.RawMessage, error)

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

func (c *Client) Send(msgType string, body any) error

Send transmits an application-level envelope (such as realtime.TypeParty) over the active WebSocket without waiting for an acknowledgement.

func (*Client) SetStatus

func (c *Client) SetStatus(status string) error

SetStatus sets the local user's short status string (up to 128 bytes) and replays it automatically after reconnects.

func (*Client) Start

func (c *Client) Start(ctx context.Context)

Start launches the background connection and reconnect loop. Calling Start more than once or after Close is a no-op.

func (*Client) State

func (c *Client) State() State

State returns the client's current connection state.

func (*Client) Unfollow

func (c *Client) Unfollow(accounts ...string) error

Unfollow stops receiving online status updates for accounts and removes them from the reconnect replay set.

type DialFunc

type DialFunc func(ctx context.Context, rawURL string, opts wsclient.Options) (Socket, error)

DialFunc opens one Socket connection to rawURL with opts.

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

type ServerError struct {
	Code    string
	Message string
}

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
)

Jump to

Keyboard shortcuts

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