blob

package
v0.7.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 27, 2026 License: Apache-2.0 Imports: 26 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package blob stores content-addressed objects: file contents and trees.

Objects are immutable. Put returns the hash of the object, and storing the same bytes twice is a no-op. Every read is verified against its hash, so a corrupted store fails loudly instead of returning wrong content.

Index

Constants

View Source
const DefaultCacheBytes = 64 << 20

DefaultCacheBytes is the memory cache in front of a bucket unless the URL says otherwise (cache=).

View Source
const MinPartSize = 5 << 20

MinPartSize is the smallest part S3 accepts in a multipart upload.

Variables

View Source
var ErrCorrupt = errors.New("object corrupt")

ErrCorrupt is returned when stored bytes do not match their hash.

View Source
var ErrNotFound = errors.New("object not found")

ErrNotFound is returned when an object is not in the store.

Functions

func GetKind

func GetKind(ctx context.Context, s Store, want hash.Kind, h hash.Hash) ([]byte, error)

GetKind is Get that also checks the object has the expected kind.

func IsNotFound added in v0.5.0

func IsNotFound(err error) bool

IsNotFound reports whether err is a 404 from the service.

func VerifySigV4 added in v0.5.0

func VerifySigV4(r *http.Request, cr Credentials, region string, body []byte) error

VerifySigV4 checks a signed request the way a server does, recomputing the signature from what arrived. Test servers (internal/blob/s3test) use it; body is the request body already read.

Types

type CacheStats added in v0.5.0

type CacheStats struct {
	Hits, Misses int64
	Objects      int
	Bytes        int64
}

CacheStats counts cache use.

type Cached added in v0.5.0

type Cached struct {
	// contains filtered or unexported fields
}

Cached keeps recently used objects of a remote store in memory, bounded by total size, least recently used first out. Objects are immutable, so a cached object never goes stale; only presence is cached, never absence (another server may store the object a moment later). Objects are only deleted by an organization purge, and only when no repository records them, so a stale cached object is never served through a repository; Put always goes to the store behind (see Put).

func NewCached added in v0.5.0

func NewCached(inner Store, maxBytes int64) *Cached

NewCached wraps inner with a cache of at most maxBytes of object data. Objects larger than an eighth of that are not cached, so one large file cannot push out everything else.

func (*Cached) Delete added in v0.6.0

func (c *Cached) Delete(ctx context.Context, h hash.Hash) error

Delete implements Deleter: the object leaves the cache and the store behind it.

func (*Cached) Get added in v0.5.0

func (c *Cached) Get(ctx context.Context, h hash.Hash) (hash.Kind, []byte, error)

Get implements Store. Callers may change the returned slice: they get a copy, as from the other stores.

func (*Cached) Has added in v0.5.0

func (c *Cached) Has(ctx context.Context, h hash.Hash) (bool, error)

Has implements Store.

func (*Cached) Inner added in v0.5.0

func (c *Cached) Inner() Store

Inner is the wrapped store.

func (*Cached) List added in v0.5.0

func (c *Cached) List(ctx context.Context, fn func(hash.Hash) error) error

List implements Lister when the inner store does.

func (*Cached) Put added in v0.5.0

func (c *Cached) Put(ctx context.Context, kind hash.Kind, data []byte) (hash.Hash, error)

Put implements Store. It always asks the store behind the cache (which skips objects it has with a HEAD request): an organization purge on another server may have deleted an object this cache still holds, and a Put must bring it back.

func (*Cached) Size added in v0.5.0

func (c *Cached) Size(ctx context.Context, h hash.Hash) (int64, error)

Size implements Sizer when the inner store does.

func (*Cached) Stats added in v0.5.0

func (c *Cached) Stats() CacheStats

Stats returns the cache counters.

func (*Cached) String added in v0.5.0

func (c *Cached) String() string

String names the store for logs.

type CopyOptions added in v0.5.0

type CopyOptions struct {
	// Jobs is how many objects are copied at once (default 8).
	Jobs int
	// VerifyExisting reads back objects the destination already has
	// instead of trusting them; without it they are skipped, which makes a
	// second run after an interruption fast.
	VerifyExisting bool
	// Progress, when set, is called after every 1000 objects and at the end.
	Progress func(CopyStats)
}

CopyOptions configures Copy.

type CopyStats added in v0.5.0

type CopyStats struct {
	Seen     int64 // objects listed in the source
	Copied   int64 // written to the destination and read back
	Skipped  int64 // already in the destination
	Verified int64 // already in the destination, read back and correct
	Bytes    int64 // uncompressed bytes written
}

CopyStats counts what Copy did.

func Copy added in v0.5.0

func Copy(ctx context.Context, src, dst Store, o CopyOptions) (CopyStats, error)

