Documentation
¶
Overview ¶
Package remote is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.
Package remote provides optional network-backed asset delivery for pkg/assets: loose content-hashed assets described by remote.yaml with a quota-bounded LRU cache, and downloadable content (DLC) ZIP packs with signed, rollback-protected catalogs, HTTP Range resume, and Ed25519 verification.
Games that load only bundled or local assets through pkg/assets do not import this package and therefore never link net/http or crypto/tls.
Index ¶
- Constants
- Variables
- func EncodeCatalog(c *Catalog) ([]byte, error)
- func EncodeManifest(m *Manifest) ([]byte, error)
- func HashedPath(relPath, sha256Hex string) string
- func SignCatalog(priv ed25519.PrivateKey, c *Catalog) (string, error)
- func SignPack(priv ed25519.PrivateKey, data []byte) (sha256Hex, signatureHex string)
- func SignPackDigest(priv ed25519.PrivateKey, sha256Hex string) (string, error)
- func URL(base, relPath string) (string, error)
- func VerifyCatalog(pub ed25519.PublicKey, c *Catalog) error
- func With(opts Options) assets.Option
- type Cache
- type CacheUsage
- type Catalog
- type CatalogStore
- type DLCManager
- func (d *DLCManager) Cache() PackCache
- func (d *DLCManager) CachedCatalog() (*Catalog, error)
- func (d *DLCManager) Fetch(ctx context.Context, spec PackSpec, onProgress func(downloaded, total int64)) (fsys fs.FS, err error)
- func (d *DLCManager) FetchCatalog(ctx context.Context, catalogURL string) (*Catalog, error)
- func (d *DLCManager) FetchGroup(ctx context.Context, loader *assets.Manager, spec PackSpec, ...) (*assets.Group, error)
- func (d *DLCManager) Prune(c *Catalog) ([]string, error)
- func (d *DLCManager) Remove(spec PackSpec) error
- func (d *DLCManager) Updates(c *Catalog) []PackUpdate
- type DLCOptions
- type DirCache
- func (c *DirCache) Clear() error
- func (c *DirCache) Close() error
- func (c *DirCache) Dir() string
- func (c *DirCache) Flush() error
- func (c *DirCache) Get(sha256Hex string) ([]byte, error)
- func (c *DirCache) Has(sha256Hex string) bool
- func (c *DirCache) Pin(sha256Hex string)
- func (c *DirCache) Put(sha256Hex string, data []byte) error
- func (c *DirCache) Remove(sha256Hex string) error
- func (c *DirCache) Unpin(sha256Hex string)
- func (c *DirCache) Usage() CacheUsage
- type DirPackCache
- func (c *DirPackCache) CommitPart(key string) error
- func (c *DirPackCache) Dir() string
- func (c *DirPackCache) Has(key string) bool
- func (c *DirPackCache) HasPart(key string) bool
- func (c *DirPackCache) Keys() ([]string, error)
- func (c *DirPackCache) Open(key string) (io.ReaderAt, int64, error)
- func (c *DirPackCache) OpenPartReader(key string) (io.ReaderAt, int64, error)
- func (c *DirPackCache) OpenPartWriter(key string, appendMode bool) (io.WriteCloser, error)
- func (c *DirPackCache) PartSize(key string) (int64, error)
- func (c *DirPackCache) Remove(key string) error
- func (c *DirPackCache) RemovePart(key string) error
- type Entry
- type FileCatalogStore
- type Manifest
- type MemoryCache
- func (c *MemoryCache) Clear()
- func (c *MemoryCache) Get(sha256Hex string) ([]byte, error)
- func (c *MemoryCache) Has(sha256Hex string) bool
- func (c *MemoryCache) Pin(sha256Hex string)
- func (c *MemoryCache) Put(sha256Hex string, data []byte) error
- func (c *MemoryCache) Remove(sha256Hex string) error
- func (c *MemoryCache) Unpin(sha256Hex string)
- func (c *MemoryCache) Usage() CacheUsage
- type MemoryCatalogStore
- type MemoryPackCache
- func (c *MemoryPackCache) CommitPart(key string) error
- func (c *MemoryPackCache) Has(key string) bool
- func (c *MemoryPackCache) HasPart(key string) bool
- func (c *MemoryPackCache) Keys() ([]string, error)
- func (c *MemoryPackCache) Open(key string) (io.ReaderAt, int64, error)
- func (c *MemoryPackCache) OpenPartReader(key string) (io.ReaderAt, int64, error)
- func (c *MemoryPackCache) OpenPartWriter(key string, appendMode bool) (io.WriteCloser, error)
- func (c *MemoryPackCache) PartSize(key string) (int64, error)
- func (c *MemoryPackCache) Remove(key string) error
- func (c *MemoryPackCache) RemovePart(key string) error
- type Options
- type PackCache
- type PackLimits
- type PackManifest
- type PackSpec
- type PackUpdate
Examples ¶
Constants ¶
const CatalogVersion = 1
CatalogVersion is the schema version of a signed DLC catalog document.
const DefaultCacheQuota int64 = 200 << 20
DefaultCacheQuota is the default byte budget (200 MiB) for DirCache and MemoryCache, matching the local file system cap of mini-game runtimes such as WeChat.
const DefaultCatalogStorageKey = "assets.dlc.catalog"
DefaultCatalogStorageKey is the core.Storage key used when DLCOptions.Storage is set and DLCOptions.CatalogKey is empty.
const DefaultDLCChunkSize = 32 * 1024
DefaultDLCChunkSize is the default streaming read buffer size (32 KiB) used by DLCManager when DLCOptions.ChunkSize is zero or negative.
const DefaultRetryBackoff = 100 * time.Millisecond
DefaultRetryBackoff is the initial wait before the first retry when Options.Retries > 0 and Options.RetryBackoff <= 0.
const ManifestFile = "remote.yaml"
ManifestFile is the canonical filename written beside content-hashed remote assets by `game assets`.
const ManifestVersion = 1
ManifestVersion is the schema version of remote.yaml.
Variables ¶
var ( // ErrIncompatibleBuild reports that a pack's MinBuild/MaxBuild range does // not include the running application's AppBuild. ErrIncompatibleBuild = errors.New("assets: pack incompatible with app build") // ErrHashMismatch reports that a pack's or remote file's SHA-256 digest // does not match the manifest or PackSpec.SHA256. ErrHashMismatch error = nonRetryableError("assets: pack sha256 mismatch") // ErrInvalidSignature reports that a pack's Ed25519 signature failed // verification against DLCOptions.PublicKey. ErrInvalidSignature = errors.New("assets: pack signature invalid") // ErrCorruptPack reports that a pack archive is unreadable or not a valid // ZIP archive. ErrCorruptPack = errors.New("assets: pack archive corrupt") // ErrSizeMismatch reports that a pack's or remote file's byte length does // not match the manifest or PackSpec.Size. ErrSizeMismatch error = nonRetryableError("assets: pack size mismatch") // ErrPackTooLarge reports that a pack archive, or a file read from a mounted pack, would exceed PackLimits: a download without a PackSpec.Size that grows past MaxPackBytes, or an entry that decompresses past MaxFileBytes. ErrPackTooLarge = errors.New("assets: pack exceeds its size limit") )
var ErrCatalogRollback = errors.New("assets: dlc catalog serial is lower than last accepted serial")
ErrCatalogRollback reports that a DLC catalog's Serial is lower than the highest Serial previously accepted by this manager or its CatalogStore.
Functions ¶
func EncodeCatalog ¶
EncodeCatalog encodes c as canonical 2-space indented JSON with Packs sorted by ID and a trailing newline, so a round trip through ParseCatalog and EncodeCatalog changes nothing.
func EncodeManifest ¶
EncodeManifest encodes m as canonical 2-space YAML with Files sorted by URI so a round trip through ParseManifest and EncodeManifest changes nothing.
func HashedPath ¶
HashedPath inserts the first 8 lowercase hex characters of sha256Hex before the extension of relPath, producing "<name>.<hash8>.<ext>" (or "<name>.<hash8>" when relPath has no extension).
func SignCatalog ¶
func SignCatalog(priv ed25519.PrivateKey, c *Catalog) (string, error)
SignCatalog signs c.CanonicalBytes() with priv, stores the lowercase hex Ed25519 signature in c.Signature, and returns it.
func SignPack ¶
func SignPack(priv ed25519.PrivateKey, data []byte) (sha256Hex, signatureHex string)
SignPack hashes data with SHA-256, signs the raw 32-byte digest with priv, and returns the hex-encoded SHA-256 digest and hex-encoded Ed25519 signature.
Example ¶
SignPack produces the digest and signature a PackSpec carries, so a DLCManager given the public key refuses a pack that was altered.
package main
import (
"crypto/ed25519"
"fmt"
"strings"
"github.com/nsgo-dev/game/pkg/assets/remote"
)
func main() {
pub, priv, _ := ed25519.GenerateKey(strings.NewReader(strings.Repeat("seed", 16)))
data := []byte("pack contents")
digest, sig := remote.SignPack(priv, data)
fmt.Println(digest)
again, err := remote.SignPackDigest(priv, digest)
fmt.Println(again == sig, err, len(pub))
}
Output: 61eb17abac363f8e0bc21b11c814d31e7fcda74f2f505770e5ce2de2b69f8ffc true <nil> 32
func SignPackDigest ¶
func SignPackDigest(priv ed25519.PrivateKey, sha256Hex string) (string, error)
SignPackDigest signs a hex-encoded SHA-256 digest with priv and returns the hex-encoded Ed25519 signature.
func URL ¶
URL joins an HTTP(S) base URL with a clean relative slash-separated asset path, escaping each path segment and refusing path traversal.
func VerifyCatalog ¶
VerifyCatalog validates c and verifies c.Signature over c.CanonicalBytes() using pub. Failures return an error wrapping ErrInvalidSignature when the key or signature is missing, malformed, or invalid.
func With ¶
With configures an assets.Manager to load any asset URI listed in opts.Manifest from a remote origin by its content-hashed URL, verifying exact size and SHA-256 and storing verified files in opts.Cache. URIs not present in opts.Manifest continue to load from the Manager's local source (WithReadAsset, WithFS, or packaged app resources).
Types ¶
type Cache ¶
type Cache interface {
// Get returns the cached bytes for sha256Hex and updates its last-access
// time, or returns fs.ErrNotExist if not cached.
Get(sha256Hex string) ([]byte, error)
// Put stores verified bytes for sha256Hex, updates its last-access time,
// and evicts least-recently-used unpinned entries to stay within Quota.
Put(sha256Hex string, data []byte) error
// Remove deletes the cached entry for sha256Hex, returning nil if absent.
Remove(sha256Hex string) error
// Pin marks sha256Hex as in use by a loaded or loading group so eviction
// spares it. Calls are reference-counted and paired with Unpin.
Pin(sha256Hex string)
// Unpin releases one Pin reference on sha256Hex.
Unpin(sha256Hex string)
// Usage returns the cache's current byte usage, quota, file count, and
// pinned byte count.
Usage() CacheUsage
}
Cache stores verified remote asset files keyed by their lowercase hex SHA-256 digest and enforces a byte quota with least-recently-used eviction. Implementations must be safe for concurrent use.
type CacheUsage ¶
type CacheUsage struct {
// Bytes is the total size in bytes of all cached files.
Bytes int64
// Quota is the configured maximum cache size in bytes.
Quota int64
// Files is the number of cached files.
Files int
// PinnedBytes is the total size in bytes of cached files currently pinned by loaded groups.
PinnedBytes int64
}
CacheUsage summarizes the footprint of a Cache, suitable for displaying in a game's settings or storage management screen.
type Catalog ¶
type Catalog struct {
// Version is the catalog schema version; must equal CatalogVersion (1).
Version int `json:"version"`
// Serial is a strictly positive, monotonically increasing revision number
// enforced against rollback.
Serial uint64 `json:"serial"`
// Packs lists the downloadable packs offered by this catalog.
Packs []PackSpec `json:"packs"`
// Signature is the Ed25519 signature over CanonicalBytes(), encoded as hex
// or base64. Required when DLCOptions.PublicKey is set or AllowUnsigned is
// false.
Signature string `json:"signature,omitempty"`
}
Catalog is a signed, monotonically versioned list of downloadable content packs.
Its Ed25519 Signature covers CanonicalBytes — Version, Serial, and every pack's ID, Group, URL, Version, MinBuild, MaxBuild, Size, and SHA256 — so an attacker serving the catalog cannot reassign a pack archive to another ID or group, alter build bounds, or roll back to an older catalog once a higher Serial has been accepted. PackSpec.Signature remains supported for packs distributed standalone outside a signed Catalog.
func ParseCatalog ¶
ParseCatalog decodes a strict, versioned JSON DLC catalog, refusing unknown fields, duplicate keys, trailing data, unsupported versions, a zero serial, duplicate pack IDs, invalid build ranges, negative sizes, and malformed SHA-256 digests or signatures.
Its errors are *loaderr.Error values that give the line, field, and fix.
func (*Catalog) CanonicalBytes ¶
CanonicalBytes returns the deterministic JSON bytes covered by Catalog.Signature: Version, Serial, and Packs sorted by ID with each pack's ID, Group, URL, Version, MinBuild, MaxBuild, Size, and lowercase SHA256 (excluding Signature).
type CatalogStore ¶
type CatalogStore interface {
// LoadCatalog returns the persisted catalog bytes, or (nil, fs.ErrNotExist)
// when no catalog has been saved yet.
LoadCatalog() ([]byte, error)
// SaveCatalog atomically persists catalog bytes.
SaveCatalog(data []byte) error
}
CatalogStore persists the last accepted signed DLC catalog across launches for rollback protection and offline starts. Implementations must be safe for concurrent use.
func CoreCatalogStore ¶
func CoreCatalogStore(store core.Storage, key string) CatalogStore
CoreCatalogStore adapts an NSGo core.Storage to CatalogStore under key (DefaultCatalogStorageKey when empty). It returns nil for a zero core.Storage.
type DLCManager ¶
type DLCManager struct {
// contains filtered or unexported fields
}
DLCManager downloads, resumes, verifies, caches, and mounts DLC pack ZIP archives as fs.FS instances and assets.Groups.
func NewDLCManager ¶
func NewDLCManager(opts DLCOptions) *DLCManager
NewDLCManager returns a DLCManager configured with opts.
func (*DLCManager) Cache ¶
func (d *DLCManager) Cache() PackCache
Cache returns the PackCache used by this DLCManager.
func (*DLCManager) CachedCatalog ¶
func (d *DLCManager) CachedCatalog() (*Catalog, error)
CachedCatalog returns the last accepted catalog from CatalogStore after re-verifying its signature against DLCOptions.PublicKey (unless AllowUnsigned is set) and checking rollback protection. It returns fs.ErrNotExist when no catalog has been cached yet.
func (*DLCManager) Fetch ¶
func (d *DLCManager) Fetch(ctx context.Context, spec PackSpec, onProgress func(downloaded, total int64)) (fsys fs.FS, err error)
Fetch ensures spec is compatible with AppBuild, checks and re-verifies any cached pack, downloads missing or resumed bytes via HTTP Range requests into a .part staging entry, strictly verifies size, SHA-256, Ed25519 signature, and ZIP structure, commits atomically to the cache, and returns the mounted ZIP archive as an fs.FS.
The returned fs.FS also implements io.Closer and fs.ReadFileFS. It reads through the one cache reader it was verified on, and each file as it decompresses, bounded by PackLimits. Close it when the pack is no longer used: that releases the cache entry for Remove; one that is never closed is released when it is garbage collected. FetchGroup closes the pack it mounts when the group is reset or mounted again.
On network or context interruption, the .part entry is preserved so a subsequent Fetch resumes via HTTP Range ("bytes=<offset>-"). A spec that could never verify (a missing ID, a negative Size, a malformed SHA256 or Signature) is refused before the cache is touched. A cached pack whose bytes do not match the spec's size or SHA-256, and a download that fails verification, are removed from the cache; a cached pack whose bytes match but whose signature or contents are refused is kept, because downloading it again would fetch the same bytes.
func (*DLCManager) FetchCatalog ¶
FetchCatalog downloads a signed DLC catalog from catalogURL, verifies its Ed25519 signature with DLCOptions.PublicKey (unless AllowUnsigned is set), refuses any catalog whose Serial is lower than the last accepted serial (ErrCatalogRollback), and persists the accepted catalog in CatalogStore for rollback protection and offline starts.
When the server is unreachable due to a network/transport error (and ctx has not been cancelled), FetchCatalog falls back to the cached catalog in CatalogStore after re-verifying its signature. Tampered catalogs, rollback responses, and HTTP error statuses never fall back to the cache.
func (*DLCManager) FetchGroup ¶
func (d *DLCManager) FetchGroup( ctx context.Context, loader *assets.Manager, spec PackSpec, registerFn func(g *assets.Group, packFS fs.FS) error, onProgress func(downloaded, total int64), ) (*assets.Group, error)
FetchGroup fetches and verifies spec, mounts the resulting ZIP fs.FS onto loader.Group(spec.Group) (or spec.ID when spec.Group is empty), invokes registerFn on the engine goroutine to register assets in the group, and loads the group to completion.
FetchGroup blocks until download and group loading finish or ctx (or loader's scope) is cancelled, so it should be called off the engine goroutine.
The group owns the mounted pack: Group.Reset, Group.SetFS, a later FetchGroup into the same group and disposing loader's scope release it, and with it the cache entry for Remove.
func (*DLCManager) Prune ¶
func (d *DLCManager) Prune(c *Catalog) ([]string, error)
Prune removes completed cached packs whose cache keys are no longer listed in c, returning the sorted keys removed immediately.
Any superseded pack that is currently mounted is skipped rather than deleted under its readers, and marked for deferred removal when its last mount is released — matching Remove. A nil catalog is refused so a caller error never wipes the cache.
func (*DLCManager) Remove ¶
func (d *DLCManager) Remove(spec PackSpec) error
Remove deletes both the cached pack and any partial download for spec.
A pack that Fetch or FetchGroup mounted and that is still in use is not pulled from under its readers: its partial download goes at once, and the cached pack when the last mount is released, by closing the fs.FS Fetch returned or by resetting or re-mounting the group FetchGroup loaded (#546). A Fetch of the same pack before then keeps it.
func (*DLCManager) Updates ¶
func (d *DLCManager) Updates(c *Catalog) []PackUpdate
Updates compares each pack in c that is compatible with DLCOptions.AppBuild against the local PackCache and reports whether it is already cached and how many bytes remain to download (subtracting resumable .part bytes).
Updates is read-only and never modifies the cache.
type DLCOptions ¶
type DLCOptions struct {
// AppBuild is the running application's build number, checked against each
// PackSpec's MinBuild and MaxBuild range.
AppBuild int
// PublicKey is the Ed25519 public key used to verify pack signatures over
// each pack's 32-byte SHA-256 digest. Without it every pack is refused with ErrInvalidSignature unless AllowUnsigned is set.
PublicKey ed25519.PublicKey
// AllowUnsigned accepts packs without a signature when PublicKey is empty, checking only their size and SHA-256 from the PackSpec. Whoever supplies the PackSpec then chooses what is mounted, so set it only for development or when the specs ship inside the app (#546).
AllowUnsigned bool
// Cache stores completed packs and resumable .part downloads. When nil, a
// new MemoryPackCache is used.
Cache PackCache
// HTTPClient performs pack downloads. When nil, http.DefaultClient is used.
HTTPClient *http.Client
// ChunkSize sets the buffer size for streaming reads and progress updates.
// When <= 0, DefaultDLCChunkSize (32 KiB) is used.
ChunkSize int
// Limits caps how large a pack may be and what it may contain; zero fields use DefaultPackLimits. A pack over any limit is refused before it is mounted, a download stops as soon as it would pass MaxPackBytes, and a mounted pack reads each file as it decompresses, failing with ErrPackTooLarge past MaxFileBytes, so the caps also bound what reading an asset can allocate.
Limits PackLimits
// CatalogStore persists the last accepted signed DLC catalog for rollback
// protection and offline starts. When nil and Storage is non-zero,
// CoreCatalogStore(Storage, CatalogKey) is used; when both are unset, an
// in-memory CatalogStore is used.
CatalogStore CatalogStore
// Storage is an optional NSGo core.Storage used to persist the last
// accepted DLC catalog when CatalogStore is nil.
Storage core.Storage
// CatalogKey is the core.Storage key used with Storage. When empty,
// DefaultCatalogStorageKey is used.
CatalogKey string
}
DLCOptions configures a DLCManager created by NewDLCManager.
type DirCache ¶
type DirCache struct {
// Quota is the maximum total size of cached files in bytes. When <= 0,
// DefaultCacheQuota (200 MiB) is used.
Quota int64
// FlushInterval controls how frequently Get access-time updates are written
// to index.yaml. Zero writes immediately on every access; Put and Remove
// always persist the index immediately.
FlushInterval time.Duration
// contains filtered or unexported fields
}
DirCache stores remote loose asset files on disk under a directory, held to Quota (DefaultCacheQuota, 200 MiB, when <= 0) via least-recently-used eviction that never removes a file pinned by a loaded group, with access times persisted in a small YAML index (index.yaml).
func NewDirCache ¶
NewDirCache returns a filesystem-backed Cache rooted at dir. If quota is given and positive, it sets Quota; otherwise DefaultCacheQuota (200 MiB) is used. Directories are created lazily on first write.
func (*DirCache) Clear ¶
Clear removes every unpinned file from the cache, sparing files currently pinned by loaded groups.
func (*DirCache) Put ¶
Put implements Cache using atomic temp-file writes and LRU eviction of unpinned entries to stay within Quota.
type DirPackCache ¶
type DirPackCache struct {
// contains filtered or unexported fields
}
DirPackCache stores DLC packs on the local filesystem using ".pack.part" staging files and atomic os.Rename commits into ".pack" files.
func NewDirPackCache ¶
func NewDirPackCache(dir string) *DirPackCache
NewDirPackCache returns a filesystem-backed PackCache rooted at dir. Directories are created lazily on first write.
func (*DirPackCache) CommitPart ¶
func (c *DirPackCache) CommitPart(key string) error
CommitPart implements PackCache via atomic os.Rename.
func (*DirPackCache) Dir ¶
func (c *DirPackCache) Dir() string
Dir returns the root directory of the cache.
func (*DirPackCache) Has ¶
func (c *DirPackCache) Has(key string) bool
Has reports whether a completed pack exists for key.
func (*DirPackCache) HasPart ¶
func (c *DirPackCache) HasPart(key string) bool
HasPart reports whether a partial ".part" file exists for key.
func (*DirPackCache) Keys ¶
func (c *DirPackCache) Keys() ([]string, error)
Keys implements PackCache.
func (*DirPackCache) OpenPartReader ¶
OpenPartReader implements PackCache.
func (*DirPackCache) OpenPartWriter ¶
func (c *DirPackCache) OpenPartWriter(key string, appendMode bool) (io.WriteCloser, error)
OpenPartWriter implements PackCache.
func (*DirPackCache) PartSize ¶
func (c *DirPackCache) PartSize(key string) (int64, error)
PartSize implements PackCache.
func (*DirPackCache) Remove ¶
func (c *DirPackCache) Remove(key string) error
Remove implements PackCache.
func (*DirPackCache) RemovePart ¶
func (c *DirPackCache) RemovePart(key string) error
RemovePart implements PackCache.
type Entry ¶
type Entry struct {
// URI is the logical asset URI (for example "asset:music/theme.m4a").
URI string `yaml:"uri"`
// Path is the content-hashed relative path under Base (for example "music/theme.9f86d081.m4a").
Path string `yaml:"path"`
// Size is the exact expected file size in bytes.
Size int64 `yaml:"size"`
// SHA256 is the lowercase 64-character hex-encoded SHA-256 digest of the file.
SHA256 string `yaml:"sha256"`
}
Entry describes one loose asset file served from a remote origin.
type FileCatalogStore ¶
type FileCatalogStore struct {
// contains filtered or unexported fields
}
FileCatalogStore persists the signed DLC catalog as a JSON file using atomic temp-file writes and os.Rename.
func NewFileCatalogStore ¶
func NewFileCatalogStore(path string) *FileCatalogStore
NewFileCatalogStore returns a filesystem-backed CatalogStore that reads and writes path. Parent directories are created lazily on first save.
func (*FileCatalogStore) LoadCatalog ¶
func (s *FileCatalogStore) LoadCatalog() ([]byte, error)
LoadCatalog implements CatalogStore.
func (*FileCatalogStore) SaveCatalog ¶
func (s *FileCatalogStore) SaveCatalog(data []byte) error
SaveCatalog implements CatalogStore.
type Manifest ¶
type Manifest struct {
// Version is the schema version; must equal ManifestVersion (1).
Version int `yaml:"version"`
// Base is the default origin URL prefix (for example "https://cdn.example.com/game/")
// joined with each entry's Path when Options.Base is empty.
Base string `yaml:"base,omitempty"`
// Files lists the remotely delivered assets, sorted by URI in canonical output.
Files []Entry `yaml:"files,omitempty"`
}
Manifest maps logical asset URIs (such as "asset:music/theme.m4a") to content-hashed paths on a remote origin, with each file's exact byte size and SHA-256 digest.
func ParseManifest ¶
ParseManifest decodes a remote.yaml manifest, refusing unknown fields, trailing YAML documents, unsupported versions, duplicate URIs, invalid paths, negative sizes, and malformed SHA-256 digests.
type MemoryCache ¶
type MemoryCache struct {
// Quota is the maximum total size of cached files in bytes. When <= 0,
// DefaultCacheQuota (200 MiB) is used.
Quota int64
// contains filtered or unexported fields
}
MemoryCache is an in-memory Cache enforcing Quota, LRU eviction, and loaded-group pinning on every target including Web/WASM and unit tests.
func NewMemoryCache ¶
func NewMemoryCache(quota ...int64) *MemoryCache
NewMemoryCache returns an empty in-memory Cache. If quota is given and positive, it sets Quota; otherwise DefaultCacheQuota is used.
func (*MemoryCache) Clear ¶
func (c *MemoryCache) Clear()
Clear removes all unpinned cached entries.
func (*MemoryCache) Get ¶
func (c *MemoryCache) Get(sha256Hex string) ([]byte, error)
Get implements Cache.
func (*MemoryCache) Has ¶
func (c *MemoryCache) Has(sha256Hex string) bool
Has reports whether sha256Hex is currently cached.
func (*MemoryCache) Put ¶
func (c *MemoryCache) Put(sha256Hex string, data []byte) error
Put implements Cache.
func (*MemoryCache) Remove ¶
func (c *MemoryCache) Remove(sha256Hex string) error
Remove implements Cache.
type MemoryCatalogStore ¶
type MemoryCatalogStore struct {
// contains filtered or unexported fields
}
MemoryCatalogStore is an in-memory CatalogStore safe for concurrent use.
func NewMemoryCatalogStore ¶
func NewMemoryCatalogStore() *MemoryCatalogStore
NewMemoryCatalogStore returns an empty in-memory CatalogStore.
func (*MemoryCatalogStore) LoadCatalog ¶
func (s *MemoryCatalogStore) LoadCatalog() ([]byte, error)
LoadCatalog implements CatalogStore.
func (*MemoryCatalogStore) SaveCatalog ¶
func (s *MemoryCatalogStore) SaveCatalog(data []byte) error
SaveCatalog implements CatalogStore.
type MemoryPackCache ¶
type MemoryPackCache struct {
// contains filtered or unexported fields
}
MemoryPackCache is an in-memory PackCache that works on every target including Web/WASM and unit tests.
A pack is held once: readers share the stored bytes, which are never written after they are stored, and CommitPart moves the partial download into place instead of copying it (#546).
Example ¶
A MemoryPackCache keeps downloaded packs in memory: a download goes to a part entry first and becomes the pack once committed.
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/assets/remote"
)
func main() {
c := remote.NewMemoryPackCache()
w, _ := c.OpenPartWriter("chapter-2@1.0.0", false)
fmt.Fprint(w, "zip bytes")
w.Close()
fmt.Println(c.HasPart("chapter-2@1.0.0"), c.Has("chapter-2@1.0.0"))
if err := c.CommitPart("chapter-2@1.0.0"); err != nil {
fmt.Println(err)
return
}
_, size, _ := c.Open("chapter-2@1.0.0")
fmt.Println(c.HasPart("chapter-2@1.0.0"), c.Has("chapter-2@1.0.0"), size)
}
Output: true false false true 9
func NewMemoryPackCache ¶
func NewMemoryPackCache() *MemoryPackCache
NewMemoryPackCache returns an empty in-memory PackCache.
func (*MemoryPackCache) CommitPart ¶
func (c *MemoryPackCache) CommitPart(key string) error
CommitPart implements PackCache.
func (*MemoryPackCache) Has ¶
func (c *MemoryPackCache) Has(key string) bool
Has reports whether a completed pack exists for key.
func (*MemoryPackCache) HasPart ¶
func (c *MemoryPackCache) HasPart(key string) bool
HasPart reports whether a partial download exists for key.
func (*MemoryPackCache) Keys ¶
func (c *MemoryPackCache) Keys() ([]string, error)
Keys implements PackCache.
func (*MemoryPackCache) OpenPartReader ¶
OpenPartReader implements PackCache.
func (*MemoryPackCache) OpenPartWriter ¶
func (c *MemoryPackCache) OpenPartWriter(key string, appendMode bool) (io.WriteCloser, error)
OpenPartWriter implements PackCache.
func (*MemoryPackCache) PartSize ¶
func (c *MemoryPackCache) PartSize(key string) (int64, error)
PartSize implements PackCache.
func (*MemoryPackCache) Remove ¶
func (c *MemoryPackCache) Remove(key string) error
Remove implements PackCache.
func (*MemoryPackCache) RemovePart ¶
func (c *MemoryPackCache) RemovePart(key string) error
RemovePart implements PackCache.
type Options ¶
type Options struct {
// Manifest maps logical asset URIs to content-hashed paths, exact byte
// sizes and SHA-256 digests. URIs not listed in Manifest fall through to
// the Manager's local reader.
Manifest *Manifest
// Base is the remote origin URL prefix (for example "https://cdn.example.com/game/").
// When empty, Manifest.Base is used.
Base string
// Fetch retrieves url and returns its response body and expected content
// length (-1 if unknown). The caller closes the returned io.ReadCloser.
// When nil, net/http with http.DefaultClient is used.
Fetch func(ctx context.Context, url string) (io.ReadCloser, int64, error)
// Cache stores verified remote files keyed by SHA-256 and enforces a byte
// quota with LRU eviction. When nil, a MemoryCache with DefaultCacheQuota
// is used.
Cache Cache
// Retries is the number of additional attempts after a transient fetch
// error (network failure, HTTP 429 or 5xx). Integrity mismatches and 4xx
// responses are never retried. Zero disables retries.
Retries int
// RetryBackoff is the initial delay before the first retry (doubled on
// each subsequent attempt). When <= 0, DefaultRetryBackoff is used.
RetryBackoff time.Duration
}
Options configures loading loose asset files from a remote origin by content-hashed URL, verified against size and SHA-256 and cached under a byte quota.
type PackCache ¶
type PackCache interface {
// Open returns a random-access reader and byte size for a completed pack,
// or fs.ErrNotExist if key is not cached. The returned io.ReaderAt must be
// safe for concurrent ReadAt calls and must not leak resources without a
// Close call.
Open(key string) (io.ReaderAt, int64, error)
// PartSize returns the byte size of an in-progress partial download for
// key, or (0, nil) if no partial download exists.
PartSize(key string) (int64, error)
// OpenPartWriter opens the partial download entry for key. When appendMode
// is true, writes append to existing partial bytes; when false, existing
// partial bytes are truncated.
OpenPartWriter(key string, appendMode bool) (io.WriteCloser, error)
// OpenPartReader returns a random-access reader and byte size for an
// in-progress partial download so it can be verified before CommitPart, or
// fs.ErrNotExist if no partial download exists.
OpenPartReader(key string) (io.ReaderAt, int64, error)
// CommitPart atomically promotes the partial download for key into the
// completed pack entry.
CommitPart(key string) error
// RemovePart deletes any partial download for key, returning nil if absent.
RemovePart(key string) error
// Remove deletes any completed pack for key, returning nil if absent.
Remove(key string) error
// Keys returns the cache keys of all completed packs currently stored in
// the cache, sorted lexicographically.
Keys() ([]string, error)
}
PackCache persists downloaded DLC packs and in-progress resumable partial downloads. Implementations must be safe for concurrent use.
type PackLimits ¶
type PackLimits struct {
// MaxEntries is the largest number of files a pack may hold.
MaxEntries int
// MaxFileBytes is the largest uncompressed size of one file, checked against the archive's headers before mounting and against the bytes themselves as a mounted pack reads them.
MaxFileBytes uint64
// MaxTotalBytes is the largest uncompressed size of all files together.
MaxTotalBytes uint64
// MaxPackBytes is the largest archive a DLCManager downloads or opens. It bounds the .part file of a PackSpec without a Size, which would otherwise grow as long as the server sends bytes, and a PackSpec whose Size is larger is refused before anything is downloaded.
MaxPackBytes int64
}
PackLimits bounds the size and structure of a DLC pack ZIP.
func DefaultPackLimits ¶
func DefaultPackLimits() PackLimits
DefaultPackLimits returns the limits a DLCManager uses for zero PackLimits fields: 32768 entries, 256 MiB per file, 1 GiB in total and a 1088 MiB (1 GiB + 64 MiB) archive.
type PackManifest ¶
type PackManifest struct {
// Packs lists the packs the catalog offers.
Packs []PackSpec `json:"packs"`
}
PackManifest is a JSON catalog of downloadable content packs.
type PackSpec ¶
type PackSpec struct {
// ID uniquely identifies the pack (for example "chapter-2").
ID string `json:"id"`
// Group names the assets.Group populated by FetchGroup. When empty, ID is
// used as the group name.
Group string `json:"group,omitempty"`
// URL is the HTTP(S) endpoint serving the pack ZIP archive.
URL string `json:"url"`
// Version identifies the pack revision (for example "1.0.0").
Version string `json:"version"`
// MinBuild is the minimum inclusive application build compatible with this
// pack. Zero means no lower bound.
MinBuild int `json:"min_build,omitempty"`
// MaxBuild is the maximum inclusive application build compatible with this
// pack. Zero means no upper bound.
MaxBuild int `json:"max_build,omitempty"`
// Size is the expected pack size in bytes. When positive, downloads and
// cached packs must match Size exactly.
Size int64 `json:"size,omitempty"`
// SHA256 is the expected hex-encoded SHA-256 digest of the pack archive.
SHA256 string `json:"sha256"`
// Signature is the Ed25519 signature over the raw 32-byte SHA-256 digest of
// the pack, encoded as hex or base64. Required when DLCOptions.PublicKey is
// set.
Signature string `json:"signature,omitempty"`
}
PackSpec describes a downloadable content (DLC) pack archive.
func ParsePackManifest ¶
ParsePackManifest decodes a JSON pack manifest containing either a PackManifest object ({"packs": [...]}) or a bare JSON array of PackSpec.
A field the manifest does not define, such as a misspelt "sha265", is refused rather than ignored, as are a key given twice in one object and bytes after the manifest, so a typo cannot silently drop a check and a reader cannot be shown one value while another is used (#546).
Its errors are *loaderr.Error values that give the line and field of the problem and how to fix it; a caller that read data from a file names it with loaderr.WithFile.
Example ¶
ParsePackManifest reads the list of downloadable packs, and Compatible checks each against the running build.
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/assets/remote"
)
func main() {
packs, err := remote.ParsePackManifest([]byte(`{"packs": [
{"id": "chapter-2", "url": "https://example.com/c2.zip", "version": "1.0.0", "min_build": 10, "sha256": "00"},
{"id": "chapter-3", "url": "https://example.com/c3.zip", "version": "1.0.0", "min_build": 20, "sha256": "00"}
]}`))
if err != nil {
fmt.Println(err)
return
}
for _, p := range packs {
fmt.Println(p.ID, p.Compatible(15))
}
}
Output: chapter-2 true chapter-3 false
func (PackSpec) CacheKey ¶
CacheKey returns the stable cache key for this pack based on its ID and Version.
func (PackSpec) Compatible ¶
Compatible reports whether appBuild falls within the pack's inclusive [MinBuild, MaxBuild] bounds. Zero bounds are treated as unbounded.
type PackUpdate ¶
type PackUpdate struct {
// Spec is the pack entry from the catalog.
Spec PackSpec
// Cached reports whether a pack matching Spec's cache key, size, and SHA-256
// is already committed in the cache.
Cached bool
// DownloadBytes is the number of bytes remaining to download for Spec.
// It is 0 when Cached is true or Spec.Size is 0; otherwise it is
// Spec.Size minus resumable PartialBytes (clamped at 0).
DownloadBytes int64
// PartialBytes is the number of resumable .part bytes currently cached for
// Spec (0 when Cached is true or no valid partial download exists).
PartialBytes int64
}
PackUpdate describes the local cache and download state of one compatible pack in a Catalog.