objectstore

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2026 License: MIT Imports: 9 Imported by: ? 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.

README

objectstore

Go Reference CI

One small interface for object storage buckets, including the conditional writes that let several processes share a bucket safely, with implementations for the S3 API and a local directory.

go get github.com/jacob2161/objectstore
Package What it is
objectstore The Store interface, TestBucket, and error classification
objectstore/s3store AWS S3, Cloudflare R2, and Google Cloud Storage (S3-compatible endpoint), on aws-sdk-go-v2
objectstore/filestore A local directory on Unix-like systems, for development and tests, with atomic, durable writes
objectstore/objectstoretest Conformance checks every implementation passes

Usage

store, err := s3store.NewStore(&s3store.NewStoreArgs{
	Provider: s3store.ProviderAWS, Region: "us-east-1",
	Bucket: "my-bucket", Prefix: "app", AccessKeyID: id, SecretAccessKey: secret,
})
if err != nil {
	return err
}

// Before relying on a bucket, test what it can do:
checks := objectstore.TestBucket(ctx, store, nil)
// credentials, bucket, list, write, read, delete, conditional_writes, versioning

// Create an object only if it is absent; replace it only if unchanged:
etag, err := store.PutIfAbsent(ctx, "owner.json", body, size)
_, err = store.PutIfMatch(ctx, "owner.json", newBody, newSize, etag)
if errors.Is(err, objectstore.ErrPrecondition) {
	// another process changed it first: read again and decide anew
}
  • TestBucket reports each capability with a Problem (bad credentials, no such bucket, wrong region, unreachable, no conditional writes, versioning on) so an interface can say how to fix it. BeforeWrites adds your own check before anything is written.
  • List is an iter.Seq2, in key order, resumable with startAfter.
  • Versioning warns about buckets that keep billable noncurrent versions.

The s3store tests run against an S3 mock in Docker (skipped without Docker), and against real AWS S3, R2, and GCS buckets with OBJECTSTORE_BUCKET_TEST=1.

Tested on the two newest Go releases. Licensed under the MIT license.

Documentation

Overview

Package objectstore is one small interface for object storage buckets, including the conditional writes that let several processes share a bucket safely: create an object only if it is absent, and replace it only if its ETag still matches.

Package s3store implements it over the S3 API for AWS S3, Cloudflare R2, and Google Cloud Storage's S3-compatible endpoint; package filestore keeps objects in a local directory for development and tests; package objectstoretest holds the conformance checks every implementation passes. TestBucket verifies that a configured bucket does what an application needs before it relies on it.

Example
package main

import (
	"bytes"
	"context"
	"errors"
	"fmt"
	"log"
	"os"

	"github.com/jacob2161/objectstore"
	"github.com/jacob2161/objectstore/filestore"
)

func main() {
	directory, err := os.MkdirTemp("", "objectstore-example")
	if err != nil {
		log.Fatal(err)
	}
	defer os.RemoveAll(directory)
	// s3store.NewStore takes the same place for AWS S3, R2, or GCS.
	store, err := filestore.NewStore(directory)
	if err != nil {
		log.Fatal(err)
	}
	ctx := context.Background()
	if _, err := objectstore.RequireBucketTest(ctx, store, nil); err != nil {
		log.Fatal(err)
	}

	// Of two processes creating the same object, exactly one wins.
	owner := []byte(`{"owner":"first"}`)
	if _, err := store.PutIfAbsent(ctx, "owner.json", bytes.NewReader(owner), int64(len(owner))); err != nil {
		log.Fatal(err)
	}
	second := []byte(`{"owner":"second"}`)
	_, err = store.PutIfAbsent(ctx, "owner.json", bytes.NewReader(second), int64(len(second)))
	fmt.Println(errors.Is(err, objectstore.ErrPrecondition))
}
Output:
true

Index

Examples

Constants

View Source
const DefaultBucketTestPrefix = "objectstore-bucket-test/"

DefaultBucketTestPrefix is the key prefix TestBucket writes and deletes its objects under when its arguments name none.

Variables

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

ErrNotFound reports a missing object.

View Source
var ErrPrecondition = errors.New("precondition failed")

