base

package
v0.10.0 Latest Latest
Warning

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

Go to latest
Published: Nov 11, 2026 License: Apache-2.0 Imports: 21 Imported by: 3

Documentation

Overview

Package base provides a very low-level interface on top of the B2 API. It is not intended to be used directly.

Index

Constants

View Source
const (
	APIBase          = "https://api.backblazeb2.com"
	DefaultUserAgent = "blazer/0.10.0"
)

Variables

View Source
var ErrInvalidDuration = errors.New("b2: invalid duration")

ErrInvalidDuration reports a negative, sub-second or excessive key or download-authorization lifetime.

View Source
var ErrInvalidRangeResponse = errors.New("invalid range response")

ErrInvalidRangeResponse reports a response that does not satisfy a range request.

Functions

func Backoff

func Backoff(err error) time.Duration

Backoff returns an appropriate amount of time to wait, given an error, if any was returned by the server. If the return value is 0, but Action indicates Retry, the user should implement their own exponential backoff, beginning with one second.

func Code

func Code(err error) (int, string)

Code returns the error code and message.

func MaxRetries added in v0.8.0

func MaxRetries(err error) uint

MaxRetries returns an appropriate amount of retries, given a method and an error if any was returned by the server.

func MaxReuploads added in v0.8.0

func MaxReuploads(err error) uint

MaxReuploads returns an appropriate amount of retries for reuploading, given a method and an error if any was returned by the server.

func MsgCode added in v0.6.0

func MsgCode(err error) (int, string, string)

MsgCode returns the error code, msgCode and message.

Types

type AuthData added in v0.10.0

type AuthData struct {
	ApplicationKeyID    string
	AccountID           string
	AuthToken           string
	APIURL              string
	DownloadURL         string
	S3URL               string
	AbsMinPartSize      int
	RecommendedPartSize int
	AllowedBuckets      []string
	AllowedPrefix       string
	AllowedCapabilities []string
}

AuthData is the authorization state needed to resume a B2 session. It does not contain the application key used to obtain or refresh the session.

type AuthOption

type AuthOption func(*b2Options)

An AuthOption allows callers to choose per-session settings.

func ExpireSomeAuthTokens

func ExpireSomeAuthTokens() AuthOption

ExpireSomeAuthTokens requests intermittent authentication failures from the B2 service by sending B2's documented X-Bz-Test-Mode: expire_some_account_authorization_tokens header. It is for testing re-authentication paths only; do not use it in production.

func FailSomeUploads

func FailSomeUploads() AuthOption

FailSomeUploads requests intermittent upload failures from the B2 service by sending B2's documented X-Bz-Test-Mode: fail_some_uploads header. It is for testing retry and error-handling paths only; do not use it in production.

func ForceCapExceeded

func ForceCapExceeded() AuthOption

ForceCapExceeded requests a cap limit from the B2 service by sending B2's documented X-Bz-Test-Mode: force_cap_exceeded header. This causes all uploads to be treated as if they would exceed the configured B2 capacity. It is for testing only; do not use it in production.

func SetAPIBase added in v0.5.0

func SetAPIBase(url string) AuthOption

SetAPIBase returns an AuthOption that uses the given URL as the base for API requests.

func Transport

func Transport(rt http.RoundTripper) AuthOption

Transport returns an AuthOption that sets the underlying HTTP mechanism.

func UserAgent added in v0.2.0

func UserAgent(agent string) AuthOption

UserAgent sets the User-Agent HTTP header. The default header is "blazer/<version>"; the value set here will be prepended to that. This can be set multiple times.

type B2

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

B2 holds account information for Backblaze.

func AuthorizeAccount

func AuthorizeAccount(ctx context.Context, account, key string, opts ...AuthOption) (*B2, error)

AuthorizeAccount wraps b2_authorize_account.

func NewAuthorizedAccount added in v0.10.0

func NewAuthorizedAccount(data AuthData, opts ...AuthOption) *B2

NewAuthorizedAccount restores a session while applying this client's own transport, user agent, and other request options.

func (*B2) AuthData added in v0.10.0

func (b *B2) AuthData() AuthData

AuthData returns a detached snapshot of the current authorization state.

func (*B2) CreateBucket

