fs

package module
v0.15.0 Latest Latest
Warning

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

Go to latest
Published: Oct 6, 2026 License: Apache-2.0 Imports: 9 Imported by: 1 module, 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

fs Go Reference codecov experimental

go-faster/fs

S3-compatible object storage in a single static binary and an embeddable Go library. It began as a lightweight server for development and testing.

Status: experimental. The single-node server is mature and heavily conformance-tested. A Garage-style cluster (zone/rack-aware replication) is planned, see #279. Pin a version and read COMPATIBILITY.md before trusting production data to it.

Features

Core S3 server
  • Bucket operations (create, delete, list) and object operations (put, get, delete, list, copy, tagging, metadata, x-amz-meta-*).
  • Multipart uploads, presigned URLs (≤7-day expiry) and streaming (chunked) uploads.
  • AWS Signature V4 auth by default: multiple credentials, per-bucket grants (read/write/admin), public-read buckets and canned ACLs.
  • Hot-reloadable TLS; credential and certificate reload on SIGHUP with no restart.
  • Crash-atomic writes, fsync policy control, and content-addressed blocks verified on every read.
  • Compatible with the AWS CLI, MinIO client (mc), s3cmd, rclone and the AWS SDKs; liveness/readiness endpoints and OpenTelemetry metrics/traces.
Operability
  • Admin API on a separate bearer-token listener (runtime access-key CRUD, config reload).
  • systemd unit generation (fs systemd), commented config generation, and a library core with no forced observability stack.

Quick Start:

# Install
go install github.com/go-faster/fs/cmd/fs@latest

# Start the server
fs s3

# Or with custom configuration
fs s3 --addr :9000 --root /data/s3

See COMPATIBILITY.md for the full compatibility statement (what's implemented, what returns NotImplemented, what's planned, and the durability & failure model). Compatibility is measured against the upstream ceph/s3-tests suite and real S3 clients — the machine-generated breakdown is in the S3 conformance report.

Example Usage:

# Using AWS CLI
export AWS_ENDPOINT_URL=http://localhost:8080
aws s3 mb s3://mybucket --endpoint-url $AWS_ENDPOINT_URL
aws s3 cp file.txt s3://mybucket/ --endpoint-url $AWS_ENDPOINT_URL

# Using cURL
curl -X PUT http://localhost:8080/mybucket
curl -X PUT -d "Hello!" http://localhost:8080/mybucket/hello.txt
curl http://localhost:8080/mybucket/hello.txt

Authentication & TLS

The binary authenticates requests with AWS Signature V4 by default. Provide a root credential and (optionally) TLS:

export FS_ROOT_ACCESS_KEY=AKIAEXAMPLE
export FS_ROOT_SECRET_KEY=exampleSecretKey
fs s3 --tls-cert cert.pem --tls-key key.pem

Additional keys, per-bucket grants (read/write/admin), and public-read buckets are configured under auth: in the config file. To run without any authentication (development only), pass --insecure-no-auth.

SigV4 header auth, presigned URLs (≤7-day expiry) and streaming uploads are all verified; TLS certificates hot-reload without dropping connections. As a library, enable it with server.WithAuth(store) / server.WithCORS(cfg) — the bare handler stays anonymous unless you opt in.

Admin API

Multiple access-key/secret credentials can be managed at runtime — without a restart — through a separate admin listener. Config-defined keys stay read-only. Keys created through the admin API are stored in the engine, replicated like any metadata: in a cluster every node accepts them (within seconds on nodes other than the one that created them), and they survive restarts and SIGHUP reloads.

admin:
  enabled: true
  addr: "localhost:8090"   # keep bound to localhost or behind a proxy
  token: "change-me"       # or set FS_ADMIN_TOKEN

It is a JSON API under /api/v1 (bearer-token protected), generated from _oas/admin.yml with ogen: list credentials and their grants, create keys (generating the access key and secret, shown once), delete runtime keys, and reload the config:

# List credentials
curl -H "Authorization: Bearer $FS_ADMIN_TOKEN" localhost:8090/api/v1/access-keys

# Create a credential scoped to buckets matching "uploads-*"
curl -H "Authorization: Bearer $FS_ADMIN_TOKEN" -H "Content-Type: application/json" \
  -d '{"grants":[{"bucket":"uploads-*","permission":"write"}]}' \
  localhost:8090/api/v1/access-keys
Cluster mode (experimental)

With cluster.node_id set, nodes form a cluster: every object's metadata and data are kept on three nodes, spread across zones then racks, written and read at quorum, and repaired in the background (Garage-style; see #279). Nodes agree on a layout — which nodes hold which partitions — and any node serves any key. The same engine runs a single server: leave cluster: out.

storage:
  type: engine
cluster:
  node_id: "node-1"
  advertise_addr: "10.0.0.1:7080"
  peers: ["10.0.0.2:7080"]
  secret: "change-me-0123456789"   # or FS_CLUSTER_SECRET

Assign roles through any node's admin API; gossip carries the result to the rest:

cat > roles.yaml <<'YAML'
members:
  - {id: node-1, zone: dc1, capacity: 4TB}
  - {id: node-2, zone: dc2, capacity: 4TB}
  - {id: node-3, zone: dc3, capacity: 4TB}
YAML
fs layout apply -f roles.yaml --dry-run   # what would move
fs layout apply -f roles.yaml
fs layout show
fs layout nodes
Run as a systemd service

Generate a unit for fs s3 — a per-user service by default, or a hardened system service with --user=false:

# Install and enable a per-user service
fs systemd --install --config ~/fs.yaml
systemctl --user daemon-reload
systemctl --user enable --now fs
loginctl enable-linger "$USER"   # keep it running after logout

# Or emit a system unit
fs systemd --user=false --config /etc/fs/config.yaml | sudo tee /etc/systemd/system/fs.service

The unit wires ExecReload to SIGHUP, so systemctl --user reload fs performs the hot credential/TLS reload.

Operations

  • Durability — data lives in the engine under <storage.root>/.engine (bbolt metadata + SHA-256-named blocks). storage.fsync is file (default: data and metadata are fsynced before a write is acknowledged) or none (dev/CI only); writes are always crash-atomic (no torn object). Every block is verified on read, and in a cluster anti-entropy repairs replicas.
  • Health & readiness — /health (liveness: the process is up) and /ready (readiness: storage is reachable, 503 otherwise). Prometheus /metrics and pprof are served on a separate listener (default localhost:9464, METRICS_ADDR to change).
  • Hot reload — send SIGHUP to reload credentials and the TLS certificate from disk without a restart.

Installation

go install github.com/go-faster/fs/cmd/fs@latest

Or build from source:

git clone https://github.com/go-faster/fs
cd fs
go build -o bin/fs ./cmd/fs

Usage

Quick Start
# Start S3 server with defaults
fs s3

# Show help
fs s3 --help
Configuration

The server supports both YAML configuration files and command-line flags:

# Using YAML configuration
fs s3 --config config.yaml

# Using command-line flags
fs s3 --addr :9000 --root /var/lib/s3data

# Mix both (flags override config file)
fs s3 --config config.yaml --addr :9000

# Generate example configuration
fs s3 --generate-config > my-config.yaml

Run fs s3 --generate-config to produce a fully commented configuration template, and fs s3 --help for the list of flags.

