Blobs
The design of the storage module's blob store: files kept once by their SHA-256, never changed, linked into views, and removed only by a sweep that every owner of blobs takes part in.
Picture agni snapshotting a repo at a commit, then snapshotting the next commit a week later. Most files didn’t change, so most of the second snapshot is bytes the server already has. agni keeps each file once, named by the SHA-256 of its contents, and builds each snapshot’s folder out of hard links to those files. A sweep removes a file only once nothing points at it.
This page is the design for #154. The storage/blobs package holds the store interface, a folder store, and the manifest that lists a snapshot’s files, rendered at the bottom of the page. It starts from agni’s BlobDir (agni#1739). Mounts uses it for GitHub snapshots, and an app can use it for uploads, as agni does for designs.
Where blobs live ¶
Blobs get a package of their own, rather than sitting inside the GitHub driver, because the driver isn’t their only owner. agni’s uploaded designs are blobs in the same store, and one sweep has to see both.
A hash is sha256: and 64 lowercase hex digits, agni’s format. A malformed hash fails ParseHash, and nothing that fails it can name a file, so no hash reaches outside a store’s folder.
The interface ¶
Store has four methods:
Putstreams the contents in and returns their hash. Putting contents the store already holds writes nothing new. It does refresh the blob’s age, though. Without that, a sweep could remove an old blob in the moment after a client uploaded it again and before the client’s record named it. agni’sBlobDirhas that gap.Openreturns a reader that hashes as it goes. If the bytes no longer match, the last read returnsErrCorruptinstead ofio.EOF. Only a caller who reads to the end gets the check, which is the case for every copy and every hash.Hasreports whether a blob is there.Sweepremoves blobs. The next section covers it.
Linker adds Link, for a store on the server’s disk. It hard-links a blob into a folder, so a snapshot’s view takes no extra space, and copies when the filesystem refuses links. A linked file keeps its contents after the sweep removes the blob, because a hard link is a second name for the same file.
The sweep ¶
Several things own blobs in one store: an app’s designs, and the mounts registry’s snapshots. No one of them knows the whole set in use. So Sweep takes a Referrer from each owner, a function that calls keep for every hash the owner still names. The store keeps the union. It also keeps anything written within the grace period, which spares a blob a caller has put but not yet named.
If any referrer fails, Sweep removes nothing and returns the error. A referrer that couldn’t reach its own records doesn’t know what is in use, and treating that as “nothing” would delete live files.
The folder store’s sweep also removes temp files older than the grace period, which a crashed Put left behind.
Manifests ¶
A snapshot can have 100,000 files, and a mount record can’t hold a list that long in Datastore. So a snapshot’s file list is a blob too. Manifest lists each file’s path, hash and size. PutManifest sorts it by path before storing it, so the same files give the same hash in any order. It refuses paths that are absolute, unclean, climbing or duplicated.
A mount record keeps one hash, the manifest’s. ManifestRefs expands that hash into the manifest plus every file it lists. The mounts registry’s BlobRefs does that for every snapshot mount, and passes the hashes to Sweep.
The folder store ¶
blobs.Dir keeps a blob at <root>/sha256/ab/cdef.... That is agni’s layout, so agni can point NewDir at its existing uploads/blobs folder and keep every blob it has. Writes go through a temp file and a rename in the same folder, so a reader sees a whole blob or none, and several processes can share one Dir. Reads and removals go through os.Root, so a link planted in the folder can’t lead a sweep outside it.
Bucket stores ¶
Say agni runs on Kubernetes with no persistent volume. It keeps uploads in a bucket with s3blobs.New(ctx, "s3://acme-agni/uploads", creds) or gcsblobs.New(ctx, "gs://acme-agni/uploads", creds) (#205). The packages live in the S3 and GCS driver modules, storage/drivers/s3/s3blobs and storage/drivers/gcs/gcsblobs, so an app that uses a cloud for both mounts and blobs downloads its SDK once. The credentials come from an aws or gcp connection, through connections.Service.Credentials, as the mount drivers’ do.
- Each blob is the object
<prefix>/sha256/ab/cdef..., the same layoutDiruses on disk (blobs.Key). Soaws s3 sync uploads/blobs s3://acme-agni/uploadsmoves an existingDirinto a bucket. - A bucket needs the object’s name before the upload, and the name is the hash. So
Putfirst copies its input into a local temp file and hashes it (blobs.Spool), then uploads once.WithTempDirsets where, and it needs room for the largest blob. - The upload is conditional, with
If-None-Match: *on S3 andifGenerationMatch=0on GCS. Two servers putting the same bytes never overwrite each other. The loser finds the blob there, and moves its written time forward in the object’s metadata, so the sweep’s grace period starts again asPutpromises. On S3 that copies the object onto itself, since S3 can’t change metadata in place. Openchecks the bytes against the hash as it reads, throughblobs.Verify, asDirdoes.Sweeplists<prefix>/sha256/and ages each unreferenced blob by its written time, or by the object’s own time for a blob copied in some other way. On S3 it reads each unreferenced blob’s metadata with a HEAD, since a listing leaves metadata out. Objects under the prefix that aren’t named like blobs are left alone.- They implement
StorewithoutLinker, since a bucket can’t hard-link. On its own, a snapshot over them serves anfs.FSand has no host path. An app that needs files on disk putsblobs.Cachedin front (see below).
blobs/blobstest.RunStore checks any Store against this page’s contract: round trips, a missing or malformed hash, corruption, the refresh on a second Put, the sweep’s grace period and referrers, and concurrent Puts of the same bytes. Dir, s3blobs and gcsblobs all run it, the bucket stores against gofakes3 and fake-gcs-server. Live tests run with STORAGE_LIVE_S3=s3://<bucket>/<prefix> or STORAGE_LIVE_GCS=gs://<bucket>/<prefix>, using each cloud’s default credentials.
A local cache in front of a bucket ¶
Say agni keeps its blobs in S3, and its engine opens real files. A view needs blobs on the server’s disk, so it needs a Linker, and s3blobs isn’t one. blobs.NewCached(remote, localDir) wraps the bucket store with a local Dir, and the result is a Linker (#219).
Putwrites the local copy, then uploads that copy, and returns after both. A pod that dies afterPutloses nothing.OpenandLinkserve the local copy. On a miss they fetch the blob from the remote and keep it. The remote’s reader checks the hash, so a corrupt remote blob fails withErrCorruptand is never kept.Hasasks the local copy first, then the remote.Sweepcalls the referrers once. It sweeps the remote with what they named, then the localDirwith the same names and grace. A local copy can outlive its remote blob by one sweep, when it was fetched after the remote wrote it.WithMaxAge(d)also drops any local copy fetched or put more thandago, since the remote still holds it.- A pod that restarts with an empty disk refills the local folder on demand.
remote, _ := s3blobs.New(ctx, "s3://acme-agni/uploads", creds)
local, _ := blobs.NewDir("/var/cache/agni/blobs")
store := blobs.NewCached(remote, local, blobs.WithMaxAge(7*24*time.Hour))
blobstest.RunCached runs RunStore and RunLinker on a Cached over any remote, and then the checks above: a lost local folder, a corrupt remote blob, the sweep and the max age. A Dir, s3blobs and gcsblobs all run it as the remote. RunLinker checks Link alone, and Dir runs it too.
Blobs and wasmhost’s caches ¶
wasmhost’s Cache (MemCache, DirCache, the browser cache) looks similar, and the two are kept apart. A cache may lose an entry and rebuild it, but a blob store may not, since a record pointing at a missing blob has lost data. Their keys differ too: a cache key is any string the caller picks, and a blob’s name is computed from its contents. The two share no lower layer.
Aliases ¶
A source can have its own name for a file’s contents, such as a git blob id. Aliases is an optional interface on a store that remembers which blob such a name points at, in a namespace like git. The GitHub driver uses it so a second read of a repo downloads only files whose git blob id it hasn’t seen (#172). Dir keeps each alias as a file under <root>/aliases/<ns>/<id>, beside the blobs, so Sweep never walks them. An alias is a hint. Its blob can be swept, so a caller checks Has before trusting it.
The package ¶
blobs
import "github.com/panyam/goapplib/storage/blobs"
Package blobs keeps files by the SHA-256 of their contents. Each file is stored once, never changed, and removed only by a sweep that finds nothing pointing at it. A GitHub snapshot lands here, and so do an app's uploads.
A blob store differs from a cache such as wasmhost's: a cache may lose an entry and rebuild it, and a blob store may not. The design is at https://panyam.github.io/goapplib/reference/blobs/.
Constants and variables
var (
// ErrNotFound means the store holds no blob with that hash.
ErrNotFound = errors.New("blobs: not found")
// ErrInvalidHash means a hash isn't "sha256:" and 64 lowercase hex digits.
ErrInvalidHash = errors.New("blobs: invalid hash")
// ErrCorrupt means a blob's bytes no longer hash to its name, because something changed or
// truncated the stored file. Open's reader returns it at the end of the blob, in place of
// io.EOF.
ErrCorrupt = errors.New("blobs: contents don't match the hash")
// ErrInvalidManifest means a manifest has a path that is absolute, unclean or climbs out,
// a duplicate path, or a malformed hash.
ErrInvalidManifest = errors.New("blobs: invalid manifest")
)var ErrInvalidAlias = errors.New("blobs: invalid alias")ErrInvalidAlias means an alias's namespace or ID isn't letters, digits, '_', '.' and '-', or is "." or "..".
Key
func Key(h Hash) (string, error)Key returns where a store keeps h, relative to its root: "sha256/ab/cdef...", split after the first two hex digits. Dir uses this layout on disk, and a bucket store uses it under its prefix, so a tree of blobs copies between them unchanged. It returns ErrInvalidHash for a malformed h.
ManifestRefs
func ManifestRefs(ctx context.Context, s Store, h Hash, keep func(Hash)) errorManifestRefs calls keep for the manifest h and for every file it lists, which is what a Referrer for a snapshot needs to pass to Sweep.
Verify
func Verify(rc io.ReadCloser, h Hash) io.ReadCloserVerify wraps rc, the contents a store read for h, so that reading checks them against h. When the bytes don't match, the final Read returns ErrCorrupt in place of io.EOF, as Store.Open promises. A store outside this package returns it from Open.
Aliases
type Aliases interface {
Store
// Alias returns the hash id names in ns, and false when it names none.
Alias(ctx context.Context, ns, id string) (Hash, bool, error)
// SetAlias records that id in ns names h, replacing any earlier alias.
SetAlias(ctx context.Context, ns, id string, h Hash) error
}Aliases is a Store that also remembers which blob an outside ID names. Each ID lives in a namespace, such as "git" for git blob ids. A driver that lists a source's files with their own content IDs uses it to skip downloading a file the store already holds.
An alias is a hint. The blob it names can be swept, so a caller checks Has before trusting it.
Cached
type Cached struct {
// contains filtered or unexported fields
}Cached is a Linker that keeps a local Dir in front of a remote Store, such as a bucket store. An app whose blobs live in a bucket can then still build folder views, since views need blobs on this server's disk.
The remote holds every blob, and the local Dir holds copies. Put writes both before it returns, so a server that dies after Put loses nothing. Open and Link serve the local copy, and fetch it from the remote on a miss, so a local folder lost on restart refills on demand. Several servers may share one remote, each with its own Dir.
NewCached
func NewCached(remote Store, local *Dir, opts ...CachedOption) *CachedNewCached returns a Cached that keeps every blob in remote and copies in local.
Cached.Alias
func (c *Cached) Alias(ctx context.Context, ns, id string) (Hash, bool, error)Alias implements Aliases from the local Dir, so each server keeps its own aliases. A server whose folder was lost finds none, and its next fetch records them again. Callers check Has before using a hash, and Has asks the remote, so an alias never hands out a blob that is gone.
Cached.Has
func (c *Cached) Has(ctx context.Context, h Hash) (bool, error)Has implements Store. It asks the local Dir first, then the remote.
Cached.Link
func (c *Cached) Link(h Hash, to string) errorLink implements Linker. It fetches the blob from the remote first when the local Dir lacks it, and fails as Open does when it can't.
Cached.Open
func (c *Cached) Open(ctx context.Context, h Hash) (io.ReadCloser, error)Open implements Store. On a local miss it fetches the blob from the remote and keeps it. A remote blob whose bytes don't match h fails with ErrCorrupt and is never kept locally. A blob neither holds returns ErrNotFound.
Cached.Put
func (c *Cached) Put(ctx context.Context, r io.Reader) (Hash, error)Put implements Store. It writes the local copy first, then sends that copy to the remote, and returns only after both hold the blob. A remote that stores the bytes under some other hash fails the Put with ErrCorrupt.
Cached.SetAlias
func (c *Cached) SetAlias(ctx context.Context, ns, id string, h Hash) errorSetAlias implements Aliases in the local Dir.
Cached.Sweep
func (c *Cached) Sweep(ctx context.Context, grace time.Duration, refs ...Referrer) (int, error)Sweep implements Store, and returns how many blobs it removed from the remote. It calls each referrer once and sweeps the remote and then the local Dir with what they named, so a local copy goes when its blob is unreferenced and older than grace. A local copy can outlive its remote blob by one sweep, when it was fetched after the remote wrote it. With WithMaxAge, it then drops every local copy older than the max age.
CachedOption
type CachedOption func(*Cached)CachedOption configures a Cached.
WithMaxAge
func WithMaxAge(d time.Duration) CachedOptionWithMaxAge lets Sweep drop any local copy fetched or put more than d ago, whether or not a referrer names it, since the remote still holds the blob. The next Open or Link fetches it again. Zero, the default, keeps a referenced local copy for as long as the remote keeps it.
Dir
type Dir struct {
// contains filtered or unexported fields
}Dir is a Store and a Linker over a folder on this server's disk. A blob lives at <root>/sha256/ab/cdef..., which is agni's layout, so agni's existing blobs folder works as a Dir's root unchanged.
Writes go through a temp file and a rename, so a reader sees a whole blob or none, and several processes can share one Dir. Every read and removal goes through os.Root, so a link planted in the folder can't lead outside it.
NewDir
func NewDir(root string) (*Dir, error)NewDir returns the Dir rooted at root, creating its folder if absent.
Dir.Alias
func (d *Dir) Alias(ctx context.Context, ns, id string) (Hash, bool, error)Alias implements Aliases. An alias file that doesn't hold a valid hash counts as none.
Dir.Has
func (d *Dir) Has(ctx context.Context, h Hash) (bool, error)Has implements Store.
Dir.Link
func (d *Dir) Link(h Hash, to string) errorLink implements Linker. The copy fallback reads through Open, so it copies only a blob that still matches its hash.
Dir.Open
func (d *Dir) Open(ctx context.Context, h Hash) (io.ReadCloser, error)Open implements Store.
Dir.Path
func (d *Dir) Path(h Hash) (string, error)Path returns where h's blob is on disk, whether or not the Dir holds it, for a caller that builds a view some other way than Link. It returns ErrInvalidHash for a malformed h.
Dir.Put
func (d *Dir) Put(ctx context.Context, r io.Reader) (Hash, error)Put implements Store.
Dir.SetAlias
func (d *Dir) SetAlias(ctx context.Context, ns, id string, h Hash) errorSetAlias implements Aliases. It writes through a temp file and a rename, so a reader sees the old alias or the new one.
Dir.Sweep
func (d *Dir) Sweep(ctx context.Context, grace time.Duration, refs ...Referrer) (int, error)Sweep implements Store. It also removes temp files older than grace, which a Put that crashed left behind.
Hash
type Hash stringHash names a blob: "sha256:" and 64 lowercase hex digits. It is agni's format.
HashOf
func HashOf(b []byte) HashHashOf returns the Hash of b.
HashOfKey
func HashOfKey(key string) (Hash, bool)HashOfKey is the inverse of Key. It reports false for a key that names no blob, such as a stray object a person put under the store's prefix.
ParseHash
func ParseHash(s string) (Hash, error)ParseHash checks that s is a Hash, and returns ErrInvalidHash if not.
PutManifest
func PutManifest(ctx context.Context, s Store, m Manifest) (Hash, error)PutManifest checks m and stores it in s, sorted by path, so the same files give the same hash in any order. It doesn't check that s holds the files' blobs. It returns ErrInvalidManifest for a bad path or hash.
Spool
func Spool(r io.Reader, dir string) (*os.File, Hash, int64, error)Spool copies r into a new temp file in dir (os.TempDir when empty), hashing as it goes, and returns the file rewound to its start with its hash and size. A store whose backend needs the key before the upload, such as a bucket, spools first. The caller closes and removes the file.
Linker
type Linker interface {
Store
// Link makes the file at to hold h's contents. It hard-links where the filesystem allows,
// so the view takes no extra space, and copies where it doesn't. A linked file keeps its
// contents after Sweep removes the blob. It returns ErrInvalidHash or ErrNotFound for a bad
// or missing h.
Link(h Hash, to string) error
}Linker is a Store on this server's disk, whose blobs can appear as files in a folder view.
Manifest
type Manifest []ManifestEntryManifest lists the files of a view, such as a mount snapshot, and the blob holding each. It is stored as a blob itself, so a record names a whole snapshot with one hash however many files it has.
GetManifest
func GetManifest(ctx context.Context, s Store, h Hash) (Manifest, error)GetManifest reads the manifest stored under h, checking it as PutManifest does.
ManifestEntry
type ManifestEntry struct {
// Path is the file's place in the view: relative, clean and slash-separated.
Path string `json:"path"`
Hash Hash `json:"hash"`
Size int64 `json:"size"`
}ManifestEntry is one file in a Manifest.
Referrer
type Referrer func(ctx context.Context, keep func(Hash)) errorReferrer lists the hashes one owner still names, by calling keep for each. Every owner of blobs in a store passes one to Sweep, such as an app's designs and the mounts registry's snapshots, and Sweep keeps the union.
Store
type Store interface {
// Put stores what r yields and returns its hash. Putting contents the store already holds
// writes nothing new, and counts as a fresh write for Sweep's grace period, so a sweep can't
// remove the blob before the caller names it.
Put(ctx context.Context, r io.Reader) (Hash, error)
// Open returns the blob's contents. The reader checks the hash as it goes. If the bytes
// don't match, the final Read returns ErrCorrupt in place of io.EOF, so only a caller who
// reads to the end gets the check. A missing blob returns ErrNotFound.
Open(ctx context.Context, h Hash) (io.ReadCloser, error)
// Has reports whether the store holds h.
Has(ctx context.Context, h Hash) (bool, error)
// Sweep removes each blob that no referrer names and that was written more than grace ago,
// and returns how many it removed. The grace period spares a blob that a caller has put but
// not yet named in a record. If any referrer fails, Sweep removes nothing and returns that
// error, since it can't know what is in use.
Sweep(ctx context.Context, grace time.Duration, refs ...Referrer) (int, error)
}Store keeps blobs. Several processes may share one, and Put is safe to call from all of them at once.