Copy copies every object of src into dst. Each object is read from src (verified against its hash on read), written to dst and read back from dst, so a finished copy is known to be complete and correct. Writes are atomic per object and objects are immutable, so an interrupted copy is resumed by running it again: objects already in dst are skipped.

type Credentials added in v0.5.0

type Credentials struct {
	AccessKeyID     string
	SecretAccessKey string
	SessionToken    string // optional, for temporary credentials
}

Credentials sign requests to an S3-compatible service. They never appear in logs or error messages: String, GoString and LogValue redact them.

func CredentialsFromEnv added in v0.5.0

func CredentialsFromEnv(prefix string, getenv func(string) string) (Credentials, error)

CredentialsFromEnv reads PREFIX_ACCESS_KEY_ID, PREFIX_SECRET_ACCESS_KEY and PREFIX_SESSION_TOKEN (each also as PREFIX_..._FILE, a file holding the value), falling back to AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY and AWS_SESSION_TOKEN. Errors name the variables, never their values.

func (Credentials) Format added in v0.5.0

func (Credentials) Format(f fmt.State, _ rune)

Format keeps %v, %+v and %#v of a struct holding Credentials redacted.

func (Credentials) GoString added in v0.5.0

func (Credentials) GoString() string

func (Credentials) LogValue added in v0.5.0

func (Credentials) LogValue() slog.Value

func (Credentials) String added in v0.5.0

func (Credentials) String() string

type Deleter added in v0.6.0

type Deleter interface {
	Delete(ctx context.Context, h hash.Hash) error
}

Deleter is a Store that can delete an object. Objects are shared between repositories (content-addressed), so only the organization purge deletes, and only objects no repository records any more (see store.RecordRepoObjects for how a recording racing a deletion is caught). Deleting an object that is not there is not an error.

func AsDeleter added in v0.6.0

func AsDeleter(s Store) (Deleter, bool)

AsDeleter returns s, or the first store it wraps, as a Deleter. A cache in front of the store is a Deleter itself, so the object also leaves the cache.

type Disk

type Disk struct {
	// contains filtered or unexported fields
}

Disk stores objects as files under a root directory, fanned out by the first two bytes of the hash: root/9f/1c/9f1c....

func NewDisk

func NewDisk(root string) (*Disk, error)

NewDisk opens (and creates) a disk store at root.

func (*Disk) Delete added in v0.6.0

func (d *Disk) Delete(ctx context.Context, h hash.Hash) error

Delete implements Deleter.

func (*Disk) Get

func (d *Disk) Get(ctx context.Context, h hash.Hash) (hash.Kind, []byte, error)

Get implements Store.

func (*Disk) Has

func (d *Disk) Has(ctx context.Context, h hash.Hash) (bool, error)

Has implements Store.

func (*Disk) List added in v0.5.0

func (d *Disk) List(ctx context.Context, fn func(hash.Hash) error) error

List implements Lister. Temporary files of unfinished writes and anything else that is not an object are skipped.

func (*Disk) Put

func (d *Disk) Put(ctx context.Context, kind hash.Kind, data []byte) (hash.Hash, error)

Put implements Store.

func (*Disk) Root added in v0.5.0

func (d *Disk) Root() string

Root is the directory the store keeps its objects in.

func (*Disk) Size added in v0.5.0

func (d *Disk) Size(_ context.Context, h hash.Hash) (int64, error)

Size implements Sizer: the bytes the object's file takes.

func (*Disk) String added in v0.5.0

func (d *Disk) String() string

String names the store for logs.

type ListEntry added in v0.5.0

type ListEntry struct {
	Key          string
	Size         int64
	LastModified time.Time
}

ListEntry is one object of a listing; Key is relative to the prefix.

type Lister added in v0.5.0

type Lister interface {
	List(ctx context.Context, fn func(hash.Hash) error) error
}

Lister is a Store that can list every object it holds, in no particular order. Copies between stores (vx-server blobs copy) need it.

func AsLister added in v0.5.0

func AsLister(s Store) (Lister, bool)

AsLister returns s, or the first store it wraps, as a Lister.

type Mem

type Mem struct {
	// contains filtered or unexported fields
}

Mem is an in-memory Store for tests and short-lived work.

func NewMem

func NewMem() *Mem

NewMem returns an empty in-memory store.

func (*Mem) Delete added in v0.6.0

func (m *Mem) Delete(_ context.Context, h hash.Hash) error

Delete implements Deleter.

func (*Mem) Get

func (m *Mem) Get(_ context.Context, h hash.Hash) (hash.Kind, []byte, error)

Get implements Store.

func (*Mem) Has

func (m *Mem) Has(_ context.Context, h hash.Hash) (bool, error)

Has implements Store.

func (*Mem) Len

func (m *Mem) Len() int

Len returns the number of stored objects.

func (*Mem) List added in v0.5.0