Example Configuration
server:
  addr: ":8080"
  read_timeout: 30s
  write_timeout: 30s
  idle_timeout: 120s
  health_path: "/health"

storage:
  root: ".s3data"

observability:
  service_name: "go-faster/fs"
  enable_request_logging: true
  enable_metrics: true
  enable_tracing: true

Use as a library

The S3 server is embeddable. Install the module and pick a storage backend — engine for durable storage (open it with engine.Open and release it with Close), storagemem for in-memory, or your own implementation of the fs.Storage interface:

go get github.com/go-faster/fs

The library core pulls in no observability stack — wrap the handler yourself (e.g. with otelhttp) via server.NewHandler or Config.WrapHandler.

Custom backends can verify themselves against the storage contract with the storagetest conformance suite:

func TestStorage(t *testing.T) {
	storagetest.Run(t, func(t testing.TB) fs.Storage {
		return mybackend.New(t.TempDir())
	})
}
Mount the handler into your own server

Use server.NewHandler when you already run an http.Server or mux and just want to expose the S3 API (optionally under a path prefix):

package main

import (
	"net/http"

	"github.com/go-faster/fs/engine"
	"github.com/go-faster/fs/server"
)

func main() {
	store, err := engine.Open("/data", engine.Options{})
	if err != nil {
		panic(err)
	}
	defer store.Close()

	mux := http.NewServeMux()
	mux.Handle("/s3/", http.StripPrefix("/s3", server.NewHandler(store)))

	http.ListenAndServe(":8080", mux)
}
Run the turnkey server

Use server.New for a managed server with a health endpoint, request timeouts, optional bucket pre-creation and graceful shutdown driven by a context:

package main

import (
	"context"
	"os/signal"
	"syscall"

	"github.com/go-faster/fs/server"
	"github.com/go-faster/fs/storagemem"
)

func main() {
	ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
	defer stop()

	srv, err := server.New(server.Config{
		Storage: storagemem.New(),
		Addr:    ":9000",
		Buckets: []string{"uploads"}, // pre-created if absent
	})
	if err != nil {
		panic(err)
	}

	// Serves until ctx is canceled, then drains in-flight requests.
	if err := srv.ListenAndServe(ctx); err != nil {
		panic(err)
	}
}
server.Config
Field Default Description
Storage — (required) Backend serving S3 operations (fs.Storage).
Addr :8080 TCP address to listen on.
ReadTimeout / WriteTimeout / IdleTimeout 30s / 30s / 120s Underlying http.Server timeouts.
HealthPath /health Plaintext liveness endpoint; "-" disables it.
ReadyPath / Ready /ready / — Readiness endpoint and its probe; a non-nil probe error returns 503.
Buckets — Buckets created (idempotently) before serving.
Auth / CORS / TLS — SigV4 auth store, per-bucket CORS, and hot-reloadable TLS.
WrapHandler — Wrap the handler with middleware/observability (e.g. otelhttp.NewHandler).

See the server package reference for the full API and runnable examples.

Roadmap

Delivered so far: full SDK wire compatibility, exact S3 semantics and metadata, SigV4 auth/authorization/TLS, canned ACLs, and durability & integrity operations.

