realtime

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: 24 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 realtime is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.

Package realtime provides an authenticated realtime WebSocket service, online status fan-out, and a persistent notification inbox for online game backends.

Each signed-in client opens one WebSocket connection per (account, device) at GET /v1/socket, authenticated with its account token in the opening handshake (Authorization: Bearer <token> on native clients, or the Sec-WebSocket-Protocol subprotocol nsgo-auth.<token> / nsgo-auth-b64.<b64> for browsers). Messages travel as UTF-8 JSON text frames carrying a versioned envelope {v, type, id, body}:

  • Server -> Client: "welcome", "notification", "status", "ack", "error"
  • Client -> Server: "follow", "unfollow", "status", "ping"

Notifications are sent from server code via Service.Notify. Codes below 0 are reserved for built-in platform events (CodeFriendRequest, CodeFriendAccepted, CodeGroupJoinRequest, CodeGroupJoinAccepted, CodeTournamentRoundEnd, CodeReward); game-defined events use codes >= 0. Persistent notifications are stored in a Store (in-memory via MemoryStore, or SQLite/Postgres via the sqlstore, sqlitestore, and pgstore subpackages), listed with cursor pagination over HTTP at GET /v1/notifications, and deleted by their recipient at DELETE /v1/notifications/{id}. Non-persistent notifications are delivered only to currently connected sessions and dropped for offline recipients.

Across server replicas, notifications, status updates, and duplicate-session kicks flow through the Bus interface (MemoryBus in-process by default, or pgstore.Bus over Postgres LISTEN/NOTIFY).

Index

Examples

Constants

View Source
const (
	// BusEventNotification carries a full Notification for local delivery.
	BusEventNotification = "notification"
	// BusEventNotificationRef carries a persistent notification ID to load from
	// the shared Store when the full notification exceeded MaxBusPayloadBytes.
	BusEventNotificationRef = "notification_ref"
	// BusEventStatus carries an online/offline or status-text change for fan-out.
	BusEventStatus = "status"
	// BusEventKick notifies other replicas that a newer session replaced (To, Device).
	BusEventKick = "kick"
)

Cross-process Bus event kinds carried in BusEvent.Kind.

View Source
const (
	// ProtocolVersion is the current JSON envelope version carried in Envelope.V.
	ProtocolVersion = 1

	// Subprotocol is the RFC 6455 WebSocket subprotocol negotiated for realtime sockets.
	Subprotocol = "nsgo-realtime.v1"

	// AuthSubprotocolPrefix carries a raw RFC 7230 token-safe bearer token in
	// Sec-WebSocket-Protocol for browser clients that cannot set HTTP headers.
	AuthSubprotocolPrefix = "nsgo-auth."

	// AuthSubprotocolB64Prefix carries an unpadded base64url-encoded bearer token
	// in Sec-WebSocket-Protocol when the token contains characters outside the
	// RFC 7230 token alphabet.
	AuthSubprotocolB64Prefix = "nsgo-auth-b64."

	// CloseReplaced is the application WebSocket close code sent to an earlier
	// session when a newer socket replaces it for the same (account, device).
	CloseReplaced = 4000

	// CloseUnauthorized is the application WebSocket close code sent when a
	// connection is closed due to authentication or authorization failure.
	CloseUnauthorized = 4001

	// MaxAccountBytes is the maximum length of an account ID in bytes.
	MaxAccountBytes = 256

	// MaxDeviceBytes is the maximum length of a device ID in bytes.
	MaxDeviceBytes = 128

	// MaxStatusBytes is the maximum length of a user status string in bytes.
	MaxStatusBytes = 128

	// MaxSubjectBytes is the maximum length of a notification subject in bytes.
	MaxSubjectBytes = 256

	// MaxContentBytes is the maximum length of a notification JSON payload in bytes.
	MaxContentBytes = 1 << 20

	// MaxClientFrameBytes is the maximum size of a JSON text frame accepted from a client.
	MaxClientFrameBytes = 64 << 10

	// MaxBusPayloadBytes is the conservative byte limit for direct inline payloads
	// published over a cross-process Bus (kept below PostgreSQL's 8000-byte NOTIFY cap).
	MaxBusPayloadBytes = 7500

	// DefaultMaxFollow is the default cap on accounts a single session may follow.
	DefaultMaxFollow = 200

	// DefaultListLimit is the default page size for GET /v1/notifications.
	DefaultListLimit = 50

	// MaxListLimit is the maximum page size accepted by GET /v1/notifications.
	MaxListLimit = 200

	// DefaultOutboxSize is the default number of outbound envelopes buffered per socket.
	DefaultOutboxSize = 64
)

Protocol constants for the realtime WebSocket envelope and limits.

View Source
const (
	TypeWelcome      = "welcome"
	TypeNotification = "notification"
	TypeStatus       = "status"
	TypeFollow       = "follow"
	TypeUnfollow     = "unfollow"
	TypePing         = "ping"
	TypeParty        = "party"
	TypeAck          = "ack"
	TypeError        = "error"
)

Envelope message types carried in Envelope.Type.

View Source
const (
	// CodeFriendRequest notifies an account of an incoming friend request.
	CodeFriendRequest = -1
	// CodeFriendAccepted notifies an account that its friend request was accepted.
	CodeFriendAccepted = -2
	// CodeGroupJoinRequest notifies group moderators of a pending join request.
	CodeGroupJoinRequest = -3
	// CodeGroupJoinAccepted notifies an account that its group join request was approved.
	CodeGroupJoinAccepted = -4
	// CodeTournamentRoundEnd notifies participants that a tournament round ended.
	CodeTournamentRoundEnd = -5
	// CodeReward notifies an account of a newly granted reward in the reward inbox.
	CodeReward = -6
	// CodePartyInvite notifies an account of an invitation to join a party.
	CodePartyInvite = -7
	// CodePartyJoinRequest notifies a party leader of a pending join request.
	CodePartyJoinRequest = -8
	// CodePartyJoinAccepted notifies an account that its party join request was approved.
	CodePartyJoinAccepted = -9
	// CodePartyUpdated notifies party members of membership, leader, label, or queue state changes.
	CodePartyUpdated = -10
	// CodePartyClosed notifies party members that the party closed or they were removed.
	CodePartyClosed = -11
	// CodePartyMatchFound notifies party members of a match result or seat reservation.
	CodePartyMatchFound = -12
	// CodePartyData carries a relayed party data message between party members.
	CodePartyData = -13
)

Reserved built-in notification codes. Every code below 0 is reserved for platform events; game-defined notifications use codes >= 0.

Variables

View Source
var (
	// ErrNotFound reports a persistent notification that does not exist or belongs to another account.
	ErrNotFound = errors.New("realtime: notification not found")
	// ErrInvalidNotification reports a notification that fails validation.
	ErrInvalidNotification = errors.New("realtime: invalid notification")
	// ErrInvalidAccount reports an empty, oversized, or malformed account ID.
	ErrInvalidAccount = errors.New("realtime: invalid account")
	// ErrInvalidDevice reports an oversized or malformed device ID.
	ErrInvalidDevice = errors.New("realtime: invalid device")
	// ErrInvalidStatus reports a status string over MaxStatusBytes or containing invalid UTF-8 or control bytes.
	ErrInvalidStatus = errors.New("realtime: invalid status")
	// ErrInvalidCursor reports a malformed pagination cursor.
	ErrInvalidCursor = errors.New("realtime: invalid cursor")
	// ErrFollowLimit reports a Follow request that would exceed MaxFollow.
	ErrFollowLimit = errors.New("realtime: follow limit exceeded")
	// ErrDuplicateSession reports a rejected duplicate socket for an already-connected (account, device).
	ErrDuplicateSession = errors.New("realtime: duplicate session")
	// ErrPayloadTooLarge reports an event or message that exceeds the transport or bus size limit.
	ErrPayloadTooLarge = errors.New("realtime: payload too large")
	// ErrClosed reports an operation attempted after Close.
	ErrClosed = errors.New("realtime: closed")
)

Sentinel errors returned by realtime stores, services, and buses.

Functions

func DecodeBody

func DecodeBody(raw json.RawMessage, dst any) error

DecodeBody strictly decodes an envelope's raw JSON body into dst, refusing unknown fields and trailing data.

func EncodeAuthSubprotocol

func EncodeAuthSubprotocol(token string) string

EncodeAuthSubprotocol formats token as a Sec-WebSocket-Protocol token entry so browser clients can authenticate during the WebSocket opening handshake without custom HTTP headers.

func EncodeEnvelope

func EncodeEnvelope(msgType, id string, body any) ([]byte, error)

EncodeEnvelope serializes a version-1 Envelope with body marshaled as JSON.

func IsReservedCode

func IsReservedCode(code int) bool

IsReservedCode reports whether code is in the reserved built-in range (code < 0).

func NormalizeLimit

func NormalizeLimit(limit int) int

NormalizeLimit clamps limit to [1, MaxListLimit], using DefaultListLimit when limit <= 0.

func ParseAuthSubprotocol

func ParseAuthSubprotocol(proto string) (string, bool)

ParseAuthSubprotocol extracts a bearer token from one Sec-WebSocket-Protocol entry formatted with AuthSubprotocolPrefix or AuthSubprotocolB64Prefix.

func ParseCursor

func ParseCursor(cursor string) (uint64, error)

ParseCursor parses a pagination cursor into the exclusive upper-bound ID. An empty cursor returns (0, nil).

func ValidateAccount

func ValidateAccount(account string) error

ValidateAccount checks that account is a non-empty UTF-8 identifier of at most MaxAccountBytes bytes without ASCII control characters.

func ValidateDevice

func ValidateDevice(device string) error

ValidateDevice checks that device is valid UTF-8 of at most MaxDeviceBytes bytes without ASCII control characters. Empty device is valid.

func ValidateNotification

func ValidateNotification(n Notification) error

ValidateNotification checks every field of n before storage or delivery.

func ValidateStatus

func ValidateStatus(status string) error

ValidateStatus checks that status is valid UTF-8 of at most MaxStatusBytes (128) bytes without ASCII control characters. Empty status clears the text.

Types

type AckBody

type AckBody struct {
	OK   bool            `json:"ok"`
	Data json.RawMessage `json:"data,omitempty"`
}

AckBody is the body of a server-to-client "ack" envelope.

type Bus

type Bus interface {
	// Publish broadcasts event to every active subscriber on the bus.
	Publish(ctx context.Context, event BusEvent) error
	// Subscribe registers fn to receive published events and returns a cancel
	// function that unsubscribes fn.
	Subscribe(ctx context.Context, fn func(BusEvent)) (cancel func(), err error)
}

Bus distributes realtime events across service processes. Implementations must be safe for concurrent use.

type BusEvent

type BusEvent struct {
	V              int             `json:"v"`
	Kind           string          `json:"kind"`
	Origin         string          `json:"origin"`
	To             string          `json:"to,omitempty"`
	Device         string          `json:"device,omitempty"`
	SessionID      string          `json:"sessionId,omitempty"`
	Notification   *Notification   `json:"notification,omitempty"`
	NotificationID uint64          `json:"notificationId,omitempty"`
	Status         *StatusEvent    `json:"status,omitempty"`
	Payload        json.RawMessage `json:"payload,omitempty"`
}

BusEvent is one event broadcast between realtime service replicas over a Bus.

type Config

type Config struct {
	// Verify authenticates bearer tokens on WebSocket handshakes and HTTP
	// notification endpoints. Required for Handler(); may be nil if Service is
	// only used in-process.
	Verify TokenVerifier

	// Store persists notifications marked Persistent. When nil, NewMemoryStore()
	// is used.
	Store Store

	// Bus distributes notifications, status changes, and duplicate-session kicks
	// across service replicas. When nil, NewMemoryBus() is used.
	Bus Bus

	// Friends, when non-nil, lists friend account IDs to automatically follow
	// whenever an account connects a socket (up to MaxFollow).
	Friends FriendLister

	// AllowedOrigins lists browser origins allowed to call HTTP endpoints and
	// open WebSockets. Validated with the same rules as accounts and cloudsave.
	// When empty, clients without an Origin header (native games) are allowed,
	// and browser requests with an Origin header must match the request Host.
	AllowedOrigins []string

	// MaxFollow caps how many accounts one session may follow simultaneously.
	// Zero uses DefaultMaxFollow (200).
	MaxFollow int

	// DuplicatePolicy controls duplicate (account, device) connections.
	// Zero uses DuplicateReplaceOld.
	DuplicatePolicy DuplicatePolicy

	// OutboxSize bounds outbound WebSocket frames queued per session.
	// Zero uses DefaultOutboxSize (64).
	OutboxSize int

	// PingInterval sets how often the server sends RFC 6455 Ping frames.
	// Zero uses 30s; a negative value disables server pings.
	PingInterval time.Duration

	// PongTimeout sets the read idle deadline refreshed on each incoming frame
	// or Pong. Zero uses 60s.
	PongTimeout time.Duration

	// WriteTimeout bounds each individual WebSocket frame write. Zero uses 10s.
	WriteTimeout time.Duration

	// Now supplies the clock for timestamps. Zero uses time.Now.
	Now func() time.Time
}

Config configures a realtime Service.

type DuplicatePolicy

type DuplicatePolicy int

DuplicatePolicy controls what happens when a second socket connects for an (account, device) pair that already has an active session.

const (
	// DuplicateReplaceOld closes the earlier session with CloseReplaced (4000)
	// and admits the newer connection. This is the zero-value default.
	DuplicateReplaceOld DuplicatePolicy = iota
	// DuplicateRejectNew refuses the newer handshake with HTTP 409 Conflict
	// while keeping the existing session open.
	DuplicateRejectNew
)

type Envelope

type Envelope struct {
	V    int             `json:"v"`
	Type string          `json:"type"`
	ID   string          `json:"id,omitempty"`
	Body json.RawMessage `json:"body,omitempty"`
}

Envelope is the versioned JSON text frame carried on the realtime WebSocket in both directions.

func DecodeEnvelope

func DecodeEnvelope(data []byte) (Envelope, error)

DecodeEnvelope strictly decodes a JSON text frame into an Envelope, refusing unknown fields, trailing data, and unsupported protocol versions.

type ErrorBody

type ErrorBody struct {
	Code    string `json:"code"`
	Message string `json:"message,omitempty"`
}

ErrorBody is the body of a server-to-client "error" envelope.

func (ErrorBody) Error

func (e ErrorBody) Error() string

Error implements error so MessageHandler implementations can return structured WebSocket error codes.

type FollowBody

type FollowBody struct {
	Accounts []string `json:"accounts"`
}

FollowBody is the body of client-to-server "follow" and "unfollow" envelopes.

type FriendLister

type FriendLister interface {
	Friends(ctx context.Context, account string) ([]string, error)
}

FriendLister returns the account IDs that a newly connected account should automatically follow for online status updates.

type FriendListerFunc

type FriendListerFunc func(ctx context.Context, account string) ([]string, error)

FriendListerFunc adapts a function to FriendLister.

func (FriendListerFunc) Friends

func (f FriendListerFunc) Friends(ctx context.Context, account string) ([]string, error)

Friends calls f(ctx, account).

type MemoryBus

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

MemoryBus is an in-process Bus suitable for single-process deployments and multi-service unit tests. It is safe for concurrent use.

func NewMemoryBus

func NewMemoryBus() *MemoryBus

NewMemoryBus returns a new in-process Bus.

func (*MemoryBus) Close

func (b *MemoryBus) Close() error

Close stops future Publish and Subscribe calls and clears registered subscribers.

func (*MemoryBus) Publish

func (b *MemoryBus) Publish(ctx context.Context, event BusEvent) error

Publish delivers a cloned copy of event to all active subscribers.

func (*MemoryBus) Subscribe

func (b *MemoryBus) Subscribe(ctx context.Context, fn func(BusEvent)) (func(), error)

Subscribe registers fn to receive published events.

type MemoryStore

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

MemoryStore is an in-memory Store for persistent notifications. It is safe for concurrent use.

func NewMemoryStore

func NewMemoryStore() *MemoryStore

NewMemoryStore returns an empty in-memory Store.

func (*MemoryStore) Delete

func (m *MemoryStore) Delete(ctx context.Context, account string, id uint64) error

Delete removes account's persistent notification id, or returns ErrNotFound.

func (*MemoryStore) Get

func (m *MemoryStore) Get(ctx context.Context, account string, id uint64) (Notification, error)

Get returns account's stored notification id, or ErrNotFound.

func (*MemoryStore) List

func (m *MemoryStore) List(ctx context.Context, account string, cursor string, limit int) (Page, error)

List returns account's persistent notifications newest first with cursor pagination.

func (*MemoryStore) Save

Save persists n in memory, assigning the next monotonic ID and UTC creation time (truncated to milliseconds to match SQL stores) when Created is zero.

type MessageHandler

type MessageHandler func(ctx context.Context, account string, env Envelope) (reply any, err error)

MessageHandler handles a custom client-to-server Envelope type on an authenticated WebSocket session. When err is non-nil, an ErrorBody (if err unwraps to ErrorBody) or generic error envelope is sent back to the session; otherwise, if env.ID is non-empty, an ack envelope is sent carrying reply as optional JSON data.

type Notification

