Trove

Go Packages

Complete reference of all Trove Go packages, types, and functions.

Core Package

Import: github.com/xraph/trove

Trove

Root handle for all object storage operations.

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

Constructor

func Open(drv driver.Driver, opts ...Option) (*Trove, error)

Object Operations

func (t *Trove) Put(ctx context.Context, bucket, key string, r io.Reader, opts ...driver.PutOption) (*driver.ObjectInfo, error)
func (t *Trove) Get(ctx context.Context, bucket, key string, opts ...driver.GetOption) (*driver.ObjectReader, error)
func (t *Trove) Delete(ctx context.Context, bucket, key string, opts ...driver.DeleteOption) error
func (t *Trove) Head(ctx context.Context, bucket, key string) (*driver.ObjectInfo, error)
func (t *Trove) List(ctx context.Context, bucket string, opts ...driver.ListOption) (*driver.ObjectIterator, error)
func (t *Trove) Copy(ctx context.Context, srcBucket, srcKey, dstBucket, dstKey string, opts ...driver.CopyOption) (*driver.ObjectInfo, error)

Bucket Operations

func (t *Trove) CreateBucket(ctx context.Context, name string, opts ...driver.BucketOption) error
func (t *Trove) DeleteBucket(ctx context.Context, name string) error
func (t *Trove) ListBuckets(ctx context.Context) ([]driver.BucketInfo, error)

Accessors

func (t *Trove) Backend(name string) (*Trove, error)
func (t *Trove) Driver() driver.Driver
func (t *Trove) Config() Config
func (t *Trove) Pool() *stream.Pool
func (t *Trove) Stream() *stream.Pool
func (t *Trove) Resolver() *middleware.Resolver
func (t *Trove) CAS() *cas.CAS
func (t *Trove) VFS() *vfs.FS

Lifecycle and Middleware

func (t *Trove) UseMiddleware(mw ...middleware.Middleware)
func (t *Trove) RemoveMiddleware(name string)
func (t *Trove) Health(ctx context.Context) error
func (t *Trove) Close(ctx context.Context) error

Config

type Config struct {
    DefaultBucket    string
    ChunkSize        int64
    PoolSize         int
    ChecksumAlgorithm ChecksumAlgorithm
    StreamBufferSize int
    Retry            RetryPolicy
}

ChecksumAlgorithm

type ChecksumAlgorithm int

const (
    SHA256 ChecksumAlgorithm = iota
    Blake3
    XXHash
)

RetryPolicy

type RetryPolicy struct {
    Strategy    RetryStrategy // None, Fixed, Exponential
    MaxAttempts int
    BaseDelay   time.Duration
    MaxDelay    time.Duration
}

Option Functions

FunctionDescription
WithDefaultBucket(name string)Set the default bucket for operations that omit a bucket name
WithChunkSize(size int64)Set the chunk size for streaming uploads
WithPoolSize(n int)Set the maximum number of concurrent streams
WithChecksumAlgorithm(alg ChecksumAlgorithm)Set the hash algorithm for integrity checks
WithStreamBufferSize(size int)Set the internal buffer size for stream channels
WithRetry(policy RetryPolicy)Configure retry behavior for transient failures
WithBackend(name string, drv driver.Driver)Register a named backend for multi-driver routing
WithRoute(pattern, backend string)Route a bucket/key pattern to a named backend
WithRouteFunc(fn func(bucket, key string) string)Dynamic routing function
WithPoolConfig(cfg stream.PoolConfig)Full pool configuration
WithVFS(bucket string)Enable the virtual filesystem layer on a bucket
WithMiddleware(mw ...middleware.Middleware)Attach read/write middleware globally
WithReadMiddleware(mw ...middleware.ReadMiddleware)Attach read-only middleware
WithWriteMiddleware(mw ...middleware.WriteMiddleware)Attach write-only middleware
WithScopedMiddleware(scope middleware.Scope, mw middleware.Middleware)Attach middleware with a scope filter
WithMiddlewareAt(priority int, mw middleware.Middleware)Attach middleware at a specific priority
WithCAS(opts ...cas.Option)Enable the content-addressable storage layer

Sentinel Errors

var (
    ErrNotFound         = errors.New("trove: not found")
    ErrBucketNotFound   = errors.New("trove: bucket not found")
    ErrBucketExists     = errors.New("trove: bucket already exists")
    ErrObjectNotFound   = errors.New("trove: object not found")
    ErrKeyEmpty         = errors.New("trove: key is required")
    ErrBucketEmpty      = errors.New("trove: bucket name is required")
    ErrDriverClosed     = errors.New("trove: driver is closed")
    ErrNilDriver        = errors.New("trove: driver is required")
    ErrInvalidDSN       = errors.New("trove: invalid DSN")
    ErrChecksumMismatch = errors.New("trove: checksum mismatch")
    ErrQuotaExceeded    = errors.New("trove: quota exceeded")
    ErrContentBlocked   = errors.New("trove: content blocked")
    ErrStreamClosed     = errors.New("trove: stream is closed")
    ErrUploadExpired    = errors.New("trove: upload session expired")
    ErrBackendNotFound  = errors.New("trove: backend not found")
    ErrPoolClosed       = errors.New("trove: stream pool is closed")
    ErrStreamNotActive  = errors.New("trove: stream is not active")
    ErrMaxStreamsReached = errors.New("trove: maximum concurrent streams reached")
)

Driver Package

Import: github.com/xraph/trove/driver

Driver Interface

The core contract every storage backend must implement.

type Driver interface {
    Name() string
    Open(ctx context.Context, dsn string, opts ...Option) error
    Close(ctx context.Context) error
    Ping(ctx context.Context) error

    Put(ctx context.Context, bucket, key string, r io.Reader, opts ...PutOption) (*ObjectInfo, error)
    Get(ctx context.Context, bucket, key string, opts ...GetOption) (*ObjectReader, error)
    Delete(ctx context.Context, bucket, key string, opts ...DeleteOption) error
    Head(ctx context.Context, bucket, key string) (*ObjectInfo, error)
    List(ctx context.Context, bucket string, opts ...ListOption) (*ObjectIterator, error)
    Copy(ctx context.Context, srcBucket, srcKey, dstBucket, dstKey string, opts ...CopyOption) (*ObjectInfo, error)

    CreateBucket(ctx context.Context, name string, opts ...BucketOption) error
    DeleteBucket(ctx context.Context, name string) error
    ListBuckets(ctx context.Context) ([]BucketInfo, error)
}

Core Types

TypeDescription
ObjectInfoMetadata for a stored object (key, size, content type, ETag, last modified, custom metadata)
ObjectReaderWraps io.ReadCloser with ObjectInfo attached
BucketInfoBucket name, creation time, and region
ObjectIteratorPaginated iterator over object listings with Next(), Value(), Err(), Close()

Capability Interfaces

Drivers optionally implement these for advanced features.

InterfaceMethods
MultipartDriverInitMultipart, UploadPart, CompletePart, AbortMultipart
PresignDriverPresignGet, PresignPut
VersioningDriverListVersions, GetVersion, DeleteVersion
NotificationDriverSubscribe, Unsubscribe
LifecycleDriverSetLifecycleRules, GetLifecycleRules
RangeDriverGetRange (byte-range reads)
ServerCopyDriverServerCopy (server-side copy without download)

Supporting Types

TypeDescription
PartInfoPart number, ETag, and size for multipart uploads
VersionInfoVersion ID, timestamp, and IsLatest flag
ObjectEventEvent payload for notifications
ObjectEventTypeConstants: EventPut, EventDelete, EventCopy
LifecycleRuleExpiration, transition, and filter configuration
ObjectRefLightweight bucket + key reference

Option Types

Each operation accepts functional options that populate a config struct.

Option TypeConfig StructKey Fields
PutOptionPutConfigContentType, Metadata, CacheControl, ContentEncoding
GetOptionGetConfigVersionID, Range
DeleteOptionDeleteConfigVersionID
ListOptionListConfigPrefix, Delimiter, MaxKeys, Cursor
CopyOptionCopyConfigMetadata, ContentType
BucketOptionBucketConfigRegion, Tags

Driver Implementations

PackageImportBackendCapabilities
localdrivergithub.com/xraph/trove/drivers/localdriverLocal filesystemCore
memdrivergithub.com/xraph/trove/drivers/memdriverIn-memoryCore
s3drivergithub.com/xraph/trove/drivers/s3driverAWS S3 / MinIOCore, Multipart, Presign, Range
gcsdrivergithub.com/xraph/trove/drivers/gcsdriverGoogle Cloud StorageCore, Multipart, Presign, Range
azuredrivergithub.com/xraph/trove/drivers/azuredriverAzure Blob StorageCore, Multipart, Presign, Range
sftpdrivergithub.com/xraph/trove/drivers/sftpdriverSFTPCore

All drivers share the same constructor pattern:

drv := s3driver.New()
err := drv.Open(ctx, "s3://access:secret@us-east-1/my-bucket?endpoint=...")

Middleware Package

Import: github.com/xraph/trove/middleware

Direction

type Direction int

const (
    DirectionRead      Direction = iota // read path only
    DirectionWrite                      // write path only
    DirectionReadWrite                  // both paths
)

Middleware Interfaces

type Middleware interface {
    Name() string
    Direction() Direction
    ProcessRead(ctx context.Context, bucket, key string, r io.Reader) (io.Reader, error)
    ProcessWrite(ctx context.Context, bucket, key string, r io.Reader) (io.Reader, error)
}

type ReadMiddleware interface {
    Name() string
    ProcessRead(ctx context.Context, bucket, key string, r io.Reader) (io.Reader, error)
}

type WriteMiddleware interface {
    Name() string
    ProcessWrite(ctx context.Context, bucket, key string, r io.Reader) (io.Reader, error)
}

Registration

type Registration struct {
    Middleware Middleware
    Priority   int
    Scope      Scope
}

Scope

Scopes control which operations a middleware applies to.

ConstructorDescription
ScopeGlobal()Matches all operations
ScopeBucket(names ...string)Matches specific buckets
ScopeKeyPattern(pattern string)Matches keys by glob pattern
ScopeContentType(types ...string)Matches by MIME content type
ScopeFunc(fn func(bucket, key string) bool)Custom predicate
ScopeAnd(scopes ...Scope)Logical AND of scopes
ScopeOr(scopes ...Scope)Logical OR of scopes
ScopeNot(scope Scope)Logical NOT of a scope

Resolver

type Resolver struct { /* ... */ }
func (r *Resolver) Add(reg Registration)
func (r *Resolver) Remove(name string)
func (r *Resolver) Resolve(direction Direction, bucket, key, contentType string) []Middleware

Middleware Implementations

encrypt

Import: github.com/xraph/trove/middleware/encrypt

AES-256-GCM encryption middleware.

TypeDescription
EncryptMiddleware that encrypts on write, decrypts on read
KeyProviderInterface for supplying encryption keys
StaticKeyProviderFixed-key implementation of KeyProvider

compress

Import: github.com/xraph/trove/middleware/compress

Zstd compression middleware.

TypeDescription
CompressMiddleware that compresses on write, decompresses on read
OptionFunctional option type
WithMinSize(bytes int64)Skip compression for objects smaller than threshold
WithExclude(patterns ...string)Skip compression for matching content types

dedup

Import: github.com/xraph/trove/middleware/dedup

Content-hash deduplication middleware.

TypeDescription
DedupMiddleware that detects and eliminates duplicate content
StoreInterface for the dedup index backend
MemoryStoreIn-memory implementation of Store

scan

Import: github.com/xraph/trove/middleware/scan

Content scanning middleware (antivirus / malware detection).

TypeDescription
ScanWrite middleware that scans content before storage
ProviderInterface for scan backends (e.g., ClamAV)
ResultScan outcome: clean, infected, or error
OnDetectFuncCallback invoked when a threat is detected

watermark

Import: github.com/xraph/trove/middleware/watermark

Invisible watermark injection for images.

TypeDescription
WatermarkRead middleware that injects invisible watermarks into PNG/JPEG
TextFuncfunc(bucket, key string) string -- generates watermark text per object

Stream Package

Import: github.com/xraph/trove/stream

Pool

type Pool struct { /* ... */ }
func NewPool(cfg PoolConfig) *Pool
func (p *Pool) Open(ctx context.Context, bucket, key string, dir Direction, opts ...StreamOption) (*Stream, error)
func (p *Pool) Metrics() PoolMetrics
func (p *Pool) Close() error

PoolConfig

type PoolConfig struct {
    MaxStreams      int
    ChunkSize      int64
    BufferSize     int
    IdleTimeout    time.Duration
}

PoolMetrics

type PoolMetrics struct {
    ActiveStreams   int
    TotalOpened    int64
    TotalClosed    int64
    BytesUploaded  int64
    BytesDownloaded int64
}

Stream

type Stream struct { /* ... */ }
func (s *Stream) Write(data []byte) (int, error)
func (s *Stream) Read(buf []byte) (int, error)
func (s *Stream) Pause() error
func (s *Stream) Resume() error
func (s *Stream) Cancel() error
func (s *Stream) Complete() error
func (s *Stream) State() State
func (s *Stream) ID() id.ID

Direction

type Direction int

const (
    Upload   Direction = iota
    Download
    BiDi
)

State

type State int

const (
    Idle       State = iota
    Active
    Paused
    Completing
    Completed
    Failed
    Cancelled
)

Chunk Types

type Chunk struct {
    Index    int
    Data     []byte
    Checksum string
}

type ChunkAck struct {
    Index int
    OK    bool
    Err   error
}

type ChunkPool struct { /* ... */ }
func (cp *ChunkPool) Get() *Chunk
func (cp *ChunkPool) Put(c *Chunk)
func (cp *ChunkPool) Stats() ChunkPoolStats

type ChunkPoolStats struct {
    Gets    int64
    Puts    int64
    Misses  int64
}

Backpressure Modes

type Backpressure int

const (
    Block    Backpressure = iota // block the writer until the reader catches up
    Drop                        // drop chunks when the buffer is full
    Buffer                      // buffer chunks in memory without limit
    Adaptive                    // switch between block and buffer based on memory pressure
)

Hooks

type ProgressHook func(bytesSent, totalBytes int64)
type ChunkHook    func(chunk Chunk)
type CompleteHook func(info driver.ObjectInfo)
type ErrorHook    func(err error)

Stream Options

FunctionDescription
WithChunkSize(size int64)Override the pool default chunk size
WithResumable(enabled bool)Enable resumable uploads
WithPool(pool *Pool)Use a specific pool instance
WithChannelSize(size int)Set the internal channel buffer
WithBackpressure(mode Backpressure)Set the backpressure strategy
WithOnProgress(hook ProgressHook)Register a progress callback
WithOnChunk(hook ChunkHook)Register a per-chunk callback
WithOnComplete(hook CompleteHook)Register a completion callback
WithOnError(hook ErrorHook)Register an error callback

CAS Package

Import: github.com/xraph/trove/cas

Content-addressable storage layer built on top of Trove.

CAS

type CAS struct { /* ... */ }
func (c *CAS) Store(ctx context.Context, r io.Reader) (hash string, err error)
func (c *CAS) Retrieve(ctx context.Context, hash string) (io.ReadCloser, error)
func (c *CAS) Exists(ctx context.Context, hash string) (bool, error)
func (c *CAS) Pin(ctx context.Context, hash string) error
func (c *CAS) Unpin(ctx context.Context, hash string) error
func (c *CAS) GC(ctx context.Context) (*GCResult, error)

HashAlgorithm

type HashAlgorithm int

const (
    AlgSHA256 HashAlgorithm = iota
    AlgBlake3
    AlgXXHash
)

GCResult

type GCResult struct {
    Removed   int
    Reclaimed int64 // bytes freed
}

Index Interface

type Index interface {
    AddRef(ctx context.Context, hash string) error
    RemoveRef(ctx context.Context, hash string) error
    RefCount(ctx context.Context, hash string) (int, error)
    IsPinned(ctx context.Context, hash string) (bool, error)
}

CAS Options

FunctionDescription
WithAlgorithm(alg HashAlgorithm)Set the hash algorithm
WithIndex(idx Index)Provide a custom reference-counting index
WithBucket(name string)Set the bucket used for CAS storage

VFS Package

Import: github.com/xraph/trove/vfs

Virtual filesystem layer that presents Trove objects as a file tree compatible with io/fs.

FS

type FS struct { /* ... */ }
func New(store *trove.Trove, bucket string) *FS

func (f *FS) Stat(name string) (FileInfo, error)
func (f *FS) ReadDir(name string) ([]DirEntry, error)
func (f *FS) Walk(root string, fn WalkFunc) error
func (f *FS) Open(name string) (io.ReadCloser, error)
func (f *FS) Create(name string, r io.Reader) error
func (f *FS) Mkdir(name string) error
func (f *FS) Remove(name string) error
func (f *FS) RemoveAll(name string) error
func (f *FS) Rename(oldName, newName string) error
func (f *FS) SetMetadata(name string, meta map[string]string) error
func (f *FS) GetMetadata(name string) (map[string]string, error)

Types

TypeDescription
FileInfoImplements fs.FileInfo -- name, size, mode, mod time, is-dir
DirEntryImplements fs.DirEntry -- name, is-dir, type, info
WalkFuncfunc(path string, info FileInfo, err error) error

ID Package

Import: github.com/xraph/trove/id

TypeID-based identifiers with prefixes for every Trove resource.

Prefix Constants

ConstantPrefixExample
PrefixObjectobj_obj_2bNx8rK4wMQp0
PrefixBucketbkt_bkt_7mHj3nL9xRqYs
PrefixUploadSessionupl_upl_4kWv6tP1zNcFd
PrefixDownloadSessiondwn_dwn_9aGx5sJ2yBhTm
PrefixStreamstr_str_1cLw8qR6vEpXn
PrefixPoolpol_pol_3fMy7uT0wDkZr
PrefixVersionver_ver_6jNx2pK5xAeSt
PrefixChunkchk_chk_8hBv4rL3zCoWm

ID Type

type ID struct { /* ... */ }
func New(prefix string) ID
func Parse(s string) (ID, error)
func (id ID) String() string
func (id ID) Prefix() string
func (id ID) IsZero() bool

Test Package

Import: github.com/xraph/trove/trovetest

Conformance test suite and testing utilities.

// RunDriverSuite runs the full conformance suite against a driver implementation.
func RunDriverSuite(t *testing.T, drv driver.Driver)

Helpers

FunctionDescription
TestObject(key, content string)Create a test object with the given key and body
RandomData(size int)Generate random byte content
AssertObjectEquals(t, expected, actual *driver.ObjectInfo)Assert two object infos are equal
ReadAll(r *driver.ObjectReader) ([]byte, error)Read an entire object reader into bytes

MockDriver

type MockDriver struct {
    PutFunc    func(ctx context.Context, bucket, key string, r io.Reader, opts ...driver.PutOption) (*driver.ObjectInfo, error)
    GetFunc    func(ctx context.Context, bucket, key string, opts ...driver.GetOption) (*driver.ObjectReader, error)
    DeleteFunc func(ctx context.Context, bucket, key string, opts ...driver.DeleteOption) error
    // ... all Driver interface methods
}

Extension Package

Import: github.com/xraph/trove/extension

Forge extension that integrates Trove into the Forge application framework with HTTP handlers, database-backed metadata, and lifecycle management.

Constructor

func New(opts ...ExtOption) forge.Extension

Config

type Config struct {
    BasePath        string
    DisableRoutes   bool
    DisableMigrate  bool
}

ExtOption Functions

FunctionDescription
WithBasePath(path string)Set the URL base path for HTTP routes (default: /storage)
WithConfig(cfg Config)Provide a full configuration struct
WithDisableRoutes(disabled bool)Disable automatic HTTP route registration
WithDisableMigrate(disabled bool)Disable automatic database migration
WithGroveDatabase(name string)Set the Grove database name for metadata storage

On this page