API 레퍼런스는 소스 코드의 Go 문서 주석에서 추출되며 영어로 작성되어 있습니다.
package selfhost
import "github.com/nsgo-dev/game/pkg/online/leaderboard/selfhost"개요
Package selfhost is experimental: its API and documented formats may change in a minor release. See the API stability policy. 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/authtoken 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.
Operators
DeleteAccount removes an account's entries, Hide leaves an account out of every other player's pages while it still sees its own, and ResetBoard starts a board over before its time. Each change shows at once and the Store keeps it. AdminRoutes serves them, with board listings, on the admin listener of package admin, behind the permissions PermRead, PermDelete, PermHide and PermReset.
색인
- 상수
- 변수
- type AdminState
- type Board
- type BoardInfo
- type BoardReset
- type Config
- type Deleted
- type Duration
- type Entry
- type FileStore
- func OpenFileStore(dir string, opts FileStoreOptions) (*FileStore, error)
- func (f *FileStore) Close() error
- func (f *FileStore) DeleteAccount(ctx context.Context, board, period, account string) error
- func (f *FileStore) DeleteHidden(ctx context.Context, board, account string) 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) LoadAdmin(ctx context.Context) (AdminState, error)
- func (f *FileStore) Save(ctx context.Context, rec Record) error
- func (f *FileStore) SaveHidden(ctx context.Context, h Hidden) error
- func (f *FileStore) SaveReset(ctx context.Context, r BoardReset) error
- type FileStoreOptions
- type Hidden
- type MemoryStore
- func NewMemoryStore() *MemoryStore
- func (m *MemoryStore) DeleteAccount(ctx context.Context, board, period, account string) error
- func (m *MemoryStore) DeleteHidden(ctx context.Context, board, account string) error
- func (m *MemoryStore) Drop(ctx context.Context, board, period string) error
- func (m *MemoryStore) Load(ctx context.Context, fn func(Record) error) error
- func (m *MemoryStore) LoadAdmin(ctx context.Context) (AdminState, error)
- func (m *MemoryStore) Periods() []string
- func (m *MemoryStore) Save(ctx context.Context, rec Record) error
- func (m *MemoryStore) SaveHidden(ctx context.Context, h Hidden) error
- func (m *MemoryStore) SaveReset(ctx context.Context, r BoardReset) error
- type Operator
- type Options
- type Order
- type Page
- type Period
- type ProofSigner
- type Record
- type Reset
- type ResetResult
- type Result
- type Service
- func New(ctx context.Context, cfg Config, opts Options) (*Service, error)
- func (s *Service) AdminRoutes() []admin.Route
- 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) DeleteAccount(ctx context.Context, board, period, account string) (Deleted, error)
- func (s *Service) Friends(ctx context.Context, board, period string, accounts []string) (Page, error)
- func (s *Service) FriendsAs(ctx context.Context, viewer, board, period string, accounts []string) (Page, error)
- func (s *Service) Handler() http.Handler
- func (s *Service) HiddenAccounts(ctx context.Context, board string) ([]Hidden, error)
- func (s *Service) Hide(ctx context.Context, h Hidden) (Hidden, error)
- func (s *Service) Rank(ctx context.Context, board, period, account string) (Entry, error)
- func (s *Service) ResetBoard(ctx context.Context, board string) (ResetResult, 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)
- func (s *Service) TopAs(ctx context.Context, viewer, board, period string, offset, limit int) (Page, error)
- func (s *Service) Unhide(ctx context.Context, board, account string) error
- type Store
- type Submission
- type Tournament
- func NewTournament(cfg TournamentConfig) *Tournament
- func (t *Tournament) Config() TournamentConfig
- func (t *Tournament) EndRound(now time.Time)
- func (t *Tournament) Entrants() int
- func (t *Tournament) Join(account string, now time.Time) error
- func (t *Tournament) Round(now time.Time) (TournamentRound, bool)
- func (t *Tournament) Submit(account string, score int64, now time.Time) error
- type TournamentConfig
- type TournamentRound
- type Validation
상수
const (
// PermRead lets an operator list the boards and read their entries and hidden accounts.
PermRead = "leaderboard.read"
// PermDelete lets an operator delete an account's entries.
PermDelete = "leaderboard.delete"
// PermHide lets an operator hide and unhide an account.
PermHide = "leaderboard.hide"
// PermReset lets an operator reset a board.
PermReset = "leaderboard.reset"
)The permissions of the leaderboard's operator routes. The built-in moderator role has PermRead, PermDelete and PermHide; operator and owner have all four.
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 AdminStateVersion = 1AdminStateVersion is the version of the operator state file (AdminState) this package reads and writes.
const AllPeriods = "all"AllPeriods names every period of a board to DeleteAccount. On an all-time board it is also the only period's ID, AllTimePeriod, so both mean the same there.
const ConfigVersion = 1ConfigVersion is the configuration file schema version this package reads and writes.
const DefaultAudience = "leaderboard"DefaultAudience is the token audience the service accepts when Config.Audience is empty. The account service issues tokens for it on request (accounts.Service.RefreshFor), never at sign-in, so the token a player sends a game server cannot submit scores for the player.
const DefaultProofTTL = 10 * time.MinuteDefaultProofTTL is how old a game server's score proof may be when the configuration sets no proofTTL.
const MaxHideReason = 256MaxHideReason is the longest reason, in bytes, an operator may give for hiding an account.
const MaxMetadataBytes = 4096MaxMetadataBytes is the largest metadata payload accepted when a board does not set MetadataMaxBytes. A board may lower this limit in its configuration.
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.
변수
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")
// ErrInvalidMetadata means metadata is not valid JSON or exceeds the board limit.
ErrInvalidMetadata = errors.New("selfhost: invalid metadata")
// 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")
// ErrNotHidden means the account is not hidden on the board.
ErrNotHidden = errors.New("selfhost: account is not hidden on the board")
// ErrInvalidHide means a hiding's reason is too long or holds a control character, or its end is not in the future.
ErrInvalidHide = errors.New("selfhost: invalid hiding")
// ErrResetTooSoon means a board's current period, or its last manual reset, began less than a second before a manual reset (or after it, when the clock stepped back), so the reset would begin no new period.
ErrResetTooSoon = errors.New("selfhost: the current period began less than a second ago")
)Errors the service returns; the HTTP handler maps each to a status and an error code.
var (
// ErrTournamentClosed reports a join or submission outside an open round, or a submission from an account that has not joined a tournament that requires it.
ErrTournamentClosed = errors.New("selfhost: tournament closed")
// ErrTournamentFull reports a join once MaxEntrants accounts have joined.
ErrTournamentFull = errors.New("selfhost: tournament full")
// ErrAttemptsExceeded reports a submission once the account has used MaxAttempts submissions in the round.
ErrAttemptsExceeded = errors.New("selfhost: tournament attempts exceeded")
)타입
type AdminState struct {
// Version is the schema version; it must be AdminStateVersion.
Version int `yaml:"version"`
// Hidden are the hidden accounts, at most one per board and account.
Hidden []Hidden `yaml:"hidden,omitempty"`
// Resets are the manual resets, at most one per board and time.
Resets []BoardReset `yaml:"resets,omitempty"`
}AdminState is what operators changed on the boards beside their scores: the hidden accounts and the manual resets. A Store keeps it; FileStore writes it as _admin.yaml in its directory, a name no board directory can take because board names begin with a letter or digit:
version: 1
hidden:
- board: weekly-sprint
account: acct-9
until: 2026-12-07T00:00:00Z
reason: under review
by: op:ada
at: 2026-11-30T10:00:00Z
resets:
- board: weekly-sprint
at: 2026-11-25T10:00:00Z
Unknown fields, duplicate keys and trailing documents are refused. Marshal writes times in UTC, the hidden accounts sorted by board and account and the resets by board and time, so a file in that form reads back and writes again byte for byte.
func ParseAdminState(data []byte) (AdminState, error)ParseAdminState decodes and validates an operator state file. Errors name the line and field.
func (s AdminState) Marshal() ([]byte, error)Marshal validates s and encodes it as deterministic 2-space YAML: times in UTC, hidden accounts sorted by board and account, resets by board and time.
func (s AdminState) Validate() errorValidate checks the version, that every board name and account ID is valid, that reasons fit MaxHideReason, that times are set (a reset's in whole seconds), and that no board and account, or board and reset time, appears twice.
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"`
// Operator controls how submissions update an account. Empty means best; set, increment and decrement require validation: signed.
Operator Operator `yaml:"operator,omitempty"`
// MetadataMaxBytes limits the JSON metadata stored with each entry, from 0 to MaxMetadataBytes. Zero uses MaxMetadataBytes.
MetadataMaxBytes int `yaml:"metadataMaxBytes,omitempty"`
// 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 BoardReset struct {
// Board is the board's name.
Board string `yaml:"board"`
// At is when the new period began, in whole seconds.
At time.Time `yaml:"at"`
}BoardReset is an operator's reset of a daily, weekly or monthly board: the period in force at At ended there and a new one began, running to the end of the period the board's reset would have ended anyway.
type Config struct {
// Version is the schema version; it must be ConfigVersion.
Version int `yaml:"version"`
// Audience is the token audience Handler accepts, which the account service must list in its audiences; empty means DefaultAudience. It must differ from the audience of the key set, which names the game's servers, and must not be "accounts", the account service's own audience.
Audience string `yaml:"audience,omitempty"`
// 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 []authtoken.PublicKey `yaml:"serverKeys,omitempty"`
// AllowedOrigins lists the web origins ("https://play.example.com") whose pages may call the service from a browser. The handler answers their CORS preflight requests; other origins get no CORS headers, so browsers refuse their requests. Native clients send no origin and need no entry.
AllowedOrigins []string `yaml:"allowedOrigins,omitempty"`
// Metrics, when set, is the TCP address the service's daemon (leaderboardd serve) serves GET /healthz, /readyz and /metrics on, such as 127.0.0.1:9101, on a listener of its own apart from the one players reach. The endpoints have no authentication, so keep a non-loopback address such as :9101 on a private network the public proxy does not forward to; the daemon logs a warning for one. Empty serves none of them. Service ignores it: a program that builds its own server mounts a servicehealth.Health itself.
Metrics string `yaml:"metrics,omitempty"`
// Admin, when set, gives the daemon an admin listener of its own for operators (package admin); without it the daemon serves no admin route.
Admin *admin.Config `yaml:"admin,omitempty"`
}Config is the leaderboard service's settings, kept in a YAML file:
version: 1
audience: leaderboard
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=
allowedOrigins:
- https://play.example.com
metrics: 127.0.0.1:9103
An optional admin: block (admin.Config) at the end gives the daemon an admin listener for operators.
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, omitting allowedOrigins when empty and metrics when unset, 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) TokenAudience() stringTokenAudience is the token audience Handler accepts: Audience, or DefaultAudience when it is empty.
func (c Config) Validate() errorValidate checks that c is a complete version 1 configuration.
type Deleted struct {
// Entries are the account's entries removed from the periods the service serves, latest period first.
Entries []Record
// Hidden is the hiding of the account an all-periods delete removed with its entries; nil when the account was not hidden on the board or the delete named one period.
Hidden *Hidden
}Deleted is what DeleteAccount removed, for the operator's audit record.
func (d Deleted) Periods() []stringPeriods returns the IDs of the periods d.Entries were removed from, latest first.
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
Subscore int64
Metadata json.RawMessage
// 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; DeleteAccount rewrites a period's file without the account's lines. 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. The hidden accounts and manual resets are in <dir>/_admin.yaml (AdminState), rewritten whole on every change. A rewrite goes through a temporary file and a rename. 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) DeleteAccount(ctx context.Context, board, period, account string) errorDeleteAccount rewrites the board's period file, or every period file of the board when period is empty, without the account's lines, through a temporary file and a rename; a file left with no lines is deleted.
func (f *FileStore) DeleteHidden(ctx context.Context, board, account string) errorDeleteHidden removes the hiding of the account on the board from _admin.yaml.
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) LoadAdmin(ctx context.Context) (AdminState, error)LoadAdmin reads _admin.yaml in the store's directory; a store without one has no hidden accounts or manual resets.
func (f *FileStore) Save(ctx context.Context, rec Record) errorSave appends rec to its period's file.
func (f *FileStore) SaveHidden(ctx context.Context, h Hidden) errorSaveHidden writes h to _admin.yaml, replacing an earlier hiding of the same board and account.
func (f *FileStore) SaveReset(ctx context.Context, r BoardReset) errorSaveReset adds a manual reset to _admin.yaml.
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 Hidden struct {
// Board is the board's name.
Board string `yaml:"board"`
// Account is the hidden account's ID.
Account string `yaml:"account"`
// Until is when the hiding ends; zero hides the account until an operator unhides it.
Until time.Time `yaml:"until,omitempty"`
// Reason is the operator's note, up to MaxHideReason bytes; it is never shown to players.
Reason string `yaml:"reason,omitempty"`
// By is the operator who hid the account, as an audit record names it ("op:ada").
By string `yaml:"by,omitempty"`
// At is when the account was hidden.
At time.Time `yaml:"at"`
}Hidden is an operator's hiding of an account on a board. While it is in force, the board's pages leave the account out for everyone but the account itself, which still sees its own entry and rank.
func (h Hidden) Active(now time.Time) boolActive reports whether h hides its account at now.
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 (m *MemoryStore) DeleteAccount(ctx context.Context, board, period, account string) errorDeleteAccount removes the account's records from a board's period, or from all of the board's periods when period is empty.
func (m *MemoryStore) DeleteHidden(ctx context.Context, board, account string) errorDeleteHidden removes the hiding of the account on the board.
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) LoadAdmin(ctx context.Context) (AdminState, error)LoadAdmin returns the hidden accounts and manual resets kept.
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.
func (m *MemoryStore) SaveHidden(ctx context.Context, h Hidden) errorSaveHidden keeps h, replacing an earlier hiding of the same board and account.
func (m *MemoryStore) SaveReset(ctx context.Context, r BoardReset) errorSaveReset keeps a manual reset.
type Operator stringOperator controls how a submission changes the account's score.
const (
// OperatorBest keeps the better score and is the default.
OperatorBest Operator = "best"
// OperatorSet replaces the account's score with the submitted score.
OperatorSet Operator = "set"
// OperatorIncrement adds the submitted score to the account's score.
OperatorIncrement Operator = "increment"
// OperatorDecrement subtracts the submitted score from the account's score.
OperatorDecrement Operator = "decrement"
)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. Build it for Config.TokenAudience with authtoken.NewVerifierFor: New refuses a verifier for any other audience, such as the game servers' one authtoken.NewVerifier gives.
Tokens *authtoken.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 authtoken.ParsePrivateKey from the PEM file leaderboardd genkey writes.
func (s *ProofSigner) PublicKey() authtoken.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
Subscore int64
Metadata json.RawMessage
// 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"
// Monthly starts over on the first day of each UTC calendar month.
Monthly Reset = "monthly"
)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 ResetResult struct {
// Current is the board's new current period.
Current Period
// Previous is the period the reset ended, now the board's previous one; zero on an all-time board, which keeps no earlier period.
Previous Period
// Removed is how many entries the reset removed: every entry of an all-time board, or those of the periods a resetting board stopped keeping.
Removed int
}ResetResult is what ResetBoard did.
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) AdminRoutes() []admin.RouteAdminRoutes returns the leaderboard's operator routes, for the admin listener of package admin (admin.ListenOptions.Routes, or Server.Handle). Each needs one permission, and the admin server writes an audit record of every call that changes something, naming "board:<board>/<account>" or "board:<board>" as its subject:
GET /admin/v1/leaderboard/boards (leaderboard.read) -> {"boards": [{"name", "reset", "current", "previous", "hidden"}]}
GET /admin/v1/leaderboard/boards/{board}/entries?period=&account=&offset=&limit= (leaderboard.read) -> page, every entry with "hidden"
DELETE /admin/v1/leaderboard/boards/{board}/entries/{account}?period= (leaderboard.delete) -> {"board", "account", "periods"}
GET /admin/v1/leaderboard/boards/{board}/hidden (leaderboard.read) -> {"hidden": [hidden]}
POST /admin/v1/leaderboard/boards/{board}/hide {"account", "until", "reason"} (leaderboard.hide) -> hidden
POST /admin/v1/leaderboard/boards/{board}/unhide {"account"} (leaderboard.hide) -> 204
POST /admin/v1/leaderboard/boards/{board}/reset (leaderboard.reset) -> {"board", "current", "previous"}
A board's current and previous periods carry the number of entries they hold, and "hidden" counts the accounts hidden on it. The entries route ranks every entry, hidden or not, and with account returns that account's entry alone. DELETE needs period: "current", "previous", a kept period's ID, or "all" to erase the account from the board (DeleteAccount), which also removes its hiding and succeeds when no entry was ranked; its audit record lists the removed entries, and a reset's counts them. until is an RFC 3339 time in the future, or absent to hide until unhidden. Errors are {"error": code}: bad_request and invalid_account 400, unknown_board, unknown_period, not_ranked and not_hidden 404, reset_too_soon 409 (also when the clock stepped back behind the last reset), request_too_large 413, unavailable 503, internal 500. The routes are listed in openapi.yaml beside the player routes.
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, as the account sees the board: without the other accounts operators hid, and with its own entry even when it is hidden. 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) DeleteAccount(ctx context.Context, board, period, account string) (Deleted, error)DeleteAccount removes the account's entry from a period of the board, or from every period when period is AllPeriods, and returns what it removed. The period is named as the queries name it ("current", "previous" or a kept period's ID). The ranks below the entry close up at once. AllPeriods erases the account from the board: the store also forgets the account in periods the service does not serve, such as those of a board whose reset changed, and the account's hiding on the board, with its reason and operator, is removed too; it succeeds even when the account had no entry the service serves. With one period, it returns ErrNotRanked when the account has no entry there.
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, as any player sees it: an account operators hid is left out. 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) FriendsAs(ctx context.Context, viewer, board, period string, accounts []string) (Page, error)FriendsAs is Friends as the account viewer sees the board: a hidden viewer still finds its own entry.
func (s *Service) Handler() http.HandlerHandler serves the service over HTTP. Every request except GET /v1/openapi.yaml carries "Authorization: Bearer <token>" with a token from the account service for Config.TokenAudience, which a device gets with the account service's refresh, verified offline with Options.Tokens; its subject is the account the request is for. A token for any other audience, such as the one a player sends a game server, is invalid_token. Requests and responses are JSON; every response carries Cache-Control: no-store. The machine-readable OpenAPI 3.1 description lives in openapi.yaml and is served at GET /v1/openapi.yaml.
GET /v1/openapi.yaml -> the OpenAPI 3.1 description (unauthenticated)
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
Pages leave out the accounts operators hid (Service.Hide), except the token's own account, which still sees its entry; the ranks below a hidden account close up.
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.
Browsers may call the handler from Config.AllowedOrigins: it answers their CORS preflight requests and allows Authorization and Content-Type.
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) HiddenAccounts(ctx context.Context, board string) ([]Hidden, error)HiddenAccounts returns the accounts hidden on the board now, sorted by account.
func (s *Service) Hide(ctx context.Context, h Hidden) (Hidden, error)Hide hides h.Account on h.Board from every other player's pages until h.Until (zero for until Unhide), replacing an earlier hiding of the account there. The account need not have an entry yet. h.Reason and h.By are kept for operators; At is set to the present. Pages show the change at once. It returns ErrInvalidHide when Until is not in the future or Reason is too long or holds a control character.
func (s *Service) Rank(ctx context.Context, board, period, account string) (Entry, error)Rank returns the account's entry in a period as the account sees it (Around), or ErrNotRanked when it has none.
func (s *Service) ResetBoard(ctx context.Context, board string) (ResetResult, error)ResetBoard starts the board over now, as its own reset would. A daily, weekly or monthly board ends its current period at the present second and begins one with ID the UTC time in the form 20060102T150405Z, running to the end of the period it cut short; the period it ended becomes the previous one, and the board keeps as many earlier periods as its keep setting says, dropping the rest. The reset is kept in the store, so it survives a restart. An all-time board keeps no earlier period, so its reset removes every entry. It returns ErrResetTooSoon when the current period or the board's last manual reset began less than a second ago, or is later than the present because the clock stepped back.
func (s *Service) Submit(ctx context.Context, sub Submission) (Result, error)Submit records a score in the board's current period, applying the board's operator. On a best board the score replaces the account's entry only when it is better, or equal with a higher subscore; otherwise the entry stays as it was and Improved is false. On a set, increment or decrement board the submission always replaces the entry with the operator's result.
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, as any player sees them: without the accounts operators hid (Hide), whose places the entries below them close up. 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.
func (s *Service) TopAs(ctx context.Context, viewer, board, period string, offset, limit int) (Page, error)TopAs is Top as the account viewer sees it: a hidden viewer still sees its own entry, at the rank it holds among the accounts not hidden.
func (s *Service) Unhide(ctx context.Context, board, account string) errorUnhide ends the hiding of the account on the board, so every player sees its entry again. It returns ErrNotHidden when the account is not hidden there.
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
// DeleteAccount removes the account's record from a board's period, or from every period of the board the store holds when period is empty. Removing a record that is not there is not an error.
DeleteAccount(ctx context.Context, board, period, account string) error
// LoadAdmin returns what operators changed on the boards: the hidden accounts and the manual resets. A store that has none returns an AdminState with only its Version set.
LoadAdmin(ctx context.Context) (AdminState, error)
// SaveHidden keeps h, replacing an earlier hiding of the same board and account.
SaveHidden(ctx context.Context, h Hidden) error
// DeleteHidden removes the hiding of the account on the board; removing one that is not there is not an error.
DeleteHidden(ctx context.Context, board, account string) error
// SaveReset keeps a manual reset of a board.
SaveReset(ctx context.Context, r BoardReset) 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
// Subscore breaks ties between equal scores, with higher values ranked first.
Subscore int64
// Metadata is a JSON object stored with the resulting entry.
Metadata json.RawMessage
// 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 Tournament struct {
OnRoundEnd func(TournamentRound, []Entry)
// contains filtered or unexported fields
}Tournament runs a TournamentConfig's rounds in memory, keeping each account's best score and attempt count per round. OnRoundEnd, when set, receives each round's ranked entries once, in round order, when EndRound settles it; it runs without the tournament's lock held, so it may call the tournament. It is safe for concurrent use.
func NewTournament(cfg TournamentConfig) *TournamentNewTournament returns a tournament for cfg with no entrants.
func (t *Tournament) Config() TournamentConfigConfig returns the tournament's configuration.
func (t *Tournament) EndRound(now time.Time)EndRound settles, once each and in order, every round that has ended by now, and passes each one's entries, ranked by score from highest with ties by account, to OnRoundEnd. A round no account submitted to is settled with no entries.
func (t *Tournament) Entrants() intEntrants returns how many accounts have joined.
func (t *Tournament) Join(account string, now time.Time) errorJoin enters account in the tournament; joining again does nothing. It returns ErrTournamentClosed when no round is open at now and ErrTournamentFull when MaxEntrants accounts have joined.
func (t *Tournament) Round(now time.Time) (TournamentRound, bool)Round returns the round open at now, and false before the tournament opens or once it has closed.
func (t *Tournament) Submit(account string, score int64, now time.Time) errorSubmit records score for account at now, keeping the account's best. It returns ErrTournamentClosed when no round is open or the account has not joined a tournament that requires it, and ErrAttemptsExceeded once the account has used MaxAttempts submissions.
type TournamentConfig struct {
Name, Category string
Start, End time.Time
Duration time.Duration
MaxEntrants, MaxAttempts int
JoinRequired bool
}TournamentConfig declares a tournament: its name and category, the time it opens and closes (a zero End never closes), the length of a round (zero for one round over the whole tournament), the most entrants and score attempts per account in each round (zero for no limit), and whether an account must Join before it submits.
type TournamentRound struct {
Number int
Start, End time.Time
}TournamentRound is one round of a tournament: its number from 1 and the times it starts and ends. The last round ends at the tournament's End even when that cuts it short; a round of a tournament with no End and no Duration has a zero End and never ends.
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.