Documentation
¶
Overview ¶
Package objectstore defines backend-neutral object storage contracts.
A Store keeps immutable object versions addressed by Bucket and Key: Put publishes a new version atomically, Get and Stat read the current one, Delete removes it and List pages through a bucket in key order. MultipartStore adds explicit multipart uploads. Optional capabilities (BatchStater, BatchDeleter, Copier, Presigner) are discovered with type assertions.
PutOptions.IfAbsent and PutOptions.IfMatchVersion are evaluated atomically with publication and form the portable compare-and-swap primitive. A declared SHA-256 digest and size are verified before an object becomes visible. Failures are classified by the sentinel errors ErrNotFound, ErrPrecondition, ErrInvalidBucket, ErrInvalidKey, ErrInvalidRange and ErrInvalidPart; test them with errors.Is. Context cancellation is returned as the context's error.
Implementations live in backend/memory and backend/fs (this module) and in the nested modules backend/s3, backend/gcs, backend/azure, backend/sftp and backend/http. Every implementation is safe for concurrent use, and every read/write implementation passes the conformance suite in package storetest. The packages cas, pack, multipart, lease and handoff build on any Store.
Example ¶
Example writes an immutable object with a create-only condition and a declared digest, then reads an exact byte range. It is the README's quick start; keep the two in sync.
package main
import (
"bytes"
"context"
"crypto/sha256"
"fmt"
"io"
objectstore "github.com/justusschock/object-storage"
"github.com/justusschock/object-storage/backend/memory"
)
func main() {
ctx := context.Background()
store := memory.New()
data := []byte("hello object storage")
digest := sha256.Sum256(data)
object, err := store.Put(ctx, "assets", "greeting.txt", bytes.NewReader(data), objectstore.PutOptions{
IfAbsent: true,
SHA256: &digest,
Metadata: map[string]string{"content": "example"},
})
if err != nil {
panic(err)
}
body, metadata, err := store.Get(ctx, object.Bucket, object.Key, objectstore.GetOptions{
Range: &objectstore.ByteRange{Offset: 6, Length: 6},
})
if err != nil {
panic(err)
}
defer func() { _ = body.Close() }()
rangeBytes, err := io.ReadAll(body)
if err != nil {
panic(err)
}
fmt.Printf("%s (%d-byte object)\n", rangeBytes, metadata.Size)
}
Output: object (20-byte object)
Index ¶
- Variables
- func ValidateBucket(bucket Bucket) error
- func ValidateKey(key Key) error
- func WithProgress(reader io.Reader, total int64, progress ProgressFunc) io.Reader
- func WithProgressReadCloser(body io.ReadCloser, total int64, progress ProgressFunc) io.ReadCloser
- type BatchDeleter
- type BatchStater
- type Bucket
- type ByteRange
- type CompletedPart
- type Copier
- type CopyOptions
- type GetOptions
- type Key
- type ListOptions
- type MultipartStore
- type Object
- type Page
- type PresignedRequest
- type Presigner
- type ProgressFunc
- type PutOptions
- type StatResult
- type Store
- type Upload
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( // ErrNotFound identifies an absent object or multipart upload. ErrNotFound = errors.New("object storage: not found") // ErrPrecondition identifies a failed conditional operation. ErrPrecondition = errors.New("object storage: precondition failed") // ErrInvalidBucket identifies a malformed bucket. ErrInvalidBucket = errors.New("object storage: invalid bucket") // ErrInvalidKey identifies a malformed object key. ErrInvalidKey = errors.New("object storage: invalid key") // ErrInvalidRange identifies an invalid byte range. ErrInvalidRange = errors.New("object storage: invalid byte range") // ErrInvalidPart identifies invalid multipart input or ordering. ErrInvalidPart = errors.New("object storage: invalid multipart part") )
Functions ¶
func ValidateBucket ¶
ValidateBucket checks the portable bucket invariants.
func WithProgress ¶
WithProgress wraps reader so that every successful Read reports cumulative progress. Wrap a Put body to observe uploads (pass PutOptions.Size, because the wrapper hides the reader's own length) or a Get body to observe downloads. A nil progress function returns reader unchanged.
func WithProgressReadCloser ¶
func WithProgressReadCloser(body io.ReadCloser, total int64, progress ProgressFunc) io.ReadCloser
WithProgressReadCloser is WithProgress for bodies that must be closed, such as the reader returned by Store.Get.
Types ¶
type BatchDeleter ¶
type BatchDeleter interface {
// DeleteMany unconditionally deletes keys and returns exactly one error
// per key, in input order. Deleting an absent key succeeds, because batch
// deletion is idempotent on every supported backend. The error return is
// reserved for whole-call failures such as cancellation or an invalid
// bucket.
DeleteMany(context.Context, Bucket, []Key) ([]error, error)
}
BatchDeleter removes many objects with backend-native batching.
type BatchStater ¶
type BatchStater interface {
// StatMany returns exactly one result per key, in input order. Per-key
// failures such as ErrNotFound are reported in StatResult.Err; the error
// return is reserved for whole-call failures such as cancellation or an
// invalid bucket. Successful results carry the fields Stat returns.
StatMany(context.Context, Bucket, []Key) ([]StatResult, error)
}
BatchStater returns metadata for many keys with backend-native batching or bounded parallelism.
type CompletedPart ¶
CompletedPart identifies one immutable uploaded part.
type Copier ¶
type Copier interface {
// Copy publishes the source bytes under the destination key. The
// destination keeps the source SHA-256 digest when it is known. A missing
// source returns ErrNotFound; a failed SourceVersion or destination
// condition returns ErrPrecondition. Source and destination may be in
// different buckets of the same store.
Copy(ctx context.Context, srcBucket Bucket, srcKey Key, dstBucket Bucket, dstKey Key, options CopyOptions) (Object, error)
}
Copier copies objects without routing bytes through the caller.
type CopyOptions ¶
type CopyOptions struct {
// SourceVersion, when non-empty, requires the source's current Version.
SourceVersion string
// IfAbsent and IfMatchVersion are atomic destination write conditions
// with the same meaning as in PutOptions.
IfAbsent bool
IfMatchVersion string
// Metadata, when non-nil, replaces the destination user metadata; nil
// copies the source metadata. ContentType, when non-empty, replaces the
// source content type.
Metadata map[string]string
ContentType string
}
CopyOptions configures one server-side copy.
func (CopyOptions) Clone ¶
func (options CopyOptions) Clone() CopyOptions
Clone returns options with independently owned reference fields.
type GetOptions ¶
GetOptions configures one conditional object read.
func (GetOptions) Clone ¶
func (options GetOptions) Clone() GetOptions
Clone returns options with an independently owned range.
type ListOptions ¶
ListOptions configures a stable, key-ordered page.
Listed objects always carry Bucket, Key, Version, ETag, Size, and ModifiedAt. User Metadata and SHA256 may be omitted (nil Metadata and SHA256Known false) unless IncludeMetadata is set, in which case every listed object carries the fields Stat returns. Backends that hold full metadata cheaply may always include it.
type MultipartStore ¶
type MultipartStore interface {
Store
BeginMultipart(context.Context, Bucket, Key, PutOptions) (Upload, error)
PutPart(context.Context, Upload, int, io.Reader, int64, [32]byte) (CompletedPart, error)
CompleteMultipart(context.Context, Upload, []CompletedPart) (Object, error)
AbortMultipart(context.Context, Upload) error
}
MultipartStore extends Store with explicit multipart custody.
type Object ¶
type Object struct {
Bucket Bucket
Key Key
Version string
ETag string
Size int64
ModifiedAt time.Time
SHA256 [32]byte
SHA256Known bool
Metadata map[string]string
}
Object describes one immutable object version.
SHA256 is meaningful only when SHA256Known is true. Backends report an unknown digest instead of reading object bytes when the digest is not recorded in cheap metadata: for example foreign objects written by other tools, listings without IncludeMetadata, or multipart uploads completed without a declared digest. An unknown digest leaves SHA256 zero, so code that compares SHA256 against an expected digest fails closed.
type PresignedRequest ¶
type PresignedRequest struct {
Method string
URL string
// Header lists the headers the client must send verbatim. Content-Length,
// when present, is informational: HTTP clients derive it from the body.
Header http.Header
ExpiresAt time.Time
}
PresignedRequest is an HTTP request that a third party can execute without credentials until ExpiresAt.
func (PresignedRequest) Clone ¶
func (request PresignedRequest) Clone() PresignedRequest
Clone returns a request with independently owned headers.
type Presigner ¶
type Presigner interface {
// PresignGet authorizes reading an object or exact byte range.
PresignGet(ctx context.Context, bucket Bucket, key Key, expires time.Duration, byteRange *ByteRange) (PresignedRequest, error)
// PresignPut authorizes one object write. ContentType, Metadata,
// IfAbsent, IfMatchVersion, SHA256, and Size are bound into the request;
// the backend enforces a supplied SHA-256 digest before publication.
// Objects written without SHA256 may later report SHA256Known false.
PresignPut(ctx context.Context, bucket Bucket, key Key, expires time.Duration, options PutOptions) (PresignedRequest, error)
// PresignUploadPart authorizes uploading one multipart part of an exact
// size and SHA-256 digest. The ETag response header of the executed
// request identifies the part: complete the upload with
// CompletedPart{Number: number, ETag: etag, Size: size, SHA256: digest}.
PresignUploadPart(ctx context.Context, upload Upload, number int, size int64, digest [32]byte, expires time.Duration) (PresignedRequest, error)
}
Presigner issues time-limited URLs for direct client transfers.
type ProgressFunc ¶
type ProgressFunc func(transferred, total int64)
ProgressFunc observes transfer progress. transferred is the cumulative byte count and total is the expected byte count, or -1 when unknown. Callbacks run synchronously on the reading goroutine and must be fast.
type PutOptions ¶
type PutOptions struct {
ContentType string
Metadata map[string]string
IfAbsent bool
IfMatchVersion string
SHA256 *[32]byte
Size int64
}
PutOptions configures one conditional object write.
IfAbsent and IfMatchVersion are evaluated atomically with publication and together form the portable compare-and-swap primitive: read an object's Version, then write with IfMatchVersion set to it; ErrPrecondition reports that another writer won. Versions identify stored contents, and an S3 entity tag repeats when identical bytes are written again, so CAS users should encode a changing value (a counter, token, or timestamp) in the object.
A non-nil SHA256 is verified before the object becomes visible. Size, when positive, is the exact expected body length: it lets backends stream bodies without buffering, and a mismatch fails with ErrPrecondition. Zero means the length is unknown; negative values are invalid.
func (PutOptions) Clone ¶
func (options PutOptions) Clone() PutOptions
Clone returns options with independently owned reference fields.
func (PutOptions) ValidateSize ¶
func (options PutOptions) ValidateSize() error
ValidateSize rejects negative expected sizes with ErrInvalidRange.
type StatResult ¶
StatResult is the outcome of one key in a batch metadata lookup.
type Store ¶
type Store interface {
Put(context.Context, Bucket, Key, io.Reader, PutOptions) (Object, error)
Get(context.Context, Bucket, Key, GetOptions) (io.ReadCloser, Object, error)
Stat(context.Context, Bucket, Key) (Object, error)
Delete(context.Context, Bucket, Key, string) error
List(context.Context, Bucket, ListOptions) (Page, error)
}
Store provides immutable-version object operations.
Example (CompareAndSwap) ¶
ExampleStore_compareAndSwap updates an object only if nobody replaced it since it was read: IfMatchVersion is the portable compare-and-swap.
package main
import (
"bytes"
"context"
"errors"
"fmt"
objectstore "github.com/justusschock/object-storage"
"github.com/justusschock/object-storage/backend/memory"
)
func main() {
ctx := context.Background()
store := memory.New()
first, err := store.Put(ctx, "state", "counter", bytes.NewReader([]byte("1")), objectstore.PutOptions{IfAbsent: true})
if err != nil {
panic(err)
}
if _, err := store.Put(ctx, "state", "counter", bytes.NewReader([]byte("2")), objectstore.PutOptions{IfMatchVersion: first.Version}); err != nil {
panic(err)
}
// A second writer still holding the first version loses.
_, err = store.Put(ctx, "state", "counter", bytes.NewReader([]byte("2")), objectstore.PutOptions{IfMatchVersion: first.Version})
fmt.Println(errors.Is(err, objectstore.ErrPrecondition))
}
Output: true
Example (ExactRange) ¶
package main
import (
"bytes"
"context"
"fmt"
"io"
objectstore "github.com/justusschock/object-storage"
"github.com/justusschock/object-storage/backend/memory"
)
func main() {
store := memory.New()
_, err := store.Put(context.Background(), "assets", "digits.txt", bytes.NewReader([]byte("0123456789")), objectstore.PutOptions{})
if err != nil {
panic(err)
}
body, object, err := store.Get(context.Background(), "assets", "digits.txt", objectstore.GetOptions{Range: &objectstore.ByteRange{Offset: 3, Length: 4}})
if err != nil {
panic(err)
}
defer func() { _ = body.Close() }()
data, err := io.ReadAll(body)
if err != nil {
panic(err)
}
fmt.Printf("%s %d\n", data, object.Size)
}
Output: 3456 10
Directories
¶
| Path | Synopsis |
|---|---|
|
backend
|
|
|
fs
Package fs provides a filesystem object store that is safe for concurrent use by many goroutines and many processes sharing one root directory.
|
Package fs provides a filesystem object store that is safe for concurrent use by many goroutines and many processes sharing one root directory. |
|
memory
Package memory provides an in-memory object store for tests and local use.
|
Package memory provides an in-memory object store for tests and local use. |
|
azure
module
|
|
|
gcs
module
|
|
|
http
module
|
|
|
s3
module
|
|
|
sftp
module
|
|
|
Package cas stores immutable content addressed by its SHA-256 digest.
|
Package cas stores immutable content addressed by its SHA-256 digest. |
|
Package handoff transports lifecycle artifacts through object storage.
|
Package handoff transports lifecycle artifacts through object storage. |
|
Package lease implements distributed-coordination fenced leases on top of any object store that honors conditional writes.
|
Package lease implements distributed-coordination fenced leases on top of any object store that honors conditional writes. |
|
Package multipart provides bounded multipart upload orchestration.
|
Package multipart provides bounded multipart upload orchestration. |
|
Package pack bundles many content-addressed blobs into one immutable data object plus a binary index, so a reader fetches any blob with one exact ranged read.
|
Package pack bundles many content-addressed blobs into one immutable data object plus a binary index, so a reader fetches any blob with one exact ranged read. |
|
Package storetest is the conformance suite for implementations of objectstore.Store and objectstore.MultipartStore.
|
Package storetest is the conformance suite for implementations of objectstore.Store and objectstore.MultipartStore. |