ErrPrecondition reports a conditional write that lost: the object already existed (PutIfAbsent), or it changed or vanished after the caller read its ETag (PutIfMatch). The caller reads the object again and decides anew.

Functions

func DeleteEach

func DeleteEach(ctx context.Context, store Store, keys []string) ([]string, error)

DeleteEach deletes keys one at a time, for providers without batch deletes.

Types

type BucketFeatures

type BucketFeatures struct {
	// ConditionalWrites reports that the bucket refuses a PutIfAbsent on an
	// existing key and a PutIfMatch with a stale ETag. Without them, two
	// processes creating one object at once can both believe they won.
	ConditionalWrites bool
}

BucketFeatures is what a bucket test learned about a bucket beyond its permissions.

func RequireBucketTest

func RequireBucketTest(ctx context.Context, store Store, args *TestBucketArgs) (*BucketFeatures, error)

RequireBucket runs TestBucket and returns its first failure as an error, for callers that need a yes or no. args may be nil.

type BucketTest

type BucketTest struct {
	Name    BucketTestName   `json:"name"`
	Status  BucketTestStatus `json:"status"`
	Problem Problem          `json:"problem,omitempty"`
	// Detail is the provider's own message for a failure, or a note.
	Detail string `json:"detail,omitempty"`
}

BucketTest is one line of a bucket test.

type BucketTestName

type BucketTestName string

BucketTestName names one thing TestBucket verifies. An application's own tests, added through TestBucketArgs.BeforeWrites, use names of their own.

const (
	BucketTestCredentials       BucketTestName = "credentials"
	BucketTestFound             BucketTestName = "bucket"
	BucketTestList              BucketTestName = "list"
	BucketTestWrite             BucketTestName = "write"
	BucketTestRead              BucketTestName = "read"
	BucketTestDelete            BucketTestName = "delete"
	BucketTestConditionalWrites BucketTestName = "conditional_writes"
	BucketTestVersioning        BucketTestName = "versioning"
)

The tests, in the order TestBucket runs and reports them.

type BucketTestStatus

type BucketTestStatus string

BucketTestStatus is how one test ended.

const (
	// BucketTestPassed means the bucket does what the test needs.
	BucketTestPassed BucketTestStatus = "passed"
	// BucketTestFailed blocks the bucket from being used.
	BucketTestFailed BucketTestStatus = "failed"
	// BucketTestWarning works but costs money or safety; the bucket may be used.
	BucketTestWarning BucketTestStatus = "warning"
	// BucketTestSkipped did not run because an earlier test failed.
	BucketTestSkipped BucketTestStatus = "skipped"
)

type BucketTests

type BucketTests []BucketTest

BucketTests is a bucket test's result, in report order.

func TestBucket

func TestBucket(ctx context.Context, store Store, args *TestBucketArgs) BucketTests

TestBucket runs every test a bucket must pass, in order, and never stops early without saying why: after a failure, the tests that depend on it are skipped. It lists first, because a list tells bad credentials and a missing bucket apart without writing anything. args may be nil.

func (BucketTests) FirstFailure

func (c BucketTests) FirstFailure() (BucketTest, bool)

FirstFailure returns the first failed test, if any.

func (BucketTests) FirstFailureName

func (c BucketTests) FirstFailureName() BucketTestName

FirstFailureName names the first failed test, or "" when none failed.

func (BucketTests) Passed

func (c BucketTests) Passed() bool

Passed reports that no test failed; warnings still pass.

type EmptyPrefixRemover

type EmptyPrefixRemover interface {
	// RemoveEmptyPrefix removes prefix's directory if it is empty, and
	// succeeds when it is missing or holds anything.
	RemoveEmptyPrefix(ctx context.Context, prefix string) error
}

EmptyPrefixRemover is a store that keeps directories, such as filestore, and can remove the one under a key prefix once it holds nothing.

type Object

type Object struct {
	Key      string
	Size     int64
	Modified time.Time
}

Object describes a listed object.

type Problem

type Problem string

Problem classifies a failed test, so an interface can say how to fix it. An application's own tests may use problems of their own.

