Справочник API собран из Go doc-комментариев в исходном коде и написан на английском языке.
package cloudsave
import "github.com/nsgo-dev/game/pkg/online/cloudsave"Обзор
Package cloudsave is experimental: its API and documented formats may change in a minor release. See the API stability policy. is a self-hostable cloud save service: per-account save slots over HTTPS, kept in versions so that concurrent writes from two devices are refused rather than silently overwritten, slots over a size limit are rejected, and the last few versions of each slot can be listed and restored.
Accounts
The service does not keep accounts. Each request carries a bearer token from the account service (package accounts), which the service verifies offline with an authtoken.Verifier for its own audience (Config.TokenAudience, built with authtoken.NewVerifierFor), so a token a player sent a game server is refused; the token's subject is the account ID its slots are filed under. A player signed in to the same account on the web and on a phone reads and writes the same slots.
Versions and conflicts
Every write or delete adds a version to the slot, numbered from 1, and the service keeps the newest Config.KeepVersions of them; a delete is a version that marks the slot deleted, so a deleted slot can still be restored. A write may name the payload it expects to replace by its hash ("If-Match") or require that the slot does not exist ("If-None-Match: *"); when the slot holds anything else the write fails with ErrChanged (HTTP 412) and changes nothing. liveops.CloudClient makes every write of a liveops.CloudSyncer conditional this way, so a write that loses a race surfaces as a conflict the syncer's policy resolves.
Limits
A payload over Config.MaxSlotBytes is refused with ErrSlotTooLarge (HTTP 413) and a new slot beyond Config.MaxSlots live slots with ErrTooManySlots (HTTP 409). A deleted slot does not count toward MaxSlots; beyond MaxSlots deleted slots per account, the oldest are purged with their history.
Storage
The service keeps its records in a Store: NewMemoryStore for tests and prototypes, or the SQL store of package sqlstore, opened on SQLite by package sqlitestore or on Postgres by package pgstore. Package storetest checks any Store against the contract.
Configuration
Config is a versioned YAML file (ParseConfig, Config.Marshal); Service.Handler serves the service over HTTP, and command cloudsaved runs it as a standalone server.
Указатель
- Константы
- Переменные
- func Hash(data []byte) string
- func ValidateSlot(slot string) error
- type Config
- type Match
- type MemoryStore
- func NewMemoryStore() *MemoryStore
- func (m *MemoryStore) Append(_ context.Context, account, slot string, w Write) (Version, error)
- func (m *MemoryStore) Head(_ context.Context, account, slot string) (Version, error)
- func (m *MemoryStore) Purge(_ context.Context, account, slot string) (Purged, error)
- func (m *MemoryStore) PurgeAccount(_ context.Context, account string) (Purged, error)
- func (m *MemoryStore) Slots(_ context.Context, account string) ([]Version, error)
- func (m *MemoryStore) Stats(context.Context) (Stats, error)
- func (m *MemoryStore) Version(_ context.Context, account, slot string, number int64) (Version, error)
- func (m *MemoryStore) Versions(_ context.Context, account, slot string) ([]Version, error)
- type Options
- type Purged
- type Service
- func New(cfg Config, opts Options) (*Service, error)
- func (s *Service) AdminRoutes() []admin.Route
- func (s *Service) Config() Config
- func (s *Service) Delete(ctx context.Context, account, slot string, m Match) error
- func (s *Service) Handler() http.Handler
- func (s *Service) List(ctx context.Context, account string) ([]Version, error)
- func (s *Service) Load(ctx context.Context, account, slot string) (Version, error)
- func (s *Service) Purge(ctx context.Context, account, slot string) error
- func (s *Service) PurgeAccount(ctx context.Context, account string) (Purged, error)
- func (s *Service) Restore(ctx context.Context, account, slot string, number int64, m Match) (Version, error)
- func (s *Service) Save(ctx context.Context, account, slot string, data []byte, m Match) (Version, error)
- func (s *Service) Stats(ctx context.Context) (Stats, error)
- func (s *Service) Version(ctx context.Context, account, slot string, number int64) (Version, error)
- func (s *Service) Versions(ctx context.Context, account, slot string) ([]Version, error)
- type Stats
- type Store
- type Version
- type Write
Константы
const (
// PermRead lets an operator list an account's slots and their versions and read the store's statistics, without the payloads.
PermRead = "cloudsave.read"
// PermReadPayload lets an operator download a version's payload. It is separate from PermRead, and "*.read" does not grant it, because a save may hold personal data.
PermReadPayload = "cloudsave.read.payload"
// PermRestore lets an operator restore a kept version of a slot.
PermRestore = "cloudsave.restore"
// PermPurge lets an operator purge a slot or every slot of an account for good.
PermPurge = "cloudsave.purge"
)Permissions of the operator routes AdminRoutes returns. The built-in admin roles grant them: viewer has PermRead, support also PermReadPayload and PermRestore, operator and owner all four.
const (
// MaxSlotBytesLimit is the largest Config.MaxSlotBytes: 64 MiB.
MaxSlotBytesLimit = 64 << 20
// MaxSlotsLimit is the largest Config.MaxSlots.
MaxSlotsLimit = 10000
// MaxKeepVersions is the largest Config.KeepVersions.
MaxKeepVersions = 100
)Bounds of the configuration's limits.
const (
// ActionPurgeAccount is the audit action of purging every slot of an account; the route requires PermPurge.
ActionPurgeAccount = "cloudsave.purge.account"
)Audit actions of the operator routes besides their permissions.
const ConfigVersion = 1ConfigVersion is the configuration file schema version this package reads and writes.
const DefaultAudience = "cloudsave"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 does not reach the player's saves.
const (
// HeaderVersion carries a slot version's number on GET responses.
HeaderVersion = "Save-Version"
)Headers of the HTTP protocol besides the standard ones.
const MaxAccountBytes = 256MaxAccountBytes is the longest account ID, in bytes, the service files slots under.
const MaxSlotNameBytes = 200MaxSlotNameBytes is the longest slot name, in bytes; it matches the limit of save.ValidateSlot.
Переменные
var (
// ErrNotFound reports a slot, or a version of one, that the account does not have. Service.Load returns it for a deleted slot too.
ErrNotFound = errors.New("cloudsave: not found")
// ErrChanged reports a conditional write or delete whose precondition no longer holds because the slot changed. Nothing was written.
ErrChanged = errors.New("cloudsave: slot changed")
// ErrSlotTooLarge reports a payload over Config.MaxSlotBytes. Nothing was written.
ErrSlotTooLarge = errors.New("cloudsave: slot too large")
// ErrTooManySlots reports a write that would give the account more than Config.MaxSlots live slots. Nothing was written.
ErrTooManySlots = errors.New("cloudsave: too many slots")
// ErrInvalidSlot reports a slot name ValidateSlot refuses.
ErrInvalidSlot = errors.New("cloudsave: invalid slot name")
// ErrInvalidAccount reports an empty account ID or one longer than MaxAccountBytes.
ErrInvalidAccount = errors.New("cloudsave: invalid account id")
)Функции
func Hash(data []byte) stringHash returns the hash a slot's payload is identified by in versions, ETags and If-Match preconditions: "sha256:" followed by the lowercase hex SHA-256 of data. It equals liveops.PayloadHash.
func ValidateSlot(slot string) errorValidateSlot checks that slot is a name the service stores: 1 to MaxSlotNameBytes bytes of UTF-8 with no control characters and no '/', other than "." and "..", which are not path segments a URL can carry. Every name save.ValidateSlot accepts passes.
Типы
type Config struct {
// Version is the schema version; it must be ConfigVersion.
Version int `yaml:"version"`
// Audience is the token audience the service 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"`
// MaxSlotBytes is the largest payload a slot may hold, in bytes, from 1 to MaxSlotBytesLimit. A liveops.CloudSyncer payload is the save inside a JSON envelope: about 250 bytes more, with the save's quotes and backslashes escaped, or base64, a third larger, for data that is not UTF-8.
MaxSlotBytes int `yaml:"maxSlotBytes"`
// MaxSlots is how many live slots an account may have, from 1 to MaxSlotsLimit.
MaxSlots int `yaml:"maxSlots"`
// KeepVersions is how many of each slot's newest versions are kept, the current one included, from 1 to MaxKeepVersions.
KeepVersions int `yaml:"keepVersions"`
// 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 (cloudsaved 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 cloud save service's settings, kept in a YAML file:
version: 1 audience: cloudsave maxSlotBytes: 1048576 maxSlots: 32 keepVersions: 5 allowedOrigins: - https://play.example.com metrics: 127.0.0.1:9102
An optional admin: block (admin.Config) at the end gives the daemon an admin listener for operators.
Unknown fields are refused. Marshal writes the canonical form: the fields in this order, audience and metrics only when set and allowedOrigins only when it has entries. A file in that form, such as one Marshal wrote, reads back and writes again unchanged.
func DefaultConfig() ConfigDefaultConfig returns a configuration for DefaultAudience with 1 MiB slots, 32 slots per account and 5 versions kept per slot, and no web origins.
func ParseConfig(data []byte) (Config, error)ParseConfig decodes and validates a YAML configuration. Unknown fields and trailing documents are refused.
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 the service accepts: Audience, or DefaultAudience when it is empty.
func (c Config) Validate() errorValidate checks that c is a complete version 1 configuration.
type Match struct {
// Any skips the check: the write applies whatever the slot holds.
Any bool
// Hash, when Any is false, is the hash of the payload the slot must hold; empty means the slot must not exist (never written, or deleted).
Hash string
}Match is the precondition of a conditional write or delete.
func MatchHash(hash string) MatchMatchHash is the precondition that the slot holds the payload with this hash, or, for "", that it does not exist.
func (m Match) Holds(head Version, exists bool) boolHolds reports whether m holds for a slot whose newest version is head; exists is false when the slot has no versions. A Store's Append decides its precondition with it.
type MemoryStore struct {
// contains filtered or unexported fields
}MemoryStore is a Store held in memory, for tests and single-process prototypes. Its records are lost when the process ends.
func NewMemoryStore() *MemoryStoreNewMemoryStore returns an empty MemoryStore.
func (m *MemoryStore) Append(_ context.Context, account, slot string, w Write) (Version, error)Append implements Store.
func (m *MemoryStore) Head(_ context.Context, account, slot string) (Version, error)Head implements Store.
func (m *MemoryStore) Purge(_ context.Context, account, slot string) (Purged, error)Purge implements Store.
func (m *MemoryStore) PurgeAccount(_ context.Context, account string) (Purged, error)PurgeAccount implements Store.
func (m *MemoryStore) Slots(_ context.Context, account string) ([]Version, error)Slots implements Store.
func (m *MemoryStore) Stats(context.Context) (Stats, error)Stats implements Store.
func (m *MemoryStore) Version(_ context.Context, account, slot string, number int64) (Version, error)Version implements Store.
func (m *MemoryStore) Versions(_ context.Context, account, slot string) ([]Version, error)Versions implements Store.
type Options struct {
// Store keeps the slots. Required.
Store Store
// Tokens verifies the bearer tokens of HTTP requests: an authtoken.Verifier built from the account service's key set for Config.TokenAudience (authtoken.NewVerifierFor). Required, and New refuses a verifier for any other audience, such as the game servers' one authtoken.NewVerifier gives. The Go methods take the account ID directly; Handler takes it from the token's subject.
Tokens *authtoken.Verifier
// Logger receives errors outside the service's contract, such as a failing database. Nil discards them.
Logger *slog.Logger
// Now returns the current time, used to stamp versions; time.Now when nil.
Now func() time.Time
// Stats counts what the store holds for Service.Stats and the operator statistics route; Store.Stats when nil. Set it to count through a database handle other than the store's, such as sqlstore.ReadStats on a sqlitestore.OpenReader handle, so the count does not hold the connection players' requests use.
Stats func(ctx context.Context) (Stats, error)
}Options are what a Service needs besides its Config.
type Purged struct {
// Slots is the number of slots removed, live or deleted.
Slots int
// Versions is the number of kept versions removed.
Versions int
// Head is the hash of the purged slot's newest version, empty when that version is a deletion. Only Purge sets it.
Head string
}Purged is what a purge removed. A store counts it in the same atomic step as the removal, so it names what went even when a player's write committed just before.
type Service struct {
// contains filtered or unexported fields
}Service is the cloud save service. It is safe for concurrent use.
func New(cfg Config, opts Options) (*Service, error)New returns a service with the configuration and options.
func (s *Service) AdminRoutes() []admin.RouteAdminRoutes returns the service's operator routes for the admin listener (admin.ListenOptions.Routes, or admin.Server.Handle), each behind one permission. The admin server authenticates the operator, checks the permission and writes the audit record of every request that changes something, and of every payload download; the subject of each record is "account:<id>". Slot names are path segments, escaped as url.PathEscape does.
GET /admin/v1/cloudsave/stats cloudsave.read -> {"accounts", "slots", "bytes"}
GET /admin/v1/cloudsave/accounts/{id}/slots cloudsave.read -> {"slots": [version]}, deleted slots included
GET /admin/v1/cloudsave/accounts/{id}/slots/{slot}/versions cloudsave.read -> {"versions": [version]}, newest first
GET /admin/v1/cloudsave/accounts/{id}/slots/{slot}/versions/{n} cloudsave.read.payload -> the payload of version n as an attachment, with ETag and Save-Version; audited
POST /admin/v1/cloudsave/accounts/{id}/slots/{slot}/restore cloudsave.restore {"version", "ifMatch"} -> the new version
DELETE /admin/v1/cloudsave/accounts/{id}/slots/{slot} cloudsave.purge -> 204, the slot and its history purged
DELETE /admin/v1/cloudsave/accounts/{id} cloudsave.purge -> 204, every slot of the account purged
A restore writes the kept version's bytes back unchanged as the slot's next version, as Service.Restore does, conditional on the slot still holding the payload with hash ifMatch, or when ifMatch is omitted the payload it held when the request was read; a slot that changed in between answers 412 changed. The player's next sync receives the restored payload under the usual conflict rules. Its audit record carries the version restored ("version"), the operator's ifMatch when given ("ifMatch"), and on success the slot's hash before ("before", empty for a deleted slot) and after ("after") and the version written ("written"). A purge records what the store removed, counted in the same transaction as the removal: a slot purge's record carries the slot's hash before ("before", empty for a deleted slot) and how many versions went ("versions"), an account purge's how many slots and versions went ("slots", "versions"). A purge of a slot or account that holds nothing answers 404. The statistics come from Service.Stats, one count per 15 s.
A payload download carries Content-Disposition: attachment and X-Content-Type-Options: nosniff, so a browser on the admin origin saves the player's bytes as a file and never renders them.
Errors are {"error": code} as in Handler, with bad_request 400 also for an invalid account ID or restore body; the admin server answers 401 unauthorized, 403 forbidden (with "permission") and 403 csrf itself.
func (s *Service) Config() ConfigConfig returns the service's configuration.
func (s *Service) Delete(ctx context.Context, account, slot string, m Match) errorDelete deletes the slot when m holds, adding a version that marks it deleted; its earlier versions stay listed and can be restored. Deleting a slot that does not exist succeeds when m allows it (MatchAny or MatchHash("")). It returns ErrChanged when m does not hold.
func (s *Service) Handler() http.HandlerHandler serves the service over HTTP. Every request except GET /v1/openapi.yaml needs "Authorization: Bearer <token>" with a token from the account service for Config.TokenAudience, which a device gets with the account service's refresh; a token for any other audience, such as the one a player sends a game server, is invalid_token. Slots are those of the token's subject. Slot names are path segments, escaped as url.PathEscape does. 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/saves -> {"slots": [version]}
GET /v1/saves/{slot} -> the payload, with ETag and Save-Version
PUT /v1/saves/{slot} payload -> version; If-Match: "<hash>" or If-None-Match: * make it conditional
DELETE /v1/saves/{slot} -> 204; If-Match: "<hash>" or If-None-Match: * make it conditional
GET /v1/saves/{slot}/versions -> {"versions": [version]}, newest first
GET /v1/saves/{slot}/versions/{n} -> the payload of version n, with ETag and Save-Version
DELETE /v1/saves/{slot}/versions -> 204, the slot and all its versions purged
A version is {"slot", "version", "deleted", "hash", "size", "created"}, created in RFC 3339 with milliseconds; deleted and hash appear only when set. An ETag is the payload's Hash in double quotes. Payloads are application/octet-stream.
Errors are {"error": code} with the status the code implies: bad_request 400 (an invalid slot name, version number or precondition header), invalid_token 401, not_found 404, too_many_slots 409, deleted 410 (a version that is a deletion has no payload), changed 412, slot_too_large 413 (with "limit", Config.MaxSlotBytes), unavailable 503 when the request was cancelled or timed out, and internal 500. Every response carries Cache-Control: no-store.
Browsers may call the handler from Config.AllowedOrigins: it answers their CORS preflight requests and exposes ETag and Save-Version to them.
The handler does not limit request rates; put it behind a rate limiter, and behind TLS.
func (s *Service) List(ctx context.Context, account string) ([]Version, error)List returns the current version of each of the account's live slots, sorted by name and without data.
func (s *Service) Load(ctx context.Context, account, slot string) (Version, error)Load returns the current version of the account's slot with its data, or ErrNotFound when the slot was never written or is deleted.
func (s *Service) Purge(ctx context.Context, account, slot string) errorPurge removes the slot and all its versions for good.
func (s *Service) PurgeAccount(ctx context.Context, account string) (Purged, error)PurgeAccount removes every slot of the account, deleted ones included, and all their versions for good, and returns what it removed. An account with no slots is not an error.
func (s *Service) Restore(ctx context.Context, account, slot string, number int64, m Match) (Version, error)Restore writes the data of kept version number as the slot's next version when m holds, so the slot holds that payload again, deleted or not. A version that is a deletion deletes the slot. The restored bytes are the old payload unchanged; liveops.CloudClient.Restore re-stamps a CloudSyncer payload instead, so devices see the restore as the newest copy.
func (s *Service) Save(ctx context.Context, account, slot string, data []byte, m Match) (Version, error)Save writes data as the slot's next version when m holds, returning the new version without data. It returns ErrSlotTooLarge for data over Config.MaxSlotBytes, ErrChanged when m does not hold and ErrTooManySlots for a new slot beyond Config.MaxSlots; then nothing is written.
func (s *Service) Stats(ctx context.Context) (Stats, error)Stats counts the accounts with a slot, the live slots and the bytes of every kept version, through Options.Stats or else the store's Stats. One count answers every call for 15 s, and concurrent calls share it, so callers that ask often cost one full read per 15 s; a count that has not finished in 5 s fails.
func (s *Service) Version(ctx context.Context, account, slot string, number int64) (Version, error)Version returns one kept version of the slot with its data, or ErrNotFound.
func (s *Service) Versions(ctx context.Context, account, slot string) ([]Version, error)Versions lists the kept versions of the slot, deletions included, newest first and without data. It returns ErrNotFound for a slot with none.
type Stats struct {
// Accounts is the number of accounts with at least one slot, live or deleted.
Accounts int64
// Slots is the number of slots whose newest version is a save, not a deletion.
Slots int64
// Bytes is the size of every payload the store keeps, of every slot's kept versions.
Bytes int64
}Stats is how much a Store holds.
type Store interface {
// Head returns the newest version of slot with its data, or ErrNotFound when the slot has none.
Head(ctx context.Context, account, slot string) (Version, error)
// Version returns version number of slot with its data, or ErrNotFound when it is not kept.
Version(ctx context.Context, account, slot string, number int64) (Version, error)
// Versions lists the kept versions of slot, newest first and without data, or returns ErrNotFound when the slot has none.
Versions(ctx context.Context, account, slot string) ([]Version, error)
// Slots lists the newest version of each of the account's slots, deleted ones included, sorted by slot name and without data.
Slots(ctx context.Context, account string) ([]Version, error)
// Append adds a version to slot when w.Match holds for its newest version, returning the new version without data. It returns ErrChanged when the precondition fails, ErrNotFound for a delete of a slot that does not exist (never written or already deleted), and ErrTooManySlots when the write would exceed w.MaxSlots live slots; in each case nothing is written. It drops all but the w.Keep newest versions of slot.
Append(ctx context.Context, account, slot string, w Write) (Version, error)
// Purge removes slot and every version of it, and returns what it removed, counted in the same atomic step as the removal; a slot with no versions is not an error and returns a zero Purged.
Purge(ctx context.Context, account, slot string) (Purged, error)
// PurgeAccount removes every slot of account and every version of them, deleted slots included, so nothing of the account remains, and returns what it removed, counted in the same atomic step as the removal; an account with no slots is not an error and returns a zero Purged.
PurgeAccount(ctx context.Context, account string) (Purged, error)
// Stats counts what the store holds. It may read every record, so call it at an operator's or a scrape's pace, not per request.
Stats(ctx context.Context) (Stats, error)
}Store keeps slot versions per account. Implementations must be safe for concurrent use, and Append must be atomic: of two concurrent appends whose preconditions name the same newest version, at most one succeeds.
type Version struct {
// Slot is the slot name.
Slot string
// Number counts the slot's versions from 1; each write or delete adds one.
Number int64
// Deleted marks a version that deleted the slot. It has no data and an empty hash.
Deleted bool
// Hash is Hash(Data).
Hash string
// Size is len(Data).
Size int64
// Created is when the version was written, to the millisecond.
Created time.Time
// Data is the payload. Listings (Store.Versions and Store.Slots) leave it nil.
Data []byte
}Version is one version of a slot.
type Write struct {
// Delete adds a version that deletes the slot; Data is then ignored.
Delete bool
// Data is the new payload.
Data []byte
// Match is the precondition on the slot's newest version.
Match Match
// Created is the version's time.
Created time.Time
// Keep is how many of the slot's newest versions to keep, at least 1.
Keep int
// MaxSlots is how many live slots the account may have; a write that makes a slot live beyond it fails with ErrTooManySlots. Deleted slots beyond MaxSlots are purged, oldest first, with their history.
MaxSlots int
}Write is a version Store.Append adds.