package selfhost
import "github.com/nsgo-dev/game/pkg/leaderboard/selfhost"Overview
Package selfhost is a self-hostable leaderboard service, for cross-platform games and games on platforms without a game service: one board ranks the scores a player's devices submit from every platform, keyed by the account the accounts package signs in.
Boards
A versioned YAML Config declares the boards. Each has a sort order (descending for points, ascending for times), a reset period (allTime, daily or weekly, in UTC) and, for a resetting board, how many earlier periods stay readable after a reset. A board ranks each account's best score in a period; equal scores rank by who got there first.
Submitting
Service.Submit records a score for an account. Over HTTP (Service.Handler) the account is the subject of the player's account token, which the handler verifies offline with an accounts/token Verifier, so a player can only submit their own scores.
A board with validation: signed accepts a score only with a proof from the game server: after deciding a match or checking a replay, the server signs the board, account and score with a ProofSigner, and the client submits the proof beside the score. The configuration lists the servers' public keys and how long a proof stays valid.
Queries
Top pages through a period from the first rank, Around returns the entries around an account, and Friends ranks a set of accounts the game supplies. Each reads the current period, the previous one, or an earlier period the board keeps by its ID. Every board period is an order-statistic skip list in memory, so each query costs O(log n + entries returned): a few microseconds on a board of a million accounts.
Storage
The service keeps its records in a Store: NewMemoryStore for tests, or OpenFileStore, which writes one JSON Lines file per board period. New loads them and drops the periods boards no longer keep; a reset drops them as it happens.
Index
- Constants
- Variables
- type Board
- type BoardInfo
- type Config
- type Duration
- type Entry
- type FileStore
- func OpenFileStore(dir string, opts FileStoreOptions) (*FileStore, error)
- func (f *FileStore) Close() error
- func (f *FileStore) Drop(ctx context.Context, board, period string) error
- func (f *FileStore) Load(ctx context.Context, fn func(Record) error) error
- func (f *FileStore) Save(ctx context.Context, rec Record) error
- type FileStoreOptions
- type MemoryStore
- type Options
- type Order
- type Page
- type Period
- type ProofSigner
- type Record
- type Reset
- type Result
- type Service
- func New(ctx context.Context, cfg Config, opts Options) (*Service, error)
- func (s *Service) Around(ctx context.Context, board, period, account string, radius int) (Page, error)
- func (s *Service) Boards(ctx context.Context) []BoardInfo
- func (s *Service) Config() Config
- func (s *Service) Friends(ctx context.Context, board, period string, accounts []string) (Page, error)
- func (s *Service) Handler() http.Handler
- func (s *Service) Rank(ctx context.Context, board, period, account string) (Entry, error)
- func (s *Service) Submit(ctx context.Context, sub Submission) (Result, error)
- func (s *Service) Top(ctx context.Context, board, period string, offset, limit int) (Page, error)
- type Store
- type Submission
- type Validation
Constants
const (
// DefaultLimit is the number of entries GET top returns without a limit.
DefaultLimit = 25
// DefaultRadius is the radius GET around uses without one.
DefaultRadius = 5
)Query defaults the handler uses when a request leaves them out.
const (
// MaxPage is the most entries Top returns at once.
MaxPage = 100
// MaxRadius is the most entries Around returns on each side of the account.
MaxRadius = 50
// MaxFriends is the most accounts one Friends query looks up.
MaxFriends = 200
// MaxAccountLength is the longest account ID, in bytes, the service ranks.
MaxAccountLength = 128
)Query limits.
const ConfigVersion = 1ConfigVersion is the configuration file schema version this package reads and writes.
const DefaultProofTTL = 10 * time.MinuteDefaultProofTTL is how old a game server's score proof may be when the configuration sets no proofTTL.
const MaxSafeScore = 1<<53 - 1MaxSafeScore is the largest score magnitude a board accepts, 2^53-1, so a score survives a JSON number in every client, JavaScript's included.
Variables
var (
// ErrUnknownBoard means the configuration has no board of that name.
ErrUnknownBoard = errors.New("selfhost: unknown board")
// ErrUnknownPeriod means the board has no such period, or no longer keeps it.
ErrUnknownPeriod = errors.New("selfhost: unknown period")
// ErrNotRanked means the account has no score in the period.
ErrNotRanked = errors.New("selfhost: account has no score in the period")
// ErrInvalidAccount means an account ID is empty, too long, not UTF-8 or holds a control character.
ErrInvalidAccount = errors.New("selfhost: invalid account ID")
// ErrScoreOutOfRange means the score is outside the board's min and max.
ErrScoreOutOfRange = errors.New("selfhost: score out of range")
// ErrProofRequired means the board validates scores and the submission has no proof.
ErrProofRequired = errors.New("selfhost: the board needs a game server's proof")
// ErrInvalidProof means the proof is malformed, signed by a key the configuration does not list, issued in the future, or not for this board, account and score.
ErrInvalidProof = errors.New("selfhost: invalid score proof")
// ErrProofExpired means the proof is older than the configuration's proofTTL, or was issued before the current period of a daily or weekly board began.
ErrProofExpired = errors.New("selfhost: score proof expired")
// ErrInvalidQuery means a limit, offset or radius is out of range, or a Friends query names too many accounts.
ErrInvalidQuery = errors.New("selfhost: invalid query")
)Errors the service returns; the HTTP handler maps each to a status and an error code.
Types
type Board struct {
// Name is the board's key in URLs and the data directory: 1 to 64 characters of a-z, 0-9, '.', '_' and '-', starting with a letter or digit.
Name string `yaml:"name"`
// Order is the direction scores rank in.
Order Order `yaml:"order"`
// Reset is how often the board starts over.
Reset Reset `yaml:"reset"`
// WeekStart is the day a weekly board resets on, such as "monday" (the default when empty); only a weekly board may set it.
WeekStart string `yaml:"weekStart,omitempty"`
// Keep is how many earlier periods of a daily or weekly board stay readable after it resets, from 1 to MaxKeep; zero means 1. An all-time board may not set it.
Keep int `yaml:"keep,omitempty"`
// Validation is "signed" to accept only scores with a game server's proof, or empty to trust the player's client.
Validation Validation `yaml:"validation,omitempty"`
// Min is the lowest score accepted; nil means -MaxSafeScore.
Min *int64 `yaml:"min,omitempty"`
// Max is the highest score accepted; nil means MaxSafeScore.
Max *int64 `yaml:"max,omitempty"`
}Board declares one leaderboard.
type BoardInfo struct {
// Board is the board's declaration.
Board Board
// Current is the period scores count in now.
Current Period
// Previous are the earlier periods still readable, the latest first.
Previous []Period
}BoardInfo describes a board and its periods now.
type Config struct {
// Version is the schema version; it must be ConfigVersion.
Version int `yaml:"version"`
// ProofTTL is how old a game server's score proof may be, from 1s to 24h; zero means DefaultProofTTL.
ProofTTL Duration `yaml:"proofTTL,omitempty"`
// Boards are the leaderboards, in the order the service lists them.
Boards []Board `yaml:"boards"`
// ServerKeys are the game servers' Ed25519 public keys that sign score proofs. A board with validation: signed needs at least one.
ServerKeys []token.PublicKey `yaml:"serverKeys,omitempty"`
}Config is the leaderboard service's settings, kept in a YAML file:
version: 1
proofTTL: 10m
boards:
- name: high-score
order: descending
reset: allTime
- name: weekly-sprint
order: ascending
reset: weekly
weekStart: monday
keep: 4
validation: signed
min: 1
max: 3600000
serverKeys:
- id: 2317febd373fcbcd
key: hze+0cYruVRddgjkbHzgCeWWJbEsBkn6K8JNHRDf6Wg=
Unknown fields, duplicate keys and trailing documents are refused. Optional fields keep what the file says, so a parsed file marshals back to the same fields; Marshal writes them in the order above with 2-space indentation, and a file in that form reads back and writes again byte for byte.
func ParseConfig(data []byte) (Config, error)ParseConfig decodes and validates a YAML configuration. Unknown fields, duplicate keys and trailing documents are refused.
func (c Config) Board(name string) (Board, bool)Board returns the board named name and whether it exists.
func (c Config) Marshal() ([]byte, error)Marshal validates c and encodes it as deterministic 2-space YAML.
func (c Config) Validate() errorValidate checks that c is a complete version 1 configuration.
type Duration time.DurationDuration is a time.Duration written in YAML as Go duration text ("10m", "1h30m").
func (d Duration) IsZero() boolIsZero reports whether d is zero, so an omitted duration stays omitted.
func (d Duration) MarshalYAML() (any, error)MarshalYAML writes d as its shortest Go duration text: "10m" rather than "10m0s".
func (d *Duration) UnmarshalYAML(n *yaml.Node) errorUnmarshalYAML reads Go duration text.
type Entry struct {
// Rank is the 1-based rank: the better score first, then the earlier achievement, then the smaller account ID, so no two entries share a rank.
Rank int
// Account is the account ID.
Account string
// Score is the account's best score in the period.
Score int64
// Achieved is when that score was submitted.
Achieved time.Time
}Entry is an account's place on a board.
type FileStore struct {
// contains filtered or unexported fields
}FileStore is a Store in a directory of text files: one JSON Lines file per board and period, at <dir>/<board>/<period>.jsonl, each line an account's new best score:
{"account":"3f9a...","score":4200,"achieved":"2026-11-24T09:15:02.5Z"}
Save appends a line and Drop deletes a period's file. Load replays the files; it cuts off a last line a crash left unfinished, and rewrites a file whose lines are mostly superseded scores with one line per account. It is safe for concurrent use.
func OpenFileStore(dir string, opts FileStoreOptions) (*FileStore, error)OpenFileStore returns a FileStore in dir, creating the directory when it does not exist.
func (f *FileStore) Close() errorClose closes the files the store has open for appending.
func (f *FileStore) Drop(ctx context.Context, board, period string) errorDrop deletes a period's file.
func (f *FileStore) Load(ctx context.Context, fn func(Record) error) errorLoad replays every period file, boards and periods in name order.
func (f *FileStore) Save(ctx context.Context, rec Record) errorSave appends rec to its period's file.
type FileStoreOptions struct {
// Sync flushes every Save to the disk before it returns. Without it a Save reaches the operating system, which survives the process crashing but not the machine losing power.
Sync bool
}FileStoreOptions are a FileStore's settings.
type MemoryStore struct {
// contains filtered or unexported fields
}MemoryStore is a Store in memory, for tests and prototypes: its records last as long as the process. It is safe for concurrent use.
func NewMemoryStore() *MemoryStoreNewMemoryStore returns an empty MemoryStore.
func (m *MemoryStore) Drop(ctx context.Context, board, period string) errorDrop removes the records of a board's period.
func (m *MemoryStore) Load(ctx context.Context, fn func(Record) error) errorLoad calls fn for every record in the order they were saved.
func (m *MemoryStore) Periods() []stringPeriods returns the board and period pairs the store holds records for, sorted, as "board/period".
func (m *MemoryStore) Save(ctx context.Context, rec Record) errorSave appends rec.
type Options struct {
// Store keeps the records; required.
Store Store
// Tokens verifies the account service's tokens for Handler, which needs it; a Service used only from Go may leave it nil.
Tokens *token.Verifier
// Logger receives resets and store errors, never tokens or proofs; nil discards them.
Logger *slog.Logger
// Now is the service's clock; nil uses time.Now.
Now func() time.Time
// Leeway is the clock skew allowed between a game server and the service: a proof issued up to Leeway in the future is accepted, and an expired one up to Leeway late.
Leeway time.Duration
}Options are what a Service needs besides its Config.
type Order stringOrder is the direction a board ranks scores in.
const (
// Descending ranks the highest score first, as for points.
Descending Order = "descending"
// Ascending ranks the lowest score first, as for a race time.
Ascending Order = "ascending"
)The orders a board ranks in.
type Page struct {
// Board is the board's name.
Board string
// Period is the period the entries are in.
Period Period
// Total is how many accounts have a score in the period.
Total int
// Entries are the entries asked for, in rank order.
Entries []Entry
}Page is the result of a query: some entries of one period of a board.
type Period struct {
// ID names the period: AllTimePeriod for an all-time board, otherwise the UTC date it starts on, such as "2026-11-23".
ID string
// Start is when the period starts; zero for an all-time board.
Start time.Time
// End is when the next period starts; zero for an all-time board.
End time.Time
}Period is one stretch of a board between resets.
type ProofSigner struct {
// Now is the signer's clock; nil uses time.Now.
Now func() time.Time
// contains filtered or unexported fields
}ProofSigner issues score proofs on a game server: after the server has decided a match or checked a replay, it signs the board, the account and the score, and the player's client submits the proof with the score. A board with validation: signed accepts a score only with such a proof, made within the configuration's proofTTL by a key listed in its serverKeys.
A proof is the text "v1.<key id>.<unix seconds>.<signature>", the signature an Ed25519 signature in unpadded base64url. It holds no secret, but it lets anyone holding it submit that score for that account, so the server hands it only to that player.
func NewProofSigner(key ed25519.PrivateKey) (*ProofSigner, error)NewProofSigner returns a signer for key, such as one read with token.ParsePrivateKey from the PEM file leaderboardd genkey writes.
func (s *ProofSigner) PublicKey() token.PublicKeyPublicKey returns the signer's public key as a serverKeys entry for the leaderboard configuration.
func (s *ProofSigner) Sign(board, account string, score int64) (string, error)Sign returns a proof that the account scored score on the board now.
type Record struct {
// Board is the board's name.
Board string
// Period is the period's ID.
Period string
// Account is the account ID.
Account string
// Score is the best score.
Score int64
// Achieved is when the score was submitted; an earlier achievement ranks above a later one with the same score.
Achieved time.Time
}Record is an account's best score in one period of a board, as a Store keeps it.
type Reset stringReset is how often a board starts over.
const (
// AllTime never resets.
AllTime Reset = "allTime"
// Daily starts over every day at midnight UTC.
Daily Reset = "daily"
// Weekly starts over every week at midnight UTC on the board's weekStart day.
Weekly Reset = "weekly"
)The reset periods. Periods are in UTC: a daily board starts over at midnight UTC, a weekly one at midnight UTC on its weekStart day.
type Result struct {
// Period is the period the score counted in.
Period Period
// Entry is the account's entry after the submission: the new score when it improved on the account's best, the earlier best otherwise.
Entry Entry
// Total is how many accounts have a score in the period.
Total int
// Improved reports whether the score became the account's best in the period.
Improved bool
}Result is what a submission did.
type Service struct {
// contains filtered or unexported fields
}Service is the leaderboard service: the configuration's boards, each ranking every account's best score in its current period and keeping its earlier periods readable. It is safe for concurrent use.
func New(ctx context.Context, cfg Config, opts Options) (*Service, error)New returns a service with the configuration and options. It loads the store's records, serves those of each board's current period and the earlier periods the board keeps, and drops from the store only the periods that align with the board's reset and weekStart and are older than the ones it keeps. Records it cannot place are left in the store, not served, and logged as a warning: those of a board the configuration no longer declares, and those of a period that does not align, such as one stored before the board's reset or weekStart changed. A period later than the current one, which a clock that is behind sees, is loaded but not served until the clock reaches it.
func (s *Service) Around(ctx context.Context, board, period, account string, radius int) (Page, error)Around returns the account's entry with up to radius entries (0 to MaxRadius) on each side of it. Near either end of the board the window shifts so it still holds 2*radius+1 entries when the board has that many. It returns ErrNotRanked when the account has no score in the period.
func (s *Service) Boards(ctx context.Context) []BoardInfoBoards describes every board in the configuration's order, with its current period and the earlier periods still readable.
func (s *Service) Config() ConfigConfig returns the service's configuration.
func (s *Service) Friends(ctx context.Context, board, period string, accounts []string) (Page, error)Friends returns the entries of the given accounts that have a score in the period, in rank order, each with its rank on the whole board. A game passes the player's friends from wherever it keeps them (a platform's friend list, its own social graph), usually with the player's own account; duplicates are ignored. At most MaxFriends accounts are looked up at once.
func (s *Service) Handler() http.HandlerHandler serves the service over HTTP. Every request carries the player's account token as "Authorization: Bearer <token>", verified offline with Options.Tokens, whose subject is the account the request is for. Requests and responses are JSON; every response carries Cache-Control: no-store.
GET /v1/boards -> {"boards": [board]}
POST /v1/boards/{board}/scores {"score", "proof"} -> {"period", "entry", "total", "improved"}
GET /v1/boards/{board}/top?period=&offset=&limit= -> page
GET /v1/boards/{board}/around?period=&radius= -> page around the token's account
POST /v1/boards/{board}/friends?period= {"accounts": [id]} -> page of those accounts
A board is {"name", "order", "reset", "validation", "current", "previous"}; a period is {"id", "start", "end"}, start and end in RFC 3339 and absent for an all-time board; a page is {"board", "period", "total", "entries"}; an entry is {"rank", "account", "score", "achieved"}. period is "current" (the default), "previous" or an earlier period's ID; limit defaults to DefaultLimit and radius to DefaultRadius.
Errors are {"error": code} with the status the code implies: invalid_token 401; proof_required, invalid_proof and proof_expired 403; unknown_board, unknown_period and not_ranked 404; bad_request, invalid_account and score_out_of_range 400; request_too_large 413; unavailable 503 when the request was cancelled or timed out; internal 500.
The handler does not limit request rates; put it behind a rate limiter, and behind TLS. It panics when the service has no Options.Tokens.
func (s *Service) Rank(ctx context.Context, board, period, account string) (Entry, error)Rank returns the account's entry in a period, or ErrNotRanked when it has none.
func (s *Service) Submit(ctx context.Context, sub Submission) (Result, error)Submit records a score. The score counts in the board's current period and replaces the account's best there only when it is better; an equal or worse score leaves the entry as it was and reports Improved false.
func (s *Service) Top(ctx context.Context, board, period string, offset, limit int) (Page, error)Top returns up to limit entries (1 to MaxPage) of a period from rank offset+1 on. The period is "" or "current" for the current period, "previous" for the one before, or the ID of an earlier period the board still keeps.
type Store interface {
// Load calls fn for every record kept, in the order they were saved, stopping at fn's first error. A later record for the same board, period and account replaces an earlier one.
Load(ctx context.Context, fn func(Record) error) error
// Save keeps rec as the account's best score in the period, replacing the one before.
Save(ctx context.Context, rec Record) error
// Drop removes every record of a board's period, once the board no longer keeps it.
Drop(ctx context.Context, board, period string) error
}Store keeps the service's records so a restart finds the boards as they were. The service calls it with one board's calls at a time, from many goroutines across boards.
type Submission struct {
// Board is the board's name.
Board string
// Account is the account that scored, the subject of the player's verified token.
Account string
// Score is the score.
Score int64
// Proof is a game server's ProofSigner proof of the score; a board with validation: signed needs it, other boards ignore it.
Proof string
}Submission is a score for a board.
type Validation stringValidation is how a board checks where a score came from.
const SignedByServer Validation = "signed"SignedByServer accepts a score only with a proof signed by one of the configuration's serverKeys, which the game server issues for the match result or replay it checked.