func (b *B2) CreateBucket(ctx context.Context, name, btype string, info map[string]string, rules []LifecycleRule, sse *b2types.ServerSideEncryption, corsRules []b2types.CORSRule, fileLockEnabled bool, replicationConfiguration *b2types.ReplicationConfiguration) (*Bucket, error)

CreateBucket wraps b2_create_bucket. A nil sse leaves the bucket's default server-side encryption to the server.

func (*B2) CreateKey added in v0.5.0

func (b *B2) CreateKey(ctx context.Context, name string, caps []string, valid time.Duration, bucketID string, prefix string) (*Key, error)

CreateKey wraps v3 b2_create_key, producing a single-bucket key (or, with an empty bucketID, an unrestricted one) that v3-only clients can still use. A zero duration creates a non-expiring key; otherwise the lifetime must be at least one second and below 1000 days. Longer fractional durations truncate to whole seconds. Invalid lifetimes return ErrInvalidDuration before sending a request. For a Multi-Bucket Application Key, use CreateKeyMultiBucket.

func (*B2) CreateKeyMultiBucket added in v0.9.0

func (b *B2) CreateKeyMultiBucket(ctx context.Context, name string, caps []string, valid time.Duration, bucketIDs []string, prefix string) (*Key, error)

CreateKeyMultiBucket wraps v4 b2_create_key, producing a Multi-Bucket Application Key. A zero duration creates a non-expiring key; otherwise the lifetime must be at least one second and below 1000 days. Longer fractional durations truncate to whole seconds. Invalid lifetimes return ErrInvalidDuration before sending a request. Such keys are unusable by v3-only clients; for v3 compatibility, create one CreateKey per bucket instead.

func (*B2) ListBuckets

func (b *B2) ListBuckets(ctx context.Context, name string, bucketTypes ...string) ([]*Bucket, error)

ListBuckets wraps b2_list_buckets. If name is non-empty, only that bucket will be returned if it exists; else nothing will be returned.

func (*B2) ListKeys added in v0.5.0

func (b *B2) ListKeys(ctx context.Context, max int, next string) ([]*Key, string, error)

ListKeys wraps b2_list_keys.

func (*B2) Update

func (b *B2) Update(n *B2)

Update replaces the B2 object with a new one, in-place.

type Bucket

type Bucket struct {
	Name           string
	Type           string
	Info           map[string]string
	LifecycleRules []LifecycleRule
	ID             string

	CORSRules        []b2types.CORSRule
	DefaultRetention *b2types.Retention
	// DefaultServerSideEncryption is the bucket's default encryption for new
	// files. It is nil when the key may not read it, and a nil value is left
	// out of Update so the server keeps whatever it has.
	DefaultServerSideEncryption *b2types.ServerSideEncryption
	FileLockEnabled             bool
	ReplicationConfiguration    *b2types.ReplicationConfiguration
	// ReplicationConfigurationUnreadable records a bucket response that withheld
	// replication settings. A partial merge requires readable existing settings;
	// a complete explicit replacement does not.
	ReplicationConfigurationUnreadable bool
	// contains filtered or unexported fields
}

Bucket holds B2 bucket details.

func (*Bucket) BaseURL

func (b *Bucket) BaseURL() string

BaseURL returns the base part of the download URLs.

func (*Bucket) CopyFile added in v0.9.0

func (b *Bucket) CopyFile(ctx context.Context, sourceFileID, name, destinationBucketID, byteRange, metadataDirective, contentType string, info map[string]string) (*File, error)

CopyFile wraps b2_copy_file. An empty destinationBucketID makes B2 put the copy in the source file's bucket. contentType and info are sent only for the REPLACE metadata directive.

func (*Bucket) CopyFileWithSSEC added in v0.10.0

func (b *Bucket) CopyFileWithSSEC(ctx context.Context, sourceFileID, name, destinationBucketID, byteRange, metadataDirective, contentType string, info map[string]string, sourceSSE, destinationSSE *b2types.ServerSideEncryption) (*File, error)

CopyFileWithSSEC wraps b2_copy_file and supplies independent source and destination SSE-C settings in the JSON request body.

func (*Bucket) DeleteBucket

func (b *Bucket) DeleteBucket(ctx context.Context) error

DeleteBucket wraps b2_delete_bucket.

func (*Bucket) DownloadFileByID added in v0.10.0

func (b *Bucket) DownloadFileByID(ctx context.Context, id string, offset, size int64, header bool) (*FileReader, error)

DownloadFileByID wraps b2_download_file_by_id.

func (*Bucket) DownloadFileByIDWithSSEC added in v0.10.0

func (b *Bucket) DownloadFileByIDWithSSEC(ctx context.Context, id string, offset, size int64, header bool, sse *b2types.ServerSideEncryption) (*FileReader, error)

DownloadFileByIDWithSSEC downloads the requested version with an optional customer-managed key on this request only.

func (*Bucket) DownloadFileByName

func (b *Bucket) DownloadFileByName(ctx context.Context, name string, offset, size int64, header bool) (*FileReader, error)

DownloadFileByName wraps b2_download_file_by_name.

func (*Bucket) DownloadFileByNameWithSSEC added in v0.10.0

func (b *Bucket) DownloadFileByNameWithSSEC(ctx context.Context, name string, offset, size int64, header bool, sse *b2types.ServerSideEncryption) (*FileReader, error)

DownloadFileByNameWithSSEC wraps b2_download_file_by_name and sends the customer-managed key on GET, HEAD and ranged requests.

func (*Bucket) File

func (b *Bucket) File(id, name string) *File

File returns a bare File struct, but with the appropriate id and b2 interfaces.

func (*Bucket) GetDownloadAuthorization

func (b *Bucket) GetDownloadAuthorization(ctx context.Context, prefix string, valid time.Duration, contentDisposition string) (string, error)

GetDownloadAuthorization wraps b2_get_download_authorization. Negative durations, positive durations below one second and lifetimes of 1000 days or more return ErrInvalidDuration before sending a request. Longer fractional durations truncate to whole seconds. The server requires a duration from one second to one week; zero is still sent for the server to reject.

func (*Bucket) GetFileInfoByName added in v0.9.0

func (b *Bucket) GetFileInfoByName(ctx context.Context, name string) (*FileInfo, error)

GetFileInfoByName returns metadata for the current visible file with name. A one-result b2_list_file_names request avoids downloading the file and returns no result for a hidden file or a name that only shares a prefix.

func (*Bucket) GetUploadURL

func (b *Bucket) GetUploadURL(ctx context.Context) (*URL, error)

GetUploadURL wraps b2_get_upload_url.

func (*Bucket) HideFile

func (b *Bucket) HideFile(ctx context.Context, name string) (*File, error)

HideFile wraps b2_hide_file.

func (*Bucket) ListFileNames

func (b *Bucket) ListFileNames(ctx context.Context, count int, continuation, prefix, delimiter string) ([]*File, string, error)

ListFileNames wraps b2_list_file_names.

func (*Bucket) ListFileVersions

func (b *Bucket) ListFileVersions(ctx context.Context, count int, startName, startID, prefix, delimiter string) ([]*File, string, string, error)

ListFileVersions wraps b2_list_file_versions.

func (*Bucket) ListUnfinishedLargeFiles added in v0.2.2

func (b *Bucket) ListUnfinishedLargeFiles(ctx context.Context, count int, continuation string) ([]*File, string, error)

ListUnfinishedLargeFiles wraps b2_list_unfinished_large_files.

func (*Bucket) NotificationRules added in v0.9.0

func (b *Bucket) NotificationRules(ctx context.Context) ([]b2types.EventNotificationRule, error)

NotificationRules wraps b2_get_bucket_notification_rules.

func (*Bucket) S3URL added in v0.7.0

func (b *Bucket) S3URL() string

S3URL returns the base URL for S3-compatible API calls.

func (*Bucket) SetNotificationRules added in v0.9.0

func (b *Bucket) SetNotificationRules(ctx context.Context, rules []b2types.EventNotificationRule) error

SetNotificationRules replaces a bucket's complete notification rule set. A nil or empty slice clears every rule. To add or modify one rule, read the existing set and preserve the other rules in the replacement. B2 ignores the server-managed IsSuspended and SuspensionReason fields on set. Suspended rules can only be deleted, not edited.

func (*Bucket) StartLargeFile

func (b *Bucket) StartLargeFile(ctx context.Context, name, contentType string, info map[string]string, lock ...FileLock) (*LargeFile, error)

StartLargeFile wraps b2_start_large_file. At most one FileLock may be given; it sets Object Lock retention and legal hold on the new file. Extra FileLock arguments return an error without sending a request.

func (*Bucket) StartLargeFileWithSSEC added in v0.10.0

func (b *Bucket) StartLargeFileWithSSEC(ctx context.Context, name, contentType string, info map[string]string, sse *b2types.ServerSideEncryption, lock ...FileLock) (*LargeFile, error)

StartLargeFileWithSSEC wraps b2_start_large_file and carries SSE-C settings in the JSON request body. Like StartLargeFile, it rejects extra FileLock arguments.

func (*Bucket) Update

func (b *Bucket) Update(ctx context.Context) (*Bucket, error)

Update wraps b2_update_bucket.

type ErrAction

type ErrAction int

ErrAction is an action that a caller can take when any function returns an error.

const (
	// ReAuthenticate indicates that the B2 account authentication tokens have
	// expired, and should be refreshed with a new call to AuthorizeAccount.
	ReAuthenticate ErrAction = iota

	// AttemptNewUpload indicates that an upload's authentication token (or URL
	// endpoint) has expired, and that users should request new ones with a call
	// to GetUploadURL or GetUploadPartURL.
	AttemptNewUpload

	// Retry indicates that the caller should wait an appropriate amount of time,
	// and then reattempt the RPC.
	Retry

	// Punt means that there is no useful action to be taken on this error, and
	// that it should be displayed to the user.
	Punt
)

func Action

func Action(err error) ErrAction

Action checks an error and returns a recommended course of action.

type File

type File struct {
	Name      string
	Size      int64
	Status    string
	Timestamp time.Time
	Info      *FileInfo
	ID        string
	// contains filtered or unexported fields
}

File represents a B2 file.

func (*File) AsLargeFile added in v0.7.0

func (f *File) AsLargeFile() *LargeFile

AsLargeFile return a LargeFile with the same fields as this File

func (*File) CompileParts

func (f *File) CompileParts(size int64, seen map[int]string) *LargeFile

CompileParts returns a LargeFile that can accept new data. Seen is a mapping of completed part numbers to SHA1 strings; size is the total size of all the completed parts to this point.

func (*File) DeleteFileVersion

func (f *File) DeleteFileVersion(ctx context.Context, bypassGovernance ...bool) error

DeleteFileVersion wraps b2_delete_file_version. Passing true requests a governance-retention bypass; it requires the bypassGovernance capability and does not bypass compliance retention. https://www.backblaze.com/apidocs/b2-delete-file-version https://www.backblaze.com/docs/cloud-storage-object-lock

func (*File) GetFileInfo

func (f *File) GetFileInfo(ctx context.Context) (*FileInfo, error)

GetFileInfo wraps b2_get_file_info.

func (*File) ListParts

func (f *File) ListParts(ctx context.Context, next, count int) ([]*FilePart, int, error)

ListParts wraps b2_list_parts.

func (*File) UpdateFileLegalHold added in v0.9.0

func (f *File) UpdateFileLegalHold(ctx context.Context, legalHold string) error

UpdateFileLegalHold wraps b2_update_file_legal_hold.

func (*File) UpdateFileRetention added in v0.9.0

func (f *File) UpdateFileRetention(ctx context.Context, retention *FileRetention, bypassGovernance bool) error

UpdateFileRetention wraps b2_update_file_retention. A nil retention removes the file's retention, which for governance mode requires bypassGovernance.

type FileChunk

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

FileChunk holds information necessary for uploading file chunks.

func (*FileChunk) Reload

func (fc *FileChunk) Reload(ctx context.Context) error

Reload reloads FileChunk in-place.

func (*FileChunk) UploadPart

func (fc *FileChunk) UploadPart(ctx context.Context, r io.Reader, sha1 string, size, index int) (int, error)

UploadPart wraps b2_upload_part.

func (*FileChunk) UploadPartWithSSEC added in v0.10.0

func (fc *FileChunk) UploadPartWithSSEC(ctx context.Context, r io.Reader, sha1 string, size, index int, sse *b2types.ServerSideEncryption) (int, error)

UploadPartWithSSEC wraps b2_upload_part and repeats the SSE-C headers selected by b2_start_large_file.

type FileInfo

type FileInfo struct {
	Name                 string
	SHA1                 string
	MD5                  string
	Size                 int64
	ContentType          string
	Info                 map[string]string
	Status               string
	Timestamp            time.Time
	Retention            *FileRetention
	LegalHold            string
	ServerSideEncryption *b2types.ServerSideEncryption
	EncryptionMode       string
	EncryptionAlgorithm  string
	SSECKeyMD5           string
}

FileInfo holds information about a specific file.

type FileLock added in v0.9.0

type FileLock struct {
	Retention *FileRetention
	LegalHold string // "on", "off" or "" for unset
}

FileLock holds the optional Object Lock settings of a file. The zero value sets neither.

type FilePart

type FilePart struct {
	Number int
	SHA1   string
	Size   int64
}

FilePart is a piece of a started, but not finished, large file upload.

type FileReader

type FileReader struct {
	io.ReadCloser
	// ContentLength is the response length, saturated at the platform's maximum
	// int. It does not limit the bytes returned by Read.
	ContentLength int
	ContentType   string
	SHA1          string
	ID            string
	Info          map[string]string
}

FileReader is an io.ReadCloser that downloads a file from B2.

type FileRetention added in v0.9.0

type FileRetention struct {
	Mode                 string
	RetainUntilTimestamp int64
}

FileRetention is per-file Object Lock retention: a mode ("governance" or "compliance") and a retain-until time in milliseconds since the Unix epoch.

type Key added in v0.5.0

type Key struct {
	ID           string
	Secret       string
	Name         string
	Capabilities []string
	// Expires is the application key's expiration date. A zero time.Time means
	// the key never expires; check that with IsZero, not Unix, which is
	// -62135596800 for the zero time.
	Expires   time.Time
	BucketIDs []string
	Prefix    string
	// contains filtered or unexported fields
}

Key is a B2 application key.

func (*Key) Delete added in v0.5.0

func (k *Key) Delete(ctx context.Context) error

Delete wraps b2_delete_key.

type LargeFile

type LargeFile struct {
	ID string
	// contains filtered or unexported fields
}

LargeFile holds information necessary to implement B2 large file support.

func (*LargeFile) CancelLargeFile

func (l *LargeFile) CancelLargeFile(ctx context.Context) error

CancelLargeFile wraps b2_cancel_large_file.

func (*LargeFile) CopyPart added in v0.10.0

func (l *LargeFile) CopyPart(ctx context.Context, sourceFileID string, partNumber int, byteRange string, _ *copyPartSSE) (*FilePart, error)

CopyPart copies a source file or byte range into a part of this large file.

func (*LargeFile) FinishLargeFile

func (l *LargeFile) FinishLargeFile(ctx context.Context) (*File, error)

FinishLargeFile wraps b2_finish_large_file.

func (*LargeFile) GetUploadPartURL

func (l *LargeFile) GetUploadPartURL(ctx context.Context) (*FileChunk, error)

GetUploadPartURL wraps b2_get_upload_part_url.

type LifecycleRule

type LifecycleRule struct {
	Prefix                 string
	DaysNewUntilHidden     int
	DaysHiddenUntilDeleted int
}

type URL

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

URL holds information from the b2_get_upload_url API.

func (*URL) Reload

func (url *URL) Reload(ctx context.Context) error

Reload reloads URL in-place, by reissuing a b2_get_upload_url and overwriting the previous values.

func (*URL) UploadFile

func (url *URL) UploadFile(ctx context.Context, r io.Reader, size int, name, contentType, sha1 string, info map[string]string, lock ...FileLock) (*File, error)

UploadFile wraps b2_upload_file. At most one FileLock may be given; it sets Object Lock retention and legal hold on the new file. Extra FileLock arguments return an error without sending a request.

func (*URL) UploadFileWithSSEC added in v0.10.0

func (url *URL) UploadFileWithSSEC(ctx context.Context, r io.Reader, size int, name, contentType, sha1 string, info map[string]string, sse *b2types.ServerSideEncryption, lock ...FileLock) (*File, error)

UploadFileWithSSEC wraps b2_upload_file and sends per-request server-side encryption settings. Callers normally use package b2 instead of this low-level method. Like UploadFile, it rejects extra FileLock arguments.

Jump to

Keyboard shortcuts

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