const (
	ProblemNone           Problem = ""
	ProblemBadCredentials Problem = "bad_credentials"
	ProblemNoSuchBucket   Problem = "no_such_bucket"
	ProblemAccessDenied   Problem = "access_denied"
	ProblemWrongRegion    Problem = "wrong_region"
	ProblemUnreachable    Problem = "unreachable"
	ProblemMismatch       Problem = "mismatch"
	ProblemNoConditional  Problem = "no_conditional_writes"
	ProblemVersioning     Problem = "versioning"
	ProblemUnrecognized   Problem = "unrecognized"
)

func Classify

func Classify(err error) Problem

Classify sorts a bucket error into a Problem by its provider error code, or as unreachable for network failures.

type Store

type Store interface {
	// Put uploads size bytes from body. Callers pass a seekable body so the
	// SDK can retry without buffering.
	Put(ctx context.Context, key string, body io.ReadSeeker, size int64) error
	Get(ctx context.Context, key string) (io.ReadCloser, error)
	// PutIfAbsent uploads an object only when key does not exist yet, and
	// returns its ETag. When it exists, the result is ErrPrecondition, so of
	// two concurrent callers exactly one wins. A provider that ignores the
	// condition overwrites instead; TestBucket reports that.
	PutIfAbsent(ctx context.Context, key string, body io.ReadSeeker, size int64) (string, error)
	// PutIfMatch replaces an object only while its ETag is still etag, and
	// returns the new ETag; otherwise the result is ErrPrecondition.
	PutIfMatch(
		ctx context.Context,
		key string,
		body io.ReadSeeker,
		size int64,
		etag string,
	) (string, error)
	// GetWithETag opens an object and returns the ETag to pass to PutIfMatch.
	GetWithETag(ctx context.Context, key string) (io.ReadCloser, string, error)
	// List yields objects whose keys start with prefix, in key order, after startAfter.
	List(ctx context.Context, prefix string, startAfter string) iter.Seq2[Object, error]
	Delete(ctx context.Context, key string) error
	// DeleteMany removes keys, batching where the provider allows; missing
	// keys succeed. It returns the keys it deleted and the first failure.
	DeleteMany(ctx context.Context, keys []string) ([]string, error)
	// Versioning reports whether the bucket keeps noncurrent versions of
	// deleted objects; providers without the API report VersioningUnknown.
	Versioning(ctx context.Context) (Versioning, error)
}

Store is a bucket, already scoped to its configured prefix.

type TestBucketArgs

type TestBucketArgs struct {
	// Prefix is where the test writes and deletes its objects; nothing else
	// may write under it. Empty uses DefaultBucketTestPrefix.
	Prefix string
	// BeforeWrites, when set, adds a test that must pass before anything is
	// written, such as one that no other installation already uses the
	// bucket.
	BeforeWrites func(context.Context) BucketTest
}

TestBucketArgs configures TestBucket.

type Versioning

type Versioning string

Versioning is a bucket's object versioning state.

const (
	// VersioningEnabled keeps billable noncurrent versions after a delete
	// unless a lifecycle rule expires them.
	VersioningEnabled Versioning = "enabled"
	// VersioningSuspended keeps the noncurrent versions written while it was enabled.
	VersioningSuspended Versioning = "suspended"
	// VersioningDisabled deletes objects outright.
	VersioningDisabled Versioning = "disabled"
	// VersioningUnknown is a provider without the versioning API, such as R2.
	VersioningUnknown Versioning = "unknown"
)

Directories

Path Synopsis
Package filestore keeps objects as files under a directory, for development and tests.
Package filestore keeps objects as files under a directory, for development and tests.
Package objectstoretest holds checks every objectstore.Store implementation must pass, for the implementations' own tests.
Package objectstoretest holds checks every objectstore.Store implementation must pass, for the implementations' own tests.
Package s3store implements objectstore.Store over the S3 API for AWS S3, Cloudflare R2, GCS (S3-compatible endpoint with HMAC keys), and MinIO.
Package s3store implements objectstore.Store over the S3 API for AWS S3, Cloudflare R2, GCS (S3-compatible endpoint with HMAC keys), and MinIO.

Jump to

Keyboard shortcuts

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