func (m *Mem) List(ctx context.Context, fn func(hash.Hash) error) error

List implements Lister.

func (*Mem) Put

func (m *Mem) Put(_ context.Context, kind hash.Kind, data []byte) (hash.Hash, error)

Put implements Store.

func (*Mem) Size added in v0.5.0

func (m *Mem) Size(_ context.Context, h hash.Hash) (int64, error)

Size implements Sizer with the object's uncompressed length.

type OpenOptions added in v0.5.0

type OpenOptions struct {
	// DiskDir is the disk store used when the URL is empty.
	DiskDir string
	// EnvPrefix names the credential variables: PREFIX_ACCESS_KEY_ID,
	// PREFIX_SECRET_ACCESS_KEY and PREFIX_SESSION_TOKEN, or the same with
	// _FILE naming a file that holds the value. Default "VX_BLOB". The
	// AWS_* variables are the fallback.
	EnvPrefix string
	// Getenv defaults to os.Getenv.
	Getenv func(string) string
	// NoCache opens a bucket without the memory cache (copies verify what
	// is really stored).
	NoCache    bool
	HTTPClient *http.Client
}

OpenOptions configures Open.

type S3 added in v0.5.0

type S3 struct {
	// contains filtered or unexported fields
}

S3 stores objects in a bucket of an S3-compatible service, under the client's prefix and with the disk store's layout and format (prefix/9f/1c/9f1c..., "vx1" + kind + zstd). Objects are immutable and content-addressed, so several servers can share one bucket: two writes of one object write the same bytes.

func NewS3 added in v0.5.0

func NewS3(c *S3Client) (*S3, error)

NewS3 returns a store on the client's bucket and prefix.

func (*S3) Client added in v0.5.0

func (s *S3) Client() *S3Client

Client is the underlying client.

func (*S3) Delete added in v0.6.0

func (s *S3) Delete(ctx context.Context, h hash.Hash) error

Delete implements Deleter. S3 deletes of missing keys succeed.

func (*S3) Get added in v0.5.0

func (s *S3) Get(ctx context.Context, h hash.Hash) (hash.Kind, []byte, error)

Get implements Store; the object is verified against its hash.

func (*S3) Has added in v0.5.0

func (s *S3) Has(ctx context.Context, h hash.Hash) (bool, error)

Has implements Store with a HEAD request: nothing is downloaded.

func (*S3) List added in v0.5.0

func (s *S3) List(ctx context.Context, fn func(hash.Hash) error) error

List implements Lister. Keys under the prefix that are not objects of this layout (for example backups kept in the same bucket) are skipped.

func (*S3) Put added in v0.5.0

func (s *S3) Put(ctx context.Context, kind hash.Kind, data []byte) (hash.Hash, error)

Put implements Store. An object already in the bucket is not uploaded again: a HEAD request is cheaper than a PUT.

func (*S3) Size added in v0.5.0

func (s *S3) Size(ctx context.Context, h hash.Hash) (int64, error)

Size implements Sizer: the stored (compressed) bytes, from a HEAD request.

func (*S3) String added in v0.5.0

func (s *S3) String() string

String names the store for logs.

type S3Client added in v0.5.0

type S3Client struct {
	// contains filtered or unexported fields
}

S3Client is a small client for the part of the S3 API vx needs: put, get, head, list and delete objects, and multipart uploads for large streams. Every request is signed with SigV4 and retried with backoff.

func NewS3Client added in v0.5.0

func NewS3Client(cfg S3Config) (*S3Client, error)

NewS3Client checks cfg and returns a client.

func (*S3Client) CreateBucket added in v0.5.0

func (c *S3Client) CreateBucket(ctx context.Context) error

CreateBucket creates the client's bucket; one that exists and is yours is not an error. Servers never call it (buckets are made by whoever runs the service); tests and first-time setup against MinIO do.

func (*S3Client) Delete added in v0.5.0

func (c *S3Client) Delete(ctx context.Context, key string) error

Delete removes an object; a missing object is not an error.

func (*S3Client) GetBytes added in v0.5.0

func (c *S3Client) GetBytes(ctx context.Context, key string) ([]byte, error)

GetBytes reads a whole object. A missing object is an *S3Error with status 404 (IsNotFound). Reads cut short are retried.

func (*S3Client) Head added in v0.5.0

func (c *S3Client) Head(ctx context.Context, key string) (size int64, exists bool, err error)

Head returns the object's size; exists is false for a missing object.

func (*S3Client) List added in v0.5.0

func (c *S3Client) List(ctx context.Context, prefix string, fn func(ListEntry) error) error

