Documentation
¶
Overview ¶
Package cloudsave 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 a token.Verifier for its own audience (Config.TokenAudience, built with token.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 on SQLite or Postgres. 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.
Index ¶
- Constants
- Variables
- func Hash(data []byte) string
- func ValidateSlot(slot string) error
- type Config
- type Match
- type 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) error
- func (m *MemoryStore) Slots(_ context.Context, account string) ([]Version, 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 Service
- 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) 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) Version(ctx context.Context, account, slot string, number int64) (Version, error)
- func (s *Service) Versions(ctx context.Context, account, slot string) ([]Version, error)
- type Store
- type Version
- type Write
Constants ¶
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 ConfigVersion = 1
ConfigVersion 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 = 256
MaxAccountBytes is the longest account ID, in bytes, the service files slots under.
const MaxSlotNameBytes = 200
MaxSlotNameBytes is the longest slot name, in bytes; it matches the limit of save.ValidateSlot.
Variables ¶
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") )
var MatchAny = Match{Any: true}
MatchAny is the precondition that always holds.
Functions ¶
func Hash ¶
Hash 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 ¶
ValidateSlot 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.
Types ¶
type Config ¶
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"`
}
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
Unknown fields are refused. Marshal writes the canonical form: the fields in this order, audience 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 ¶
func DefaultConfig() Config
DefaultConfig 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 ¶
ParseConfig decodes and validates a YAML configuration. Unknown fields and trailing documents are refused.
func (Config) TokenAudience ¶
TokenAudience is the token audience the service accepts: Audience, or DefaultAudience when it is empty.
type Match ¶
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.
type MemoryStore ¶
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 ¶
func NewMemoryStore() *MemoryStore
NewMemoryStore returns an empty MemoryStore.
func (*MemoryStore) Purge ¶
func (m *MemoryStore) Purge(_ context.Context, account, slot string) error
Purge implements Store.
type Options ¶
type Options struct {
// Store keeps the slots. Required.
Store Store
// Tokens verifies the bearer tokens of HTTP requests: a token.Verifier built from the account service's key set for Config.TokenAudience (token.NewVerifierFor). Required, and New refuses a verifier for any other audience, such as the game servers' one token.NewVerifier gives. The Go methods take the account ID directly; Handler takes it from the token's subject.
Tokens *token.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
}
Options are what a Service needs besides its Config.
type Service ¶
type Service struct {
// contains filtered or unexported fields
}
Service is the cloud save service. It is safe for concurrent use.
func (*Service) Delete ¶
Delete 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 (*Service) Handler ¶
Handler 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 (*Service) List ¶
List returns the current version of each of the account's live slots, sorted by name and without data.
func (*Service) Load ¶
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 (*Service) Restore ¶
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 (*Service) Save ¶
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.
type Store ¶
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; a slot with no versions is not an error.
Purge(ctx context.Context, account, slot string) 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 ¶
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 ¶
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.
Directories
¶
| Path | Synopsis |
|---|---|
|
Package sqlstore is a cloudsave.Store over database/sql, for SQLite (OpenSQLite, with the pure-Go modernc.org/sqlite driver) and Postgres (OpenPostgres, with github.com/jackc/pgx/v5).
|
Package sqlstore is a cloudsave.Store over database/sql, for SQLite (OpenSQLite, with the pure-Go modernc.org/sqlite driver) and Postgres (OpenPostgres, with github.com/jackc/pgx/v5). |
|
Package storetest checks a cloudsave.Store against the contract the service relies on.
|
Package storetest checks a cloudsave.Store against the contract the service relies on. |