GitHubComeçar

A referência da API é gerada a partir dos comentários de documentação Go no código-fonte e está escrita em inglês.

package cloudsave

import "github.com/nsgo-dev/game/pkg/cloudsave"

Visão geral

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; 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.

Índice

Constantes

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 (
	// 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.

Variáveis

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.

Funções

func Hash(data []byte) string

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(slot string) error

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.

Tipos

type Config struct {
	// Version is the schema version; it must be ConfigVersion.
	Version int `yaml:"version"`
	// 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
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 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() Config

DefaultConfig returns a configuration 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) Validate() error

Validate 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) Match

MatchHash 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) bool

Holds 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() *MemoryStore

NewMemoryStore 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) error

Purge implements Store.

func (m *MemoryStore) Slots(_ context.Context, account string) ([]Version, error)

Slots 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: a token.Verifier built from the account service's key set (token.NewVerifier). Required. 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 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) Config() Config

Config returns the service's configuration.

func (s *Service) Delete(ctx context.Context, account, slot string, m Match) error

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 (s *Service) Handler() http.Handler

Handler serves the service over HTTP. Every request needs "Authorization: Bearer <token>" with a token from the account service; slots are those of the token's subject. Slot names are path segments, escaped as url.PathEscape does.

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) error

Purge removes the slot and all its versions for good.

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) 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 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 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.