r2

package
v0.2.711 Latest Latest
Warning

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

Go to latest
Published: Oct 17, 2026 License: MIT Imports: 23 Imported by: 0 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.

Documentation

Overview

Package r2 holds cfctl's R2 helpers that don't depend on Cobra: object listing over the REST API, operation classes and pricing, cost estimates, size formatting, and the S3-compatible client used for multipart uploads and sync.

Index

Constants

View Source
const (
	Standard         = "Standard"
	InfrequentAccess = "InfrequentAccess"
)

Storage classes as R2 names them.

View Source
const (
	ClassA    = "A"
	ClassB    = "B"
	ClassFree = "free"
)

Operation classes.

View Source
const DefaultPartSize int64 = 16 << 20

DefaultPartSize is 16 MiB.

View Source
const GB = 1e9

GB is a decimal gigabyte, the unit R2 bills in.

View Source
const MinPartSize int64 = 5 << 20

MinPartSize is S3's minimum for every part but the last.

View Source
const PricingSource = "developers.cloudflare.com/r2/pricing, checked 2026-10-03"

PricingSource is shown next to cost estimates.

View Source
const S3EndpointEnv = "CFCTL_R2_S3_ENDPOINT"

S3EndpointEnv overrides the S3 endpoint (tests, or a custom gateway).

Variables

View Source
var Prices = map[string]Price{
	Standard: {
		StorageGBMonth:   0.015,
		ClassAPerMillion: 4.50,
		ClassBPerMillion: 0.36,
		FreeStorageGB:    10,
		FreeClassA:       1_000_000,
		FreeClassB:       10_000_000,
	},
	InfrequentAccess: {
		StorageGBMonth:   0.01,
		ClassAPerMillion: 9.00,
		ClassBPerMillion: 0.90,
		RetrievalPerGB:   0.01,
	},
}

Prices is the R2 price table.

source: developers.cloudflare.com/r2/pricing, checked 2026-10-03. Egress is free. Billable units are rounded up (partial GB-months and partial millions of requests bill as a whole unit). DeleteObject, DeleteBucket and AbortMultipartUpload are free. The free tier applies to Standard storage only; Infrequent Access has none.

Functions

func BucketPath

func BucketPath(acct, bucket string, segs ...string) string

BucketPath is /accounts/{acct}/r2/buckets/{bucket} plus optional suffix segments (each path-escaped).

func DeleteKeys

func DeleteKeys(ctx context.Context, c *s3.Client, bucket string, keys []string) ([]string, error)

DeleteKeys deletes keys with S3 DeleteObjects (1000 per request) and returns the keys that failed.

func DownloadFile

func DownloadFile(ctx context.Context, c *s3.Client, bucket, key, path string) (int64, error)

DownloadFile writes bucket/key to path (via a temp file, renamed into place).

func Excluded

func Excluded(rel string, globs []string) bool

Excluded reports whether rel matches any glob (matched against the full relative path and against the base name).

func Ext

func Ext(key string) string

Ext returns a key's extension for grouping ("(none)" when there isn't one).

func FileMD5

func FileMD5(p string) (string, error)

FileMD5 returns a file's hex MD5 (the ETag of a single-part upload).

func HumanBytes

func HumanBytes(n float64) string

HumanBytes formats a byte count with decimal units (R2 bills in GB).

func HumanCount

func HumanCount(n float64) string

HumanCount formats a count with thousands separators.

func IsNotFound

func IsNotFound(err error) bool

IsNotFound reports whether an S3 error is a 404.

func IsReadOnly

func IsReadOnly(err error) bool

IsReadOnly reports whether err (possibly wrapped by the AWS SDK) is the read-only guard's refusal.

func JurisdictionHeader

func JurisdictionHeader(j string) http.Header

JurisdictionHeader returns the cf-r2-jurisdiction header for j, or nil.

func NewS3

func NewS3(acct, jurisdiction string, creds TempCredentials) *s3.Client

NewS3 builds an S3 client for R2. It uses cfctl's shared HTTP client, so the read-only guard (only GET/HEAD/OPTIONS go out) and --debug logging apply.

func ObjectPath

func ObjectPath(acct, bucket, key string) string

ObjectPath is the REST path of one object. The key is escaped as a single segment (slashes become %2F), as the API expects.

func OpClass

func OpClass(action string) string

OpClass returns ClassA, ClassB, or ClassFree for an R2 action type (GraphQL r2OperationsAdaptiveGroups dimensions.actionType).

Class A: PutObject, CopyObject, multipart (create/upload part/complete, list uploads/parts), List*, PutBucket*, LifecycleStorageTierTransition. Free: DeleteObject, DeleteBucket, AbortMultipartUpload. Everything else (GetObject, HeadObject, HeadBucket, Get*, ...) is Class B.

func PrefixAt

func PrefixAt(key, base string, depth int) string

PrefixAt groups key by the first `depth` path segments below base ("a/b/" for key "base/a/b/c.png", depth 2). Objects with fewer directory levels group under their own directory plus " (files)"; objects directly under base group as "(files)".

func RESTStorageClass

func RESTStorageClass(c string) string

RESTStorageClass maps a storage class to the REST API's name (the cf-r2-storage-class header and bucket storageClass): Standard or InfrequentAccess.

func S3Endpoint

func S3Endpoint(acct, jurisdiction string) string

S3Endpoint returns the account's R2 S3 endpoint for a jurisdiction.

func S3StorageClass

func S3StorageClass(c string) string

S3StorageClass maps a storage class to the S3 API's name: R2's S3 API takes x-amz-storage-class STANDARD or STANDARD_IA, while the REST API (cf-r2-storage-class) takes Standard or InfrequentAccess.

func SortedKeys

func SortedKeys[V any](m map[string]V) []string

SortedKeys returns a map's keys sorted.

func UploadFile

func UploadFile(ctx context.Context, c *s3.Client, bucket, key, path string, o PutOptions, mo MultipartOptions) error

UploadFile uploads a local file to bucket/key: one PutObject for files up to the part size, a multipart upload above it. A failed multipart upload is aborted.

func WriteFileAtomic

func WriteFileAtomic(path string, r io.Reader) (int64, error)

WriteFileAtomic streams r into path via a temp file in the same directory.

Types

type Cost

type Cost struct {
	Storage, ClassA, ClassB, Retrieval, Total float64
}

Cost is a cost estimate for one storage class.

func Estimate

func Estimate(class string, u Usage) Cost

Estimate prices one month of usage for a storage class. Partial units round up: 10.2 GB over the free tier bills as 11 GB-months, 1 request over the free tier bills as a full million.

type ListOptions

type ListOptions struct {
	Prefix    string
	Delimiter string // "/" for a folder view; "" lists recursively
	PerPage   int    // ≤0 → 1000 (the maximum)
	// Limit stops after this many objects (≤0 → no limit).
	Limit int
	// MaxPages bounds the loop (≤0 → api.DefaultMaxPages).
	MaxPages int
	// Jurisdiction sets cf-r2-jurisdiction ("" or "default" → none).
	Jurisdiction string
}

ListOptions selects objects to list.

type ListResult

type ListResult struct {
	Objects []Object `json:"objects"`
	// Prefixes are the common prefixes ("folders") when Delimiter is set.
	Prefixes  []string `json:"prefixes,omitempty"`
	Pages     int      `json:"-"`
	Truncated bool     `json:"truncated,omitempty"`
}

ListResult is the outcome of List.

func List

func List(ctx context.Context, c *api.Client, acct, bucket string, o ListOptions, fn func(page []Object)) (*ListResult, error)

List lists objects through the REST API, following the cursor until the listing isn't truncated. fn, if set, is called with each page's objects (useful for progress); the objects are also accumulated unless fn returns false for "don't keep".

type LocalFile

type LocalFile struct {
	Rel  string // slash-separated path relative to the root
	Path string // OS path
	Size int64
}

LocalFile is one file under a sync source directory.

func WalkLocal

func WalkLocal(root string, excludes []string) ([]LocalFile, error)

WalkLocal lists regular files under root (symlinks to files are followed; directories named in excludes are skipped).

type MultipartOptions

type MultipartOptions struct {
	PartSize    int64 // bytes; ≥5 MiB
	Concurrency int
	// Progress is called after each part with the bytes uploaded so far.
	Progress func(done int64)
}

MultipartOptions tune multipart uploads.

type Object

type Object struct {
	Key            string            `json:"key"`
	ETag           string            `json:"etag,omitempty"`
	LastModified   string            `json:"last_modified,omitempty"`
	Size           int64             `json:"size"`
	HTTPMetadata   map[string]any    `json:"http_metadata,omitempty"`
	CustomMetadata map[string]string `json:"custom_metadata,omitempty"`
	StorageClass   string            `json:"storage_class,omitempty"`
}

Object is one R2 object as the REST API lists it.

func Stat

func Stat(ctx context.Context, c *api.Client, acct, bucket, key, jurisdiction string) (*Object, error)

Stat returns one object's listing entry (size, etag, metadata), or (nil, nil) if no object has exactly that key. The REST API has no HEAD; listing with prefix=key returns the key itself first when it exists.

type Price

type Price struct {
	// StorageGBMonth is USD per GB-month of stored data.
	StorageGBMonth float64
	// ClassAPerMillion / ClassBPerMillion are USD per million requests.
	ClassAPerMillion float64
	ClassBPerMillion float64
	// RetrievalPerGB is USD per GB read back (Infrequent Access only).
	RetrievalPerGB float64
	// Free tier (per account per month; Standard only).
	FreeStorageGB float64
	FreeClassA    float64
	FreeClassB    float64
}

Price is one storage class's price list.

type PutOptions

type PutOptions struct {
	ContentType        string
	CacheControl       string
	ContentDisposition string
	ContentEncoding    string
	ContentLanguage    string
	StorageClass       string
	Metadata           map[string]string
}

PutOptions are the object metadata for an upload.

type SyncItem

type SyncItem struct {
	Key    string `json:"key"`
	Path   string `json:"path"`
	Size   int64  `json:"size"`
	Reason string `json:"reason"` // "new" or "changed"
}

SyncItem is one transfer in a sync plan.

type SyncPlan

type SyncPlan struct {
	Transfers []SyncItem `json:"transfers"`
	// Deletes are remote keys (upload) or local paths (download) to remove.
	Deletes   []string `json:"deletes,omitempty"`
	Unchanged int      `json:"unchanged"`
	Bytes     int64    `json:"bytes"`
}

SyncPlan is what a sync would do.

func PlanDownload

func PlanDownload(remote []Object, local []LocalFile, prefix, root string, sizeOnly, deleteExtra bool, excludes []string) SyncPlan

PlanDownload compares remote objects under prefix with files under root. Keys ending in "/" (folder markers) are skipped.

func PlanUpload

func PlanUpload(local []LocalFile, remote []Object, prefix string, sizeOnly, deleteExtra bool, excludes []string) SyncPlan

PlanUpload compares local files with remote objects under prefix.

type TempCredentials

type TempCredentials struct {
	AccessKeyID     string `json:"accessKeyId"`
	SecretAccessKey string `json:"secretAccessKey"`
	SessionToken    string `json:"sessionToken"`
}

TempCredentials are short-lived S3 credentials from POST /accounts/{id}/r2/temp-access-credentials.

type Usage

type Usage struct {
	StorageBytes   float64 // average (or current) stored bytes over the month
	ClassA, ClassB float64 // request counts
	RetrievedBytes float64 // bytes read (billed for Infrequent Access)
}

Usage is one month's billable usage for one storage class.

Jump to

Keyboard shortcuts

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