Data & infrastructure/Storage & Uploads

Storage & Uploads

Multi-disk storage, S3 streaming and presigned uploads, signed URLs, blob tracking, and image variants.

github.com/fletchhq/fletch/storage· fletch docs show storage

On this page

github.com/fletchhq/fletch/storage provides a driver-agnostic object storage interface (storage.Store), multi-disk routing, capability detection, signed download URLs, blob lifecycle tracking, and on-demand image variant caching.

For handling multipart file uploads in HTML forms, see Forms & Uploads. For attaching stored files to outgoing mail, see Emails & Mailers.

Core Stores & Multi-Disk Manager

Attach a single store with fletch.WithStorage(s), or configure multiple named disks with storage.NewManager and fletch.WithStorageManager(m):

local := storage.Disk("./storage/uploads")
mem := storage.Memory()

mgr := storage.NewManager("local", local)
mgr.Register("scratch", mem)

app := fletch.New(
	fletch.WithStorageManager(mgr),
)

storage.Disk(root) stores files on the local filesystem rooted at root. storage.Memory() holds objects in RAM for tests and ephemeral workspaces.

Key Safety

Every store validates object keys through storage.ValidateKey(key), which rejects path traversal (..), leading slashes, null bytes, and malformed paths before touching a disk or bucket. Call storage.ValidateKey(key) directly when accepting user-influenced keys at API boundaries.

Capabilities & Helper Functions

storage.Store keeps its core surface minimal. Backends opt into richer operations by implementing optional capability interfaces:

Interface Capability
Lister Prefix listing with pagination.
Copier Server-side object copy without downloading through the app server.
BatchDeleter Multi-key batch deletion.
RangeReader Byte-range reads for streaming media and resumable downloads.
OptionPutter Uploads with explicit content type, cache control, and custom metadata.
MetaStatter Reads object metadata, ETag, and content type without fetching the body.
UploadSigner Generates presigned PUT or multipart POST URLs for direct browser uploads.

Inspect what a configured store supports at runtime with storage.Capabilities(store) []string.

Package-level helpers use a store’s optional capability when present and fall back to portable implementations where possible:

  • storage.List, storage.StatMeta, storage.PutWithOptions, storage.OpenRange
  • storage.Copy, storage.Move, storage.DeleteMany, storage.DeletePrefix
  • storage.DetectContentType, storage.ETagFor, storage.ServeObject

storage.ServeObject streams an object over HTTP with content type, ETag, and range handling when the backing store implements RangeReader.

Signed Disks & Expiring Download URLs

Private objects stored on local disks should not be exposed through static file serving. Wrap any local store with storage.NewSignedDisk(inner, cfg) or issue signed HTTP routes with github.com/fletchhq/fletch/auth/signedurl:

signer, err := signedurl.New(signingSecret) // []byte, at least 32 bytes
if err != nil {
	return err
}

downloadURL, err := signer.Sign("/files/"+objectKey, 15*time.Minute)

Protect the download endpoint with signer.RequireSignature() middleware or check the request manually inside the handler with signer.Verify(r) before calling storage.ServeObject.

Amazon S3 (storage/s3)

github.com/fletchhq/fletch/storage/s3 implements storage.Store plus S3-native capabilities (Lister, Copier, BatchDeleter, RangeReader, OptionPutter, MetaStatter, and UploadSigner).

Authentication uses the standard AWS credential chain: environment variables, ECS/container credentials, EC2 IMDS, or explicit static credentials for local MinIO / S3-compatible services. Large uploads stream directly without buffering the full payload in memory, and server-side encryption supports SSE-KMS keys.

Direct Browser Uploads via UploadSigner

When a store implements storage.UploadSigner, mint presigned PUT or POST credentials so browsers upload directly to S3:

signer, ok := store.(storage.UploadSigner)
if ok {
	putReq, err := signer.PresignPut(ctx, key, storage.UploadSignOptions{
		ContentType: "application/pdf",
		MinSize:     size, // the client's declared byte size
		MaxSize:     size,
		Expires:     10 * time.Minute,
	})
	// putReq is a storage.PresignedUpload: URL, Method, Headers, Expires

	postReq, err := signer.PresignPost(ctx, key, storage.UploadSignOptions{
		ContentType: "image/png",
		MinSize:     1,
		MaxSize:     10 << 20,
		Expires:     10 * time.Minute,
	})
	// postReq is a storage.PresignedPost: URL, Fields, Expires
}

A presigned PUT signs Content-Length, so it can only enforce an exact size: set MinSize equal to MaxSize, or leave both zero for no size check. A size range returns an error; use PresignPost, whose policy carries a content-length-range condition, to accept anything between MinSize and MaxSize. UploadSignOptions also takes SSEKMSKeyID. Expires defaults to 15 minutes when zero. A store that cannot presign returns storage.ErrUnsupported.

Blob Tracking & Orphan Cleanup (storage/blob)

Direct uploads can leave orphaned objects in storage if a user uploads a file and abandons the form before saving. github.com/fletchhq/fletch/storage/blob tracks uploaded objects in SQL so unattached blobs are cleaned up automatically.

repo, err := blob.NewSQLRepository(db, blob.DialectSQLite) // or blob.DialectPostgres
if err != nil {
	return err
}
blobs, err := blob.NewService(mgr, repo) // mgr is the *storage.Manager from above
if err != nil {
	return err
}

// Record a pending blob and sign an upload of exactly ByteSize bytes:
upload, err := blobs.CreateDirectUpload(ctx, blob.DirectUploadRequest{
	Filename:    "report.pdf",
	ContentType: "application/pdf",
	ByteSize:    size,
})

// Register the Quiver worker that deletes expired unattached blobs:
blob.RegisterPurgeWorker(queue, blobs)

The target disk must implement storage.UploadSigner (storage.SignedDisk or storage/s3). blob.MigrationSQL(dialect) returns the DDL for the fletch_storage_blobs and fletch_storage_attachments tables. After the client uploads, call ConfirmDirectUpload, then AttachOne or AttachMany to tie the blob to a record. To expose the whole flow over HTTP, mount blobs.DirectUploadHandler(blob.DirectUploadHandlerOptions{...}).

RegisterPurgeWorker registers PurgeUnattachedJob on Quiver, sweeping blobs that were uploaded but never attached to a domain record within their grace window.

On-Demand Image Variants (storage/variants)

github.com/fletchhq/fletch/storage/variants caches resized or transformed derivatives alongside your storage backend without pre-generating every dimension on upload.

Use variants.New(...) to create a variant cache backed by a storage.Store, variants.ParseTransform to parse and validate requested transform parameters (width, height, format, quality), and variants.CacheKey to compute deterministic cache keys from the source object and transform specification.

CLI Reference

Inspect and manage objects across configured disks from the terminal:

fletch storage ls [prefix] [--disk <name>] [--json]
fletch storage stat <key> [--disk <name>] [--json]
fletch storage put <key> <local-file> [--disk <name>] [--json]
fletch storage get <key> [output-file] [--disk <name>] [--json]
fletch storage rm <key> [--disk <name>] [--json]
fletch storage sign <key> [--disk <name>] [--json]

Omitting --disk targets the manager’s default disk. Pass --json for machine-readable output in scripts and automation.