List calls fn for every object whose key (relative to the client's prefix) starts with prefix, in key order. It uses ListObjects (v1) with markers, which every S3-compatible service supports.

func (*S3Client) Open added in v0.5.0

func (c *S3Client) Open(ctx context.Context, key string) (io.ReadCloser, int64, error)

Open streams an object. When the connection breaks mid-way, the reader continues where it stopped with a ranged request for the same version (If-Match on its ETag), so large downloads survive flaky networks.

func (*S3Client) Prefix added in v0.5.0

func (c *S3Client) Prefix() string

Prefix is the key prefix of every object, "" or ending in "/".

func (*S3Client) Put added in v0.5.0

func (c *S3Client) Put(ctx context.Context, key string, body []byte, contentType string) error

Put stores body under key (relative to the prefix).

func (*S3Client) PutStream added in v0.5.0

func (c *S3Client) PutStream(ctx context.Context, key string, r io.Reader, partSize int, contentType string) (int64, error)

PutStream uploads r under key with bounded memory: a body that fits in one part goes up with one PUT, a larger one as a multipart upload of partSize parts (default 16 MB, at least 5 MB). A failed upload is aborted so it leaves nothing behind. It returns the bytes uploaded.

func (*S3Client) String added in v0.5.0

func (c *S3Client) String() string

String names the bucket for logs, without credentials.

type S3Config added in v0.5.0

type S3Config struct {
	Bucket string
	// Prefix is prepended to every key; "" or ending in "/".
	Prefix string
	// Region signs requests: "us-east-1" for MinIO, "auto" for R2 and GCS.
	Region string
	// Endpoint is scheme://host[:port]; empty means AWS S3 in Region.
	Endpoint string
	// PathStyle puts the bucket in the path (endpoint/bucket/key) instead
	// of the host name (bucket.endpoint/key).
	PathStyle   bool
	Credentials Credentials
	// HTTPClient defaults to one with sensible timeouts.
	HTTPClient *http.Client
	// MaxAttempts bounds tries per request, retrying network errors, 5xx
	// and 429 with exponential backoff (default 5).
	MaxAttempts int
	// RetryBase is the first backoff (default 200ms); it doubles per try,
	// up to 5 s, with jitter.
	RetryBase time.Duration
}

S3Config says how to reach a bucket of an S3-compatible service: AWS S3, Cloudflare R2, MinIO, or Google Cloud Storage through its XML API with HMAC keys.

func ParseBucketURL added in v0.5.0

func ParseBucketURL(rawURL string) (S3Config, int64, error)

ParseBucketURL reads s3:// and gs:// URLs into a configuration without credentials, and the cache size they ask for.

type S3Error added in v0.5.0

type S3Error struct {
	Method, Key string
	Status      int
	Code        string
	Message     string
}

S3Error is an error response from the service.

func (*S3Error) Error added in v0.5.0

func (e *S3Error) Error() string

type Sizer added in v0.5.0

type Sizer interface {
	Size(ctx context.Context, h hash.Hash) (int64, error)
}

Sizer is a Store that tells how many bytes an object takes in it (compressed, as stored), without reading the object.

func AsSizer added in v0.5.0

func AsSizer(s Store) (Sizer, bool)

AsSizer returns s, or the first store it wraps, as a Sizer.

type Store

type Store interface {
	// Put stores data under the hash of kind and data.
	Put(ctx context.Context, kind hash.Kind, data []byte) (hash.Hash, error)
	// Get returns the object and its kind.
	Get(ctx context.Context, h hash.Hash) (hash.Kind, []byte, error)
	// Has reports whether the object exists.
	Has(ctx context.Context, h hash.Hash) (bool, error)
}

Store is a content-addressed object store.

func Fresh added in v0.6.0

func Fresh(s Store) Store

Fresh returns the store under s's wrappers and caches, whose Has and Put ask the backend itself: a cache on one server may still hold an object another server deleted.

func Open added in v0.5.0

func Open(rawURL string, o OpenOptions) (Store, error)

Open opens the store a URL names:

""                     the disk store in DiskDir
file:///srv/vx/objects a disk store
s3://BUCKET/PREFIX?region=REGION&endpoint=https://HOST&style=path|virtual&cache=64MB
gs://BUCKET/PREFIX     Google Cloud Storage with HMAC keys (S3 interoperability)

A bucket store gets a memory cache of hot objects (cache=, default 64MB; cache=0 turns it off).

type Unwrapper added in v0.5.0

type Unwrapper interface {
	Unwrap() Store
}

Unwrapper is a Store that wraps another (metrics, caches); AsLister and AsSizer look through it for the optional interfaces.

Directories

Path Synopsis
Package s3test is an in-process fake of the S3 API for tests: one bucket, objects in memory, SigV4 signatures checked on every request, multipart uploads, ranged reads, ListObjects (v1) and injected failures.
Package s3test is an in-process fake of the S3 API for tests: one bucket, objects in memory, SigV4 signatures checked on every request, multipart uploads, ranged reads, ListObjects (v1) and injected failures.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL