GitHub快速开始

API 参考取自源码中的 Go 文档注释,以英文书写。

package realtime

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

概述

Package realtime is experimental: its API and documented formats may change in a minor release. See the API stability policy. provides an in-memory notification core for a game service: notifications to accounts, delivered to the subscribers of online accounts and kept per account when persistent.

索引

变量

var ErrNotFound = errors.New("realtime: notification not found")

ErrNotFound is returned by Delete for a notification the account does not have.

类型

type Notification struct {
	ID         uint64          `json:"id"`
	To         string          `json:"to"`
	Code       string          `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: its ID (assigned by Notify), recipient, code, subject and sender, its JSON content, whether it is kept for History, and when it was created.

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

Store delivers notifications to online accounts' subscribers and keeps the persistent ones per account in memory. It is safe for concurrent use.

func NewStore() *Store

NewStore returns an empty store with every account offline.

func (s *Store) Delete(account string, id uint64) error

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

func (s *Store) History(account string, before uint64, limit int) []Notification

History returns account's persistent notifications, newest first: those with an ID below before (all when before is 0), at most limit of them (all when limit is 0).

func (s *Store) Notify(n Notification) (Notification, error)

Notify assigns n the next ID and a creation time when it has none, keeps it when it is persistent, and sends it to the recipient's subscribers when the recipient is online, skipping a subscriber whose buffer is full. A notification without a recipient or code, with a code or sender over 128 bytes, a subject over 256 bytes, or content over 1 MiB or not valid JSON is refused; Notify keeps its own copy of the content.

func (s *Store) SetOnline(account string, online bool)

SetOnline marks account online or offline; only an online account's subscribers receive notifications as they are sent.

func (s *Store) Subscribe(account string, buffer int) (<-chan Notification, func())

Subscribe returns a channel receiving account's notifications while the account is online, buffering buffer of them (16 when zero), and a function that unsubscribes and closes the channel.