type Notification struct {
	ID         uint64          `json:"id"`
	To         string          `json:"to"`
	Code       int             `json:"code"`
	Subject    string          `json:"subject,omitempty"`
	Sender     string          `json:"sender,omitempty"`
	Content    json.RawMessage `json:"content,omitempty"`
	Persistent bool            `json:"persistent,omitempty"`
	Created    time.Time       `json:"created"`
}

Notification is one message to an account. Persistent notifications are stored in a Store for HTTP cursor pagination (GET /v1/notifications) and deletion by the recipient; non-persistent notifications are delivered only while the recipient is connected and dropped when offline.

Codes below 0 are reserved for built-in events (such as CodeFriendRequest, CodeGroupJoinRequest, and CodeTournamentRoundEnd); game-defined events use codes >= 0.

func CloneNotification

func CloneNotification(n Notification) Notification

CloneNotification returns a deep copy of n so callers cannot mutate stored or queued Content slices.

type Page

type Page struct {
	Notifications []Notification `json:"notifications"`
	NextCursor    string         `json:"nextCursor,omitempty"`
}

Page is one cursor-paginated page of persistent notifications, ordered newest first.

type Service

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

Service manages authenticated realtime WebSocket sessions, online status fan-out, and persistent notification delivery. It is safe for concurrent use.

Example

A Service delivers notifications to connected sessions, stores persistent notifications in its Store for cursor-paginated listing, and drops non-persistent notifications for offline recipients.

package main

import (
	"context"
	"encoding/json"
	"fmt"
	"time"

	"github.com/nsgo-dev/game/pkg/online/realtime"
)

func main() {
	ctx := context.Background()
	svc, err := realtime.NewService(realtime.Config{})
	if err != nil {
		fmt.Println(err)
		return
	}
	defer func() { _ = svc.Close() }()

	created := time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC)
	_, _ = svc.Notify(ctx, realtime.Notification{
		To:         "ana",
		Code:       realtime.CodeFriendRequest,
		Subject:    "Friend request",
		Sender:     "ben",
		Content:    json.RawMessage(`{"from":"ben"}`),
		Persistent: true,
		Created:    created,
	})
	_, _ = svc.Notify(ctx, realtime.Notification{
		To:         "ana",
		Code:       100,
		Subject:    "Match ping",
		Persistent: false,
		Created:    created,
	})

	page, err := svc.ListNotifications(ctx, "ana", "", 10)
	if err != nil {
		fmt.Println(err)
		return
	}
	for _, n := range page.Notifications {
		fmt.Println("stored", n.ID, n.Code, n.Subject)
	}
	fmt.Println(svc.DeleteNotification(ctx, "ana", 1))
	fmt.Println(svc.DeleteNotification(ctx, "ana", 1))
}
Output:
stored 1 -1 Friend request
<nil>
realtime: notification not found

func NewService

func NewService(cfg Config) (*Service, error)

NewService constructs a Service from cfg, subscribing to cfg.Bus so events published on other replicas reach locally connected sessions.

func (*Service) ActiveSessions

func (s *Service) ActiveSessions() int

ActiveSessions returns the number of currently open local WebSocket sessions.

func (*Service) AddStatusListener

func (s *Service) AddStatusListener(fn func(StatusEvent)) func()

AddStatusListener registers fn to be invoked whenever any account transitions online or offline across local and remote replica sessions. The returned function unregisters the listener.

func (*Service) Bus

func (s *Service) Bus() Bus

Bus returns the cross-process Bus configured for the service.

func (*Service) Close

func (s *Service) Close() error

Close unsubscribes from the Bus, closes all active WebSocket connections with close code 1001 (Going Away), and waits for session goroutines to exit.

func (*Service) DeleteNotification

func (s *Service) DeleteNotification(ctx context.Context, account string, id uint64) error

DeleteNotification deletes account's persistent notification id, or returns ErrNotFound if it does not exist or belongs to another account.

func (*Service) Follow

func (s *Service) Follow(account, device string, targets ...string) error

Follow adds target accounts to the active session for (account, device), respecting MaxFollow, and pushes each newly followed account's current status.

func (*Service) Following

func (s *Service) Following(account, device string) []string

Following returns a sorted copy of the accounts currently followed by (account, device)'s local session, or nil if no such session exists.

func (*Service) Handler

func (s *Service) Handler() http.Handler

Handler serves the realtime WebSocket endpoint and HTTP persistent notification inbox:

GET    /v1/socket                             -> WebSocket upgrade
GET    /v1/notifications?cursor=&limit=       -> {"notifications":[...],"nextCursor":"..."}
DELETE /v1/notifications/{id}                 -> 204 No Content

Every endpoint requires a valid account token verified by Config.Verify. Native clients pass "Authorization: Bearer <token>". Browser WebSocket clients may instead pass the token in Sec-WebSocket-Protocol via EncodeAuthSubprotocol ("nsgo-auth.<token>" or "nsgo-auth-b64.<b64>"), while negotiating Subprotocol ("nsgo-realtime.v1"). Every HTTP response carries Cache-Control: no-store.

func (*Service) ListNotifications

func (s *Service) ListNotifications(ctx context.Context, account string, cursor string, limit int) (Page, error)

ListNotifications returns one cursor-paginated page of account's persistent notifications, newest first.

func (*Service) NodeID

func (s *Service) NodeID() string

NodeID returns this service instance's unique replica identifier.

func (*Service) Notify

func (s *Service) Notify(ctx context.Context, n Notification) (Notification, error)

Notify delivers n to n.To. When n.Persistent is true, n is first saved in the service's Store so offline recipients can retrieve it later via GET /v1/notifications. When n.Persistent is false, n is delivered only to currently connected sessions (locally and across replicas via Bus) and dropped if the recipient is offline.

func (*Service) Online

func (s *Service) Online(account string) (StatusEvent, bool)

Online reports account's current online status and status text as known by this service (combining local sessions and remote replica status updates).

func (*Service) RegisterHandler

func (s *Service) RegisterHandler(msgType string, fn MessageHandler) (func(), error)

RegisterHandler registers fn to handle custom client-to-server Envelope messages of msgType (such as TypeParty). Built-in types (ping, follow, unfollow, status, welcome, notification, ack, error) cannot be overridden. The returned function unregisters the handler.

func (*Service) SetStatus

func (s *Service) SetStatus(ctx context.Context, account, status string) error

SetStatus updates an online account's status string (up to MaxStatusBytes) and fans out the updated StatusEvent to local and remote followers.

func (*Service) Store

func (s *Service) Store() Store

Store returns the persistent notification Store configured for the service.

func (*Service) Unfollow

func (s *Service) Unfollow(account, device string, targets ...string) error

Unfollow removes target accounts from the active session for (account, device).

type SetStatusBody

type SetStatusBody struct {
	Status string `json:"status"`
}

SetStatusBody is the body of a client-to-server "status" envelope.

type StatusEvent

type StatusEvent struct {
	Account string    `json:"account"`
	Online  bool      `json:"online"`
	Status  string    `json:"status,omitempty"`
	Updated time.Time `json:"updated"`
}

StatusEvent is the body of a server-to-client "status" envelope describing an account's current online state and optional short status text.

type Store

type Store interface {
	// Save persists n, assigning a monotonically increasing positive ID and a
	// UTC Created timestamp when zero, and returns the stored copy.
	Save(ctx context.Context, n Notification) (Notification, error)
	// Get returns account's stored notification id, or ErrNotFound.
	Get(ctx context.Context, account string, id uint64) (Notification, error)
	// List returns account's persistent notifications newest first. When cursor
	// is non-empty it continues strictly after the previous page; limit <= 0
	// uses DefaultListLimit and values above MaxListLimit are clamped.
	List(ctx context.Context, account string, cursor string, limit int) (Page, error)
	// Delete removes account's persistent notification id, or returns ErrNotFound.
	Delete(ctx context.Context, account string, id uint64) error
}

Store persists notifications marked Persistent per recipient account. Implementations must be safe for concurrent use.

type TokenVerifier

type TokenVerifier func(ctx context.Context, token string) (accountID string, err error)

TokenVerifier verifies an account token presented during the WebSocket handshake or HTTP API request and returns the authenticated account ID.

type WelcomeBody

type WelcomeBody struct {
	Account   string `json:"account"`
	Device    string `json:"device,omitempty"`
	Session   string `json:"session"`
	MaxFollow int    `json:"maxFollow"`
}

WelcomeBody is the body of a server-to-client "welcome" envelope sent right after a socket finishes authentication.

Directories

Path Synopsis
Package client is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.
Package client is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.
Package pgstore is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.
Package pgstore is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.
Package sqlitestore is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.
Package sqlitestore is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.
Package sqlstore is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.
Package sqlstore is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.
Package storetest is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.
Package storetest is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.

Jump to

Keyboard shortcuts

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