Planned and in progress (see findings/ROADMAP.md for the authoritative, detailed list):

  • Lifecycle noncurrent-version cleanup and the rest of lifecycle.
  • Cluster mode — a Garage-style cluster with zone/rack-aware replication (#279).
  • Virtual-host–style addressing, ACME / automatic TLS, and static website hosting.
  • Geo-replication — async bucket-level replication between deployments.
  • Bucket-policy subset — demand-gated, when canned ACLs are not enough.

Development

# Run tests
go test ./...

# Build
go build ./cmd/fs

# Run with coverage
make coverage

License

Apache 2.0

Documentation

Overview

Package fs is a S3-compatible storage server implementation.

Package fs contains the go:generate directives for the repository's generated code.

Index

Constants

View Source
const (
	// OwnershipBucketOwnerEnforced disables ACLs entirely; the bucket owner
	// owns every object.
	OwnershipBucketOwnerEnforced = "BucketOwnerEnforced"
	// OwnershipBucketOwnerPreferred gives the bucket owner objects written
	// with the bucket-owner-full-control canned ACL.
	OwnershipBucketOwnerPreferred = "BucketOwnerPreferred"
	// OwnershipObjectWriter leaves each object owned by its writer.
	OwnershipObjectWriter = "ObjectWriter"
)

Object-ownership settings, which decide who owns objects another principal writes into a bucket. Empty means the bucket has no configuration.

View Source
const (
	LifecycleEnabled  = "Enabled"
	LifecycleDisabled = "Disabled"
)

Lifecycle rule statuses. A disabled rule is stored and returned unchanged and does nothing, which is how S3 lets a client park a rule without deleting it.

View Source
const LifecycleDay = 24 * time.Hour

LifecycleDay is how long a lifecycle "day" lasts.

View Source
const NullVersionID = "null"

NullVersionID is the version ID of an object written while versioning was suspended, and of one that predates the first enable.

It is a real version ID, not a sentinel for "no version": clients send it, listings report it, and a delete addressed at it removes exactly that version. Code that treats it as equivalent to the empty string will work until the first suspended write.

Variables

View Source
var (
	ErrBucketNotFound       = errors.New("bucket not found")
	ErrBucketAlreadyExists  = errors.New("bucket already exists")
	ErrBucketNotEmpty       = errors.New("bucket not empty")
	ErrObjectNotFound       = errors.New("object not found")
	ErrUploadNotFound       = errors.New("upload not found")
	ErrInvalidBucketName    = errors.New("invalid bucket name")
	ErrUnsupportedOperation = errors.New("unsupported operation")
	ErrPreconditionFailed   = errors.New("precondition failed")
	// ErrAccessDenied reports a request the caller is not authorized to make.
	ErrAccessDenied = errors.New("access denied")
	// ErrMethodNotAllowedOnDeleteMarker reports a read addressed at a delete
	// marker. A marker exists but has no content, which S3 distinguishes from
	// a missing key: the caller asked for something that is there and cannot
	// be read, not for something that is not there.
	ErrMethodNotAllowedOnDeleteMarker = errors.New("method not allowed on a delete marker")
	// ErrBucketOwnedBySomeoneElse reports a create against a bucket name that
	// another principal already holds.
	ErrBucketOwnedBySomeoneElse = errors.New("bucket owned by someone else")
	// ErrInvalidDigest reports a Content-MD5 the server could not parse: not
	// base64, or not 16 bytes once decoded.
	ErrInvalidDigest = errors.New("invalid content digest")
	// ErrBadDigest reports a Content-MD5 that parsed but does not match the
	// bytes received. The object is not stored.
	ErrBadDigest = errors.New("content digest mismatch")

	// ErrInvalidKey reports an object key the server cannot address: not valid
	// UTF-8, over the 1024-byte limit, or carrying path elements that would
	// escape the bucket.
	ErrInvalidKey = errors.New("invalid object key")
	// ErrInvalidPart reports that a part referenced by CompleteMultipartUpload
	// was never uploaded or its ETag does not match.
	ErrInvalidPart = errors.New("invalid part")
	// ErrInvalidPartOrder reports that the CompleteMultipartUpload part list is
	// not in strictly ascending part-number order.
	ErrInvalidPartOrder = errors.New("invalid part order")
	// ErrInvalidPartNumber reports a part number outside the valid 1..10000 range.
	ErrInvalidPartNumber = errors.New("invalid part number")
	// ErrEntityTooSmall reports a non-last multipart part smaller than the 5 MiB
	// minimum.
	ErrEntityTooSmall = errors.New("entity too small")
	// ErrInvalidTag reports an object tag set violating the S3 limits
	// (at most 10 tags, unique keys, key ≤ 128 chars, value ≤ 256 chars).
	ErrInvalidTag = errors.New("invalid tag")

	// ErrIntegrity reports that an object's stored content does not match its
	// recorded checksum (bit-rot / corruption detected on read).
	ErrIntegrity = errors.New("object integrity check failed")

	// ErrCustomerKeyMismatch reports a request whose SSE-C key does not fit
	// the object or upload: none for one encrypted with a customer key, or
	// one for one that is not. A key that is present but wrong is
	// ErrAccessDenied.
	ErrCustomerKeyMismatch = errors.New("customer encryption key mismatch")
)

Functions

func LifecycleAbortAt added in v0.13.0

func LifecycleAbortAt(rules []LifecycleRule, key string, started time.Time) (at time.Time, ruleID string)

LifecycleAbortAt is when a multipart upload initiated at started is abandoned under rules, and the ID of the rule that decides it. A zero time means no enabled rule aborts it.

func LifecycleExpiry added in v0.13.0

func LifecycleExpiry(rules []LifecycleRule, key string, modified time.Time) (at time.Time, ruleID string)

LifecycleExpiry returns when key, last modified at modified, expires under rules, and the ID of the rule that decides it. A zero time means no enabled rule expires it.

When more than one rule matches, the earliest expiry wins: S3 has no rule precedence, and the alternative — keeping an object a later rule allows — would leave data alive that a rule the client wrote says should be gone.

func NewVersionID added in v0.13.0

func NewVersionID() string

NewVersionID returns a fresh version identifier.

The format is frozen

32 lowercase hex characters: the first 16 are the bitwise complement of the creation time in unix nanoseconds, the last 16 are random.

Complementing the timestamp is what makes plain ascending lexical order put the *newest* version first — which is the order every read wants, because resolving "the current version" is then "take the first entry", and a directory listing or a sorted key range already arrives that way. No index, no cached pointer, no separate ordering column.

The random half breaks ties between versions created in the same nanosecond and keeps IDs unguessable, so one version ID does not let a caller derive its neighbors.

This format cannot change once written. Every stored version is named by it and every listing sorts on it, so a later change means migrating live data — the exact trap SeaweedFS fell into by shipping IDs that did not sort and then having to convert them mid-flight. It is fixed here deliberately, at the cost of getting it right before the first release rather than after.

func ValidVersionID added in v0.13.0

func ValidVersionID(s string) bool

ValidVersionID reports whether s is a version identifier this server could have produced, or the reserved "null".

Callers send version IDs back to us, so this is the guard between a client's string and a filesystem path or a lookup key.

func WithCustomerKey added in v0.14.0

func WithCustomerKey(ctx context.Context, k CustomerKey) context.Context

WithCustomerKey returns ctx carrying k.

Types

type ACL added in v0.5.0

type ACL string

ACL is a canned S3 access-control level applied to a bucket or object. Only the canned subset is modeled — full ACL grammar (arbitrary grantees, AccessControlPolicy XML) is out of scope; the `?acl` subresource is echo-only.

const (
	// ACLPrivate grants no anonymous access (the default).
	ACLPrivate ACL = "private"
	// ACLPublicRead allows anonymous reads.
	ACLPublicRead ACL = "public-read"
	// ACLPublicReadWrite allows anonymous reads and writes.
	ACLPublicReadWrite ACL = "public-read-write"
)

func ParseACL added in v0.5.0

func ParseACL(s string) ACL

ParseACL normalizes a canned ACL header value, defaulting empty or unrecognized values to ACLPrivate.

func (ACL) AllowsAnonRead added in v0.5.0

func (a ACL) AllowsAnonRead() bool

AllowsAnonRead reports whether the level permits anonymous reads.

func (ACL) AllowsAnonWrite added in v0.5.0

func (a ACL) AllowsAnonWrite() bool

AllowsAnonWrite reports whether the level permits anonymous writes.

type Bucket

type Bucket struct {
	Name         string
	CreationDate time.Time
}

Bucket represents an S3 bucket.

type BucketCORSStore added in v0.13.0

type BucketCORSStore interface {
	BucketCORS(ctx context.Context, bucket string) ([]CORSRule, error)
	SetBucketCORS(ctx context.Context, bucket string, rules []CORSRule) error
	DeleteBucketCORS(ctx context.Context, bucket string) error
}

BucketCORSStore is the optional capability of storing a bucket's CORS rules, which is what the ?cors subresource reads and writes.

CORS can also be supplied at construction (server.WithCORS) for deployments that configure it out of band. A bucket's stored rules win when it has any: a client that called PutBucketCors expects that to be what applies.

BucketCORS returns nil rules when the bucket has no configuration, which the S3 layer reports as NoSuchCORSConfiguration.

type BucketEncrypter added in v0.13.0

type BucketEncrypter interface {
	// BucketEncryption returns the bucket's default algorithm, empty when it
	// has none configured. ErrBucketNotFound when the bucket is absent.
	BucketEncryption(ctx context.Context, bucket string) (string, error)
	// SetBucketEncryption records the default; empty clears it.
	SetBucketEncryption(ctx context.Context, bucket, algorithm string) error
}

BucketEncrypter is the optional capability of remembering a bucket's default server-side encryption, backing the ?encryption subresource.

It is separate from BucketSettingsStore, and deliberately so: a backend that can store bucket settings may still be unable to encrypt, and letting it record a default it cannot honor would produce a bucket whose every write is refused. Only a backend that can actually encrypt should advertise this, so ?encryption reports NotImplemented rather than accepting a setting that does nothing.

type BucketLifecycleStore added in v0.13.0

type BucketLifecycleStore interface {
	BucketLifecycle(ctx context.Context, bucket string) ([]LifecycleRule, error)
	SetBucketLifecycle(ctx context.Context, bucket string, rules []LifecycleRule) error
	DeleteBucketLifecycle(ctx context.Context, bucket string) error
}

BucketLifecycleStore is the optional capability of storing a bucket's lifecycle rules, which is what the ?lifecycle subresource reads and writes.

Storing rules is only half of the feature: the other half is the sweep that enforces them (internal/lifecycle). A backend implements this interface when it can persist the rules; the sweep runs over the fs.Storage interface and so works against any backend that does.

BucketLifecycle returns nil rules when the bucket has no configuration, which the S3 layer reports as NoSuchLifecycleConfiguration.

type BucketOwnership added in v0.13.0

type BucketOwnership interface {
	// CreateBucketOwned creates a bucket owned by owner, reporting
	// ErrBucketAlreadyExists exactly as CreateBucket does.
	CreateBucketOwned(ctx context.Context, bucket string, owner Owner) error
	// BucketOwner returns the recorded owner, zero when the bucket predates
	// ownership or was created without an identity; ErrBucketNotFound when the
	// bucket is absent.
	BucketOwner(ctx context.Context, bucket string) (Owner, error)
}

BucketOwnership is the optional capability of recording which principal created a bucket.

Ownership is what makes a bucket belong to someone: it decides who may reach it when no explicit grant says otherwise, and it is what tells a re-create by its owner (idempotent, as in S3's default region) from one by a stranger (BucketAlreadyExists). A backend that does not implement it has unowned buckets, and the S3 layer falls back to grants alone — which is how this server behaved before ownership existed.

type BucketSettingsStore added in v0.13.0

type BucketSettingsStore interface {
	BucketPublicAccessBlock(ctx context.Context, bucket string) (*PublicAccessBlock, error)
	SetBucketPublicAccessBlock(ctx context.Context, bucket string, block *PublicAccessBlock) error
	BucketObjectOwnership(ctx context.Context, bucket string) (string, error)
	SetBucketObjectOwnership(ctx context.Context, bucket, ownership string) error
}

BucketSettingsStore is the optional capability of storing the small per-bucket settings that have no home of their own: the public-access-block configuration and the object-ownership rule.

Both distinguish "unset" from any particular value — S3 reports an absent configuration as its own error rather than as a default — so both getters return a zero value that means absent: a nil block, an empty ownership.

type CORSRule added in v0.13.0

type CORSRule struct {
	AllowedOrigins []string
	AllowedMethods []string
	AllowedHeaders []string
	ExposeHeaders  []string
	MaxAgeSeconds  int
}

CORSRule allows cross-origin requests matching AllowedOrigins and AllowedMethods. It lives here, rather than in the cors package, because a bucket's rules are stored with the bucket; the cors package aliases it.

func (*CORSRule) AllowsHeaders added in v0.13.0

func (r *CORSRule) AllowsHeaders(requested string) bool

AllowsHeaders reports whether the rule permits every requested header (the comma-separated Access-Control-Request-Headers value).

type CompleteMultipartUploadRequest added in v0.0.4

type CompleteMultipartUploadRequest struct {
	Bucket   string
	Key      string
	UploadID string
	Parts    []CompletedPart
	// Conditions are the conditional-write headers carried by the completion
	// request. A backend that supports them must evaluate them atomically with
	// the write, exactly as it does for a conditional PutObject; the zero value
	// imposes no condition.
	Conditions Conditions
	// Checksum is the completed object's digest as the client computed it, and
	// ChecksumType which kind it is. Both are claims: the server composes its
	// own from the parts and refuses a completion that disagrees.
	Checksum     string
	ChecksumType string
}

CompleteMultipartUploadRequest represents a request to complete multipart upload.

type CompleteMultipartUploadResponse added in v0.0.4

type CompleteMultipartUploadResponse struct {
	Location string
	Bucket   string
	Key      string
	ETag     string
	// ServerSideEncryption echoes the algorithm the completed object was
	// encrypted with, empty when it was stored in the clear.
	ServerSideEncryption string
	// ChecksumAlgorithm, Checksum and ChecksumType describe the completed
	// object's client-visible digest. A completion echoes them unconditionally,
	// as a write does: the client just supplied the parts and is entitled to
	// see what they added up to.
	ChecksumAlgorithm string
	Checksum          string
	ChecksumType      string
}

CompleteMultipartUploadResponse represents the response for completing multipart upload.

type CompletedPart added in v0.0.4

type CompletedPart struct {
	PartNumber int
	ETag       string
	// Checksum is the digest the client says this part had. Checked against
	// what the part actually carried, for the same reason the ETag is: a
	// completion naming parts it did not upload must not assemble them.
	Checksum string
}

CompletedPart represents a completed part for completing multipart upload.

type ConditionalDeleter added in v0.13.0

type ConditionalDeleter interface {
	DeleteObjectIf(ctx context.Context, bucket, key string, cond Conditions) error
}

ConditionalDeleter is the optional capability of deleting an object only if it still matches a condition. Backends implement it by evaluating cond under the same lock that serializes writes to the key, so the check and the delete are atomic; a backend that cannot do that must not implement it, and the S3 layer rejects conditional deletes against it rather than racing.

DeleteObjectIf returns ErrObjectNotFound when the object is absent (deletion is idempotent: the caller reports that as success) and ErrPreconditionFailed when the object is present but cond does not hold.

type ConditionalVersionDeleter added in v0.13.1

type ConditionalVersionDeleter interface {
	// DeleteObjectVersionIf performs DeleteObjectVersion only while cond holds
	// against the version it would act on: the current one, or the one
	// versionID names.
	//
	// It reports ErrPreconditionFailed when the target exists and cond does not
	// hold, and ErrObjectNotFound when there is nothing to delete — which the
	// S3 layer reports as success, a delete being idempotent.
	DeleteObjectVersionIf(
		ctx context.Context, bucket, key, versionID string, cond Conditions,
	) (DeleteResult, error)
}

ConditionalVersionDeleter is the optional capability of deleting on a versioned bucket only if the target still matches a condition. It is to Versioner what ConditionalDeleter is to DeleteObject, and exists for the same reason: the check and the delete must be atomic, so only a backend that can evaluate cond under the lock serializing writes to the key may implement it.

Without it a conditional delete against a versioned bucket has no correct answer available to the S3 layer. Evaluating the condition in the handler and then deleting would race a concurrent write — precisely the guarantee an If-Match delete is asked for — so the layer reports NotImplemented rather than answering as though the condition had been checked.

type Conditions added in v0.13.0

type Conditions struct {
	// IfMatch and IfNoneMatch are the raw header values: "*" or a
	// comma-separated entity-tag list.
	IfMatch     string
	IfNoneMatch string
	// Size, when set, requires the object to be exactly this many bytes
	// (x-amz-if-match-size).
	Size *int64
	// LastModified, when set, requires the object's modification time to match
	// to the second (x-amz-if-match-last-modified-time).
	LastModified *time.Time
}

Conditions carries the conditional headers a mutating request may specify. The zero value imposes no condition.

Backends MUST evaluate them while holding the lock that serializes writes to the key, so the evaluation is atomic with the mutation. Evaluating the condition in a separate step before the write (check-then-act) races: several concurrent If-None-Match: * writers can all observe "absent" and all succeed.

func (Conditions) CheckDelete added in v0.13.0

func (c Conditions) CheckDelete(state ObjectState) error

CheckDelete evaluates the conditions for a delete against state.

Deletion is idempotent: a condition against a key that is already gone is not a failure, so an absent object always passes. A present object that does not satisfy a condition yields ErrPreconditionFailed.

func (Conditions) CheckWrite added in v0.13.0

func (c Conditions) CheckWrite(state ObjectState) error

CheckWrite evaluates the conditions for a write (PUT, multipart completion) against state. It returns:

  • ErrObjectNotFound when If-Match is set and the object is absent. S3 reports a conditional write against a missing key as 404 NoSuchKey, not as a failed precondition.
  • ErrPreconditionFailed when the object is present and a condition does not hold.
  • nil when the write may proceed.

func (Conditions) IsZero added in v0.13.0

func (c Conditions) IsZero() bool

IsZero reports whether no condition is set.

type CreateMultipartUploadRequest added in v0.4.0

type CreateMultipartUploadRequest struct {
	Bucket   string
	Key      string
	Metadata ObjectMetadata
	Tags     []Tag
	ACL      ACL
	// ServerSideEncryption asks for the completed object to be encrypted at
	// rest, and carries the algorithm ("AES256"). It is settled when the
	// upload starts, not when it completes, because the parts are already on
	// disk by then and would have been staged in the clear.
	ServerSideEncryption string
	// Owner is the principal starting the upload; it owns the completed object.
	Owner Owner
	// ChecksumAlgorithm names the client-visible checksum every part of this
	// upload carries, and ChecksumType whether the completed object's digest is
	// a digest of the part digests (COMPOSITE) or of the whole body
	// (FULL_OBJECT).
	//
	// Settled when the upload starts rather than at completion, for the same
	// reason encryption is: the parts are digested as they arrive, so what to
	// digest them with has to be known before the first one does.
	ChecksumAlgorithm string
	ChecksumType      string
}

CreateMultipartUploadRequest represents a request to start a multipart upload. Metadata and tags are applied to the object at completion.

type CustomerKey added in v0.14.0

type CustomerKey []byte

CustomerKey is an SSE-C key: the 256-bit key a client sends with every request on an object it encrypts with its own key. The server uses it for the duration of the request and never stores it.

It travels on the request's context rather than in each request type, because reads take no request struct: the S3 layer attaches it with WithCustomerKey, and a storage backend that supports SSE-C reads it with CustomerKeyFrom on every write, upload part and read of the object. A backend that does not must refuse a write carrying one with ErrUnsupportedOperation, never store the object in the clear.

func CustomerKeyFrom added in v0.14.0

func CustomerKeyFrom(ctx context.Context) CustomerKey

CustomerKeyFrom returns the customer key ctx carries, or nil.

type DeleteResult added in v0.13.0

type DeleteResult struct {
	// VersionID is the delete marker's own version id, or the id of the
	// version that was removed. Empty on an unversioned bucket.
	VersionID string
	// DeleteMarker reports that the delete inserted a marker rather than
	// removing bytes.
	DeleteMarker bool
}

DeleteResult describes what a delete did, which S3 reports in headers a client uses to tell "the key is gone" from "the key now has a tombstone".

type GetObjectResponse

type GetObjectResponse struct {
	Reader       io.ReadCloser
	Size         int64
	LastModified time.Time
	ETag         string
	Metadata     ObjectMetadata
	// VersionID names the version served, empty on a bucket that is not
	// versioned.
	VersionID string
	// TagCount is how many tags the object carries, reported on GET and HEAD
	// as x-amz-tagging-count. Backends fill it from metadata they already read;
	// zero means untagged (the header is then omitted).
	TagCount int

	// ServerSideEncryption names the algorithm the object is encrypted with at
	// rest, echoed to the client as x-amz-server-side-encryption. Empty for an
	// object stored in the clear. Size is always the plaintext size, so a
	// client never learns the on-disk size.
	ServerSideEncryption string

	// ChecksumAlgorithm and Checksum carry the client-visible checksum stored
	// with the object, reported only when the request asks for it. ChecksumType
	// distinguishes a multipart COMPOSITE value — a digest of the part digests
	// — from a FULL_OBJECT one.
	ChecksumAlgorithm string
	Checksum          string
	ChecksumType      string
}

GetObjectResponse represents the response for GetObject operation.

type LifecycleRule added in v0.13.0

type LifecycleRule struct {
	// ID names the rule; S3 generates one when the client does not supply it.
	ID string
	// Status is LifecycleEnabled or LifecycleDisabled.
	Status string
	// Prefix restricts the rule to keys beneath it; empty covers the bucket.
	Prefix string
	// ExpirationDays deletes a matching object this many days after its last
	// modification. Zero means the rule expires nothing by age.
	ExpirationDays int
	// ExpirationDate deletes every matching object once this instant passes,
	// whenever they were written. Zero means the rule expires nothing by date.
	ExpirationDate time.Time
	// AbortIncompleteMultipartUploadDays aborts a matching multipart upload
	// this many days after it was initiated. Zero means the rule aborts none.
	AbortIncompleteMultipartUploadDays int
}

LifecycleRule is one rule of a bucket's lifecycle configuration, restricted to the subset this server enforces: expire objects under a prefix after N days, and abort multipart uploads left unfinished for N days.

The subset is deliberate and the S3 layer refuses anything outside it rather than storing it. A rule the server keeps but never acts on tells a client its objects expire when they do not, and a client that believes data is being deleted is the one failure mode worth refusing outright.

func (LifecycleRule) Enabled added in v0.13.0

func (r LifecycleRule) Enabled() bool

Enabled reports whether the rule applies.

func (LifecycleRule) Matches added in v0.13.0

func (r LifecycleRule) Matches(key string) bool

Matches reports whether the rule covers key.

type ListObjectVersionsRequest added in v0.13.0

type ListObjectVersionsRequest struct {
	Bucket    string
	Prefix    string
	Delimiter string
	// KeyMarker and VersionIDMarker are the exclusive lower bound: listing
	// resumes after that version of that key.
	KeyMarker       string
	VersionIDMarker string
	Limit           int
}

ListObjectVersionsRequest describes one page of a version listing. It mirrors ListObjectsRequest, with the version-aware cursor S3 uses: a key marker and, within that key, a version marker.

type ListObjectVersionsResponse added in v0.13.0

type ListObjectVersionsResponse struct {
	Versions       []ObjectVersion
	CommonPrefixes []string
	IsTruncated    bool
	// NextKeyMarker and NextVersionIDMarker are where the next page resumes.
	NextKeyMarker       string
	NextVersionIDMarker string
}

ListObjectVersionsResponse is one page of a version listing, newest version first within each key.

type ListObjectsRequest added in v0.13.0

type ListObjectsRequest struct {
	Bucket string
	// Prefix restricts the listing; empty lists the bucket.
	Prefix string
	// Delimiter folds every key sharing a prefix up to its first occurrence
	// into a single common prefix. Empty returns keys unfolded.
	Delimiter string
	// StartAfter is an exclusive lower bound in the folded order: only entries
	// sorting strictly after it are returned. It may name a common prefix, in
	// which case every key under that prefix is already accounted for.
	StartAfter string
	// Limit caps the page, counting objects and common prefixes together the
	// way S3 counts max-keys. Zero or negative asks for everything, which only
	// callers that know the answer is small should do — an emptiness check, a
	// test fixture. The S3 listing path always sets it.
	Limit int
}

ListObjectsRequest describes one page of a bucket listing.

Listing is paged and delimiter-folded at this seam because a bucket is unbounded: at the design target of 100M objects per node, returning a whole bucket is not a slow answer but an impossible one, and the S3 layer above only ever renders 1000 entries at a time regardless.

The delimiter belongs here rather than above for the same reason. Folding collapses a whole keyspace into one entry, so a caller that folded after paging would have to keep asking for more keys until enough of them collapsed — several requests per page, over a backend that may walk the bucket for each. A backend folds in the pass it was already making, and one with an index can seek past a folded prefix instead of reading it.

func (*ListObjectsRequest) FoldPage added in v0.13.0

func (r *ListObjectsRequest) FoldPage(objects []Object) *ListObjectsResponse

FoldPage turns a bucket's matching objects into one page: folds them by the request's delimiter, orders them, applies StartAfter, and cuts at Limit.

It exists so that every backend folds and pages identically. The rules are subtle enough to get wrong in three places — common prefixes count toward the limit, a page exactly at the limit is truncated only if something follows, and a StartAfter naming a common prefix must skip every key beneath it — and backends outside this repository implement the same interface.

objects must already be filtered by Prefix; any order will do.

type ListObjectsResponse added in v0.13.0

type ListObjectsResponse struct {
	// Objects are the unfolded keys of this page, sorted ascending.
	Objects []Object
	// CommonPrefixes are the folded ones, sorted ascending. Both lists are
	// interleaved by key for the purposes of Limit and NextStartAfter, then
	// reported separately because that is how S3 renders them.
	CommonPrefixes []string
	// IsTruncated reports that entries exist after the last one returned.
	IsTruncated bool
	// NextStartAfter is the last entry on this page — an object key or a
	// common prefix — and is what the next request passes as StartAfter.
	NextStartAfter string
}

ListObjectsResponse is one page of a bucket listing.

type MultipartUpload added in v0.0.4

type MultipartUpload struct {
	UploadID  string
	Bucket    string
	Key       string
	Initiated time.Time
	// ChecksumAlgorithm and ChecksumType echo what the upload settled on, so a
	// client that asked by one header and got the default of the other can see
	// both without waiting until completion to find out.
	ChecksumAlgorithm string
	ChecksumType      string
}

MultipartUpload represents an in-progress multipart upload.

type Object

type Object struct {
	Key          string
	Size         int64
	LastModified time.Time
	ETag         string
	// Owner is the principal that wrote the object; zero when unrecorded.
	Owner Owner
}

Object represents an S3 object.

type ObjectAttributer added in v0.13.0

type ObjectAttributer interface {
	ObjectAttributes(ctx context.Context, bucket, key string) (*ObjectAttributes, error)
}

ObjectAttributer is the optional capability of describing an object without opening it, including the part layout a completed multipart object was assembled from. It backs GetObjectAttributes and reading a single part with ?partNumber=N; a backend that does not retain the layout can still implement it by reporting Parts as nil, which reads as "written by a single PUT".

It returns ErrBucketNotFound / ErrObjectNotFound the way GetObject does.

type ObjectAttributes added in v0.13.0

type ObjectAttributes struct {
	ETag         string
	Size         int64
	LastModified time.Time
	// UploadID names the multipart upload this object was completed from, when
	// it was. It is what lets a retried CompleteMultipartUpload be recognized
	// as a retry rather than answered with NoSuchUpload; empty for a single
	// PUT.
	UploadID string
	// Parts is the completed part layout in ascending part-number order, or
	// nil when the object was written by a single PUT.
	Parts []ObjectPart
	// ChecksumAlgorithm, Checksum and ChecksumType are the object's
	// client-visible digest, as GetObjectAttributes reports it. For a
	// multipart object the digest is composed from the parts, so it is a
	// different number from any part's own.
	ChecksumAlgorithm string
	Checksum          string
	ChecksumType      string
}

ObjectAttributes describes an object without opening its body: what GetObjectAttributes reports, plus the part layout when the object was assembled from a multipart upload (nil for a single PUT).

func (*ObjectAttributes) PartChecksum added in v0.13.0

func (a *ObjectAttributes) PartChecksum(n int) string

PartChecksum is the digest part number n carried when it was uploaded, empty when the object has no per-part digests.

A ?partNumber read reports this rather than the object's, because the client is verifying the bytes it just received and those are the part's — the object's digest is of the part digests and describes none of them.

func (*ObjectAttributes) PartRange added in v0.13.0

func (a *ObjectAttributes) PartRange(n int) (offset, length int64, ok bool)

PartRange returns the byte range covered by part number n (1-based) and whether it exists. For an object with no recorded parts, part 1 is the whole object, which is what S3 reports for a single PUT.

func (*ObjectAttributes) PartsCount added in v0.13.0

func (a *ObjectAttributes) PartsCount() int

PartsCount reports how many parts the object was assembled from; zero when it was written by a single PUT.

type ObjectMetadata added in v0.4.0

type ObjectMetadata struct {
	ContentType        string
	CacheControl       string
	ContentDisposition string
	ContentEncoding    string
	// Expires is the raw Expires header value, stored and returned verbatim.
	// S3 keeps whatever the client sent rather than reformatting it, and a
	// client that round-trips the header expects its own bytes back.
	Expires string
	// UserMetadata holds x-amz-meta-* pairs, keyed by the lowercase name
	// without the prefix (e.g. "color" for x-amz-meta-color).
	UserMetadata map[string]string
}

ObjectMetadata holds the user-controlled metadata stored with an object: the standard HTTP representation headers plus x-amz-meta-* pairs.

func (ObjectMetadata) IsZero added in v0.4.0

func (m ObjectMetadata) IsZero() bool

IsZero reports whether no metadata field is set.

type ObjectPart added in v0.13.0

type ObjectPart struct {
	PartNumber int
	Size       int64
	ETag       string
	// Checksum is the digest this part carried when it was uploaded, kept so a
	// ranged read of one part can still report it — which is what a client
	// verifying a download part by part asks for.
	Checksum string
}

ObjectPart is one part of a *completed* multipart object, retained after the upload finishes so the object can still be read and described a part at a time (GetObjectAttributes, ?partNumber=N).

type ObjectState added in v0.13.0

type ObjectState struct {
	// Exists reports whether the object is present. The other fields are
	// meaningful only when it is true.
	Exists bool
	// ETag is the stored ETag, quoted or bare.
	ETag         string
	Size         int64
	LastModified time.Time
}

ObjectState is the current state of a key, as seen by a backend holding the lock that serializes writes to it. It is what conditional requests are evaluated against.

type ObjectVersion added in v0.13.0

type ObjectVersion struct {
	Key       string
	VersionID string
	// IsLatest reports that this is the key's current version.
	IsLatest bool
	// DeleteMarker reports that this entry records a deletion, not content.
	DeleteMarker bool
	Size         int64
	ETag         string
	LastModified time.Time
	Owner        Owner
}

ObjectVersion is one entry of a version listing: a stored version, or a delete marker recording that the key was deleted at that point.

type Owner added in v0.10.0

type Owner struct {
	// ID is the canonical user ID.
	ID string
	// DisplayName is the human-readable owner name.
	DisplayName string
}

Owner identifies the S3 principal that owns a bucket or object. It is recorded when the object is written and reported in ACL and listing responses; clients compare it to decide what a caller owns, so it must not change when a different credential reads the object.

func (Owner) IsZero added in v0.10.0

func (o Owner) IsZero() bool

IsZero reports whether no owner was recorded (objects written before owners were modeled, or by an unauthenticated server).

type Part added in v0.0.4

type Part struct {
	PartNumber   int
	ETag         string
	Size         int64
	LastModified time.Time
	// Checksum is the part's own client-visible digest, base64, empty when the
	// upload asked for none. It is the part's alone: the completed object's is
	// composed from these rather than taken over the assembled body.
	Checksum string
	// ChecksumAlgorithm names what Checksum was computed with — the upload's
	// algorithm, not the request's. A part inherits it from the upload, so a
	// caller that named nothing on this request still gets a digest and needs
	// to be told which one it is.
	ChecksumAlgorithm string
}

Part represents a part of a multipart upload.

type PublicAccessBlock added in v0.13.0

type PublicAccessBlock struct {
	BlockPublicACLs       bool
	IgnorePublicACLs      bool
	BlockPublicPolicy     bool
	RestrictPublicBuckets bool
}

PublicAccessBlock is a bucket's public-access-block configuration: four independent switches over the ways a bucket can become publicly readable. Absent (a nil *PublicAccessBlock) means no configuration, which S3 reports as NoSuchPublicAccessBlockConfiguration rather than as all-false.

type PutObjectRequest

type PutObjectRequest struct {
	Reader   io.Reader
	Bucket   string
	Key      string
	Size     int64
	Metadata ObjectMetadata
	Tags     []Tag
	// ACL is the canned access-control level for the object (default
	// ACLPrivate). Governs anonymous access only.
	ACL ACL
	// Owner is the principal writing the object, recorded with it and reported
	// in ACL and listing responses. Zero leaves the object unowned.
	Owner Owner

	// IfNoneMatch and IfMatch carry the raw conditional-write header values
	// (e.g. "*" or a quoted ETag list). When set, the storage backend must
	// evaluate them atomically with the write — see PreconditionFailed — so
	// concurrent conditional PUTs resolve to a single winner. Empty means no
	// condition.
	IfNoneMatch string
	IfMatch     string

	// ContentMD5 is the hex-encoded MD5 the client claims the body has
	// (decoded from the base64 Content-MD5 header). When set, the backend must
	// compare it against what it actually received and refuse the write with
	// ErrBadDigest before the object becomes visible — verifying afterwards
	// would leave corrupt content readable in the window between.
	ContentMD5 string

	// ChecksumAlgorithm names the client-visible checksum to compute over the
	// body ("SHA256", "CRC32", ...). Empty computes none.
	//
	// This is a second checksum, distinct from ContentMD5 and from the ETag:
	// the client chose it, sent it, and expects it back unchanged.
	ChecksumAlgorithm string
	// Checksum is the base64 digest the client claims the body has. When set,
	// the backend must compare it against what it actually received and refuse
	// the write with ErrBadDigest before the object becomes visible.
	Checksum string

	// ServerSideEncryption asks for the object to be encrypted at rest, and
	// carries the algorithm ("AES256"). Empty stores the body as-is.
	//
	// The decision is made above the backend, because it is the bucket's
	// default and the request's header that settle it, and a backend must not
	// have to know about either. A backend that cannot encrypt refuses a
	// non-empty value with ErrUnsupportedOperation rather than storing
	// plaintext — silently ignoring it would report an object as encrypted
	// when it is not.
	ServerSideEncryption string
}

func (*PutObjectRequest) Conditions added in v0.13.0

func (r *PutObjectRequest) Conditions() Conditions

Conditions returns the conditional-write headers carried by the request.

func (*PutObjectRequest) PreconditionFailed deprecated added in v0.4.0

func (r *PutObjectRequest) PreconditionFailed(exists bool, currentETag string) bool

PreconditionFailed reports whether the request's If-None-Match / If-Match conditions fail against the current object state, where exists reports whether the target object is present and currentETag is its ETag (quoted or bare; only meaningful when exists is true).

Deprecated: use Conditions().CheckWrite, which distinguishes a failed precondition from a conditional write against a missing key — S3 reports the latter as 404 NoSuchKey, not 412. Kept for backends outside this repository.

type PutObjectResponse added in v0.4.0

type PutObjectResponse struct {
	ETag string
	// ChecksumAlgorithm and Checksum echo the client-visible checksum stored
	// with the object.
	ChecksumAlgorithm string
	Checksum          string
	// ServerSideEncryption echoes the algorithm the object was encrypted
	// with, empty when it was stored in the clear.
	ServerSideEncryption string
	// VersionID names the version this write created, empty on a bucket that
	// is not versioned.
	VersionID string
}

PutObjectResponse reports the stored object's ETag.

type Storage

type Storage interface {
	ListBuckets(ctx context.Context) ([]Bucket, error)
	CreateBucket(ctx context.Context, bucket string) error
	DeleteBucket(ctx context.Context, bucket string) error
	BucketExists(ctx context.Context, bucket string) (bool, error)
	// ListObjects returns one page of a bucket's objects, sorted by key.
	ListObjects(ctx context.Context, req *ListObjectsRequest) (*ListObjectsResponse, error)
	PutObject(ctx context.Context, req *PutObjectRequest) (*PutObjectResponse, error)
	GetObject(ctx context.Context, bucket, key string) (*GetObjectResponse, error)
	DeleteObject(ctx context.Context, bucket, key string) error

	// GetObjectTagging returns the object's tag set (empty when untagged).
	GetObjectTagging(ctx context.Context, bucket, key string) ([]Tag, error)
	// PutObjectTagging replaces the object's tag set.
	PutObjectTagging(ctx context.Context, bucket, key string, tags []Tag) error
	// DeleteObjectTagging removes the object's tag set.
	DeleteObjectTagging(ctx context.Context, bucket, key string) error

	// SetBucketACL records the bucket's canned ACL.
	SetBucketACL(ctx context.Context, bucket string, acl ACL) error
	// BucketACL returns the bucket's canned ACL (ACLPrivate default);
	// ErrBucketNotFound when the bucket is absent.
	BucketACL(ctx context.Context, bucket string) (ACL, error)
	// ObjectACL returns the object's canned ACL (ACLPrivate default);
	// ErrBucketNotFound/ErrObjectNotFound when absent.
	ObjectACL(ctx context.Context, bucket, key string) (ACL, error)
	// SetObjectACL records the object's canned ACL, leaving its content and
	// other metadata untouched; ErrBucketNotFound/ErrObjectNotFound when absent.
	SetObjectACL(ctx context.Context, bucket, key string, acl ACL) error
	// ObjectOwner returns the principal recorded when the object was written
	// (zero when unrecorded); ErrBucketNotFound/ErrObjectNotFound when absent.
	ObjectOwner(ctx context.Context, bucket, key string) (Owner, error)

	CreateMultipartUpload(ctx context.Context, req *CreateMultipartUploadRequest) (*MultipartUpload, error)
	UploadPart(ctx context.Context, req *UploadPartRequest) (*Part, error)
	// ListParts returns the parts uploaded so far for an in-progress multipart
	// upload, sorted by ascending part number.
	ListParts(ctx context.Context, bucket, key, uploadID string) ([]Part, error)
	// ListMultipartUploads returns the in-progress multipart uploads for a
	// bucket, sorted by object key (then upload ID for equal keys).
	ListMultipartUploads(ctx context.Context, bucket string) ([]MultipartUpload, error)
	CompleteMultipartUpload(ctx context.Context, req *CompleteMultipartUploadRequest) (*CompleteMultipartUploadResponse, error)
	AbortMultipartUpload(ctx context.Context, bucket, key, uploadID string) error
}

Storage defines the interface for S3-compatible storage operations.

type Tag added in v0.4.0

type Tag struct {
	Key   string
	Value string
}

Tag is a single object tag.

type UploadPartRequest added in v0.0.4

type UploadPartRequest struct {
	Bucket     string
	Key        string
	UploadID   string
	PartNumber int
	Reader     io.Reader
	Size       int64
	// ChecksumAlgorithm and Checksum are as on PutObjectRequest: what to
	// compute over this part, and what the client claims it will be. A claim
	// that does not match is BadDigest and the part is not stored.
	ChecksumAlgorithm string
	Checksum          string
}

UploadPartRequest represents a request to upload a part.

type Versioner added in v0.13.0

type Versioner interface {
	// SetBucketVersioning records the bucket's versioning state. Moving to
	// VersioningUnset is not possible: S3 has no way back to never-versioned.
	SetBucketVersioning(ctx context.Context, bucket string, state VersioningState) error
	// BucketVersioning returns the bucket's state, VersioningUnset when it has
	// never been configured; ErrBucketNotFound when the bucket is absent.
	BucketVersioning(ctx context.Context, bucket string) (VersioningState, error)
	// GetObjectVersion serves exactly the named version, whatever the current
	// one is. ErrObjectNotFound when that version does not exist — including
	// when it is a delete marker, which has no content to serve.
	GetObjectVersion(ctx context.Context, bucket, key, versionID string) (*GetObjectResponse, error)
	// ListObjectVersions returns one page of a bucket's versions and delete
	// markers, newest first within each key.
	ListObjectVersions(ctx context.Context, req *ListObjectVersionsRequest) (*ListObjectVersionsResponse, error)
	// DeleteObjectVersion performs a delete that is aware of versions, and is
	// the only delete a versioned bucket should take.
	//
	// With an empty versionID it inserts a delete marker and reports its id:
	// the key stops resolving, and every version written before it is still
	// there. With a versionID it permanently removes exactly that version,
	// which is the only way bytes actually leave a versioned bucket.
	//
	// On a bucket that is not versioned it deletes outright and reports a zero
	// DeleteResult, so a caller does not have to ask about bucket state first.
	DeleteObjectVersion(ctx context.Context, bucket, key, versionID string) (DeleteResult, error)
}

Versioner is the optional capability of keeping more than one version of a key. A backend that does not implement it reports NotImplemented for PutBucketVersioning and behaves exactly as it does today.

The interface grows as the feature does; today it carries the bucket state only, which is what decides whether any of the rest applies.

type VersioningState added in v0.13.0

type VersioningState string

VersioningState is a bucket's versioning setting. The zero value means the bucket was never versioned, which is a third state and not a synonym for Suspended: a never-versioned bucket reports no status at all, and its objects have no version IDs until the first enable adopts them as "null".

A bucket moves unversioned -> Enabled -> Suspended -> Enabled -> ... and can never go back to unversioned; that is S3's model, and it is what lets the read path assume that a bucket with any versioning history keeps its versions forever.

const (
	// VersioningUnset is a bucket that has never had versioning configured.
	VersioningUnset VersioningState = ""
	// VersioningEnabled makes every write create a new version.
	VersioningEnabled VersioningState = "Enabled"
	// VersioningSuspended sends writes to the "null" version while retaining
	// the versions written while it was enabled.
	VersioningSuspended VersioningState = "Suspended"
)

The versioning states a bucket can be in.

Directories

Path Synopsis
Package auth provides credential storage and a small grant-based authorization model for the S3 server.
Package auth provides credential storage and a small grant-based authorization model for the S3 server.
cmd
fs command
Package cors provides per-bucket CORS configuration for the S3 server: which cross-origin requests are allowed and what preflight responses to return.
Package cors provides per-bucket CORS configuration for the S3 server: which cross-origin requests are allowed and what preflight responses to return.
Package engine is the storage engine: fs.Storage over the cluster's replicated metadata tables and content-addressed blocks.
Package engine is the storage engine: fs.Storage over the cluster's replicated metadata tables and content-addressed blocks.
internal
adminhandler
Package adminhandler implements the go-faster/fs admin API: instance info and runtime access-key management, backed by an auth.Manager.
Package adminhandler implements the go-faster/fs admin API: instance info and runtime access-key management, backed by an auth.Manager.
checksum
Package checksum implements the client-visible checksums S3 exposes as x-amz-checksum-*.
Package checksum implements the client-visible checksums S3 exposes as x-amz-checksum-*.
cluster/block
Package block stores object data as content-addressed blocks.
Package block stores object data as content-addressed blocks.
cluster/layout
Package layout assigns the cluster's partitions to nodes.
Package layout assigns the cluster's partitions to nodes.
cluster/meta
Package meta defines the rows of the cluster's metadata tables and how replicas merge them.
Package meta defines the rows of the cluster's metadata tables and how replicas merge them.
cluster/peer
Package peer is how cluster nodes find each other and agree on the layout.
Package peer is how cluster nodes find each other and agree on the layout.
cluster/table
Package table is the cluster's replicated metadata: tables of rows that every replica can merge without coordination.
Package table is the cluster's replicated metadata: tables of rows that every replica can merge without coordination.
lastrun
Package lastrun records when a periodic background pass last completed, so the pass survives restarts without either re-running on every one of them or being postponed forever by them.
Package lastrun records when a periodic background pass last completed, so the pass survives restarts without either re-running on every one of them or being postponed forever by them.
lifecycle
Package lifecycle enforces bucket lifecycle rules: it deletes objects that have expired and aborts multipart uploads that were abandoned.
Package lifecycle enforces bucket lifecycle rules: it deletes objects that have expired and aborts multipart uploads that were abandoned.
reqid
Package reqid mints the S3 request ID — the value a client reads back from x-amz-request-id and from the RequestId of every S3 error body — so a failing client's report finds the matching log line.
Package reqid mints the S3 request ID — the value a client reads back from x-amz-request-id and from the RequestId of every S3 error body — so a failing client's report finds the matching log line.
s3err
Package s3err renders S3-compatible error responses.
Package s3err renders S3-compatible error responses.
sigv4
Package sigv4 verifies AWS Signature Version 4 on incoming S3 requests: Authorization-header auth, presigned-URL (query) auth, and the seed signature for streaming (aws-chunked) uploads.
Package sigv4 verifies AWS Signature Version 4 on incoming S3 requests: Authorization-header auth, presigned-URL (query) auth, and the seed signature for streaming (aws-chunked) uploads.
sse
Package sse implements the chunked AEAD stream that backs SSE-S3: server-side encryption with a server-managed key.
Package sse implements the chunked AEAD stream that backs SSE-S3: server-side encryption with a server-managed key.
scripts
chaos command
Command chaos runs a soak test of a cluster: real fs processes under a mixed workload while nodes are killed, frozen and moved in and out of the layout, checking after every round that the cluster lost no acknowledged write, served no torn object and brought nothing deleted back.
Command chaos runs a soak test of a cluster: real fs processes under a mixed workload while nodes are killed, frozen and moved in and out of the layout, checking after every round that the cluster lost no acknowledged write, served no torn object and brought nothing deleted back.
gencompat command
Command gencompat generates docs/CONFORMANCE.md from the ceph/s3-tests known-failures list, grouping the remaining gaps by feature area.
Command gencompat generates docs/CONFORMANCE.md from the ceph/s3-tests known-failures list, grouping the remaining gaps by feature area.
Package server provides an embeddable S3-compatible HTTP server.
Package server provides an embeddable S3-compatible HTTP server.
Package storagemem implements fs.Storage using in-memory storage.
Package storagemem implements fs.Storage using in-memory storage.
Package storagetest provides a conformance test suite for fs.Storage implementations.
Package storagetest provides a conformance test suite for fs.Storage implementations.

Jump to

Keyboard shortcuts

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