backend

package
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Nov 4, 2026 License: MIT Imports: 29 Imported by: ? 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.

README

对象存储 backend

Backend 提供 Put、Get、Stat、Delete、List,由 chunk.Store.Backend 注入。对象键是相对路径,List 按字符串前缀过滤,例如 chunks/a 能匹配 chunks/aa。命名空间仍由独立的 meta.Engine 保存。

实现 构造入口 适用范围
Memory NewMemory() 内存测试、临时存储,不提供重启恢复
Local NewLocal(root) 本地磁盘;支持 FD 读取、不可变文件硬链接导入
Afero NewAfero(fs, root, AferoOptions{...}) 调用方提供的 afero.Fs,可选有界本地对象读缓存
S3 NewS3(ctx, S3Config{...}) AWS S3 或支持条件写入的兼容对象存储
Prefix Prefix{Base: objects, Prefix: "instance"} 在同一 backend 上划分对象键空间

Afero 用法与边界

objects, err := backend.NewAfero(afero.NewMemMapFs(), "/objects")
if err != nil {
    return err
}
chunks := &chunk.Store{Backend: objects, Codec: codec.Raw{}}

将 afero.NewMemMapFs() 换成应用已有的 afero.Fs 即可复用其他文件系统。 export/afero 则是将 compactfs 导出为 afero.Fs,两个适配方向不同。

可通过 option 启用有容量上限的本地磁盘对象缓存,省略 option 默认关闭:

objects, err := backend.NewAfero(sourceFS, "/objects", backend.AferoOptions{
    CacheRoot:  "/data1/compactfs-afero-cache",
    CacheBytes: 1 << 30, // 1 GiB;目录与容量必须一起设置
})

已有 *cache.Cache 时可用 AferoOptions{Cache: objectCache} 注入并共享其容量预算, 与 CacheRoot/CacheBytes 互斥。缓存目录使用独立可信的本地目录,放在对象 root 外, 同一缓存目录由一个 cache.Cache 实例管理,多个 backend 共享同一个指针; 缓存 API 见 fs/cache。

  • Get 命中返回调用方拥有的缓存文件 reader;未命中时按流填充完整对象,内存使用有界。 缓存按容量淘汰,超过预算的对象直接读取源 Fs。填充失败不发布部分对象,读取回退源 Fs。

  • Put/删除在发布锁内先清除旧缓存,再修改源 Fs;清除失败则中止修改并返回错误。 已打开的缓存 reader 保持原对象内容,直至调用方关闭;缓存不代替文件与目录 Sync。

  • 每次构造实例使用独立缓存命名空间,避免不同 Fs 串数据及重启后误用旧值; 重开会重新填充,旧缓存文件仍计入容量并可淘汰,不提供跨实例热缓存复用。

  • 应用通常在 core.Config.Cache 配置共享编码缓存;Afero backend 的缓存用于独立使用 backend 的场景,需要时才启用,避免无必要的重复缓存。应用导出已有的 raw、编码、 解码缓存配置见 export/afero。

  • 写入先保存同目录临时文件,验证长度、同步并关闭后再 Rename,最后同步目录; 输入读取、Sync、Close、Rename 失败均向上传播,发布前失败保留旧对象并清理临时文件。

  • 底层必须支持文件原子 Rename、文件及目录 Sync。持久性以该 Fs 的实际保证为准; MemMapFs 的 Sync 是空操作,不提供磁盘持久化。不忽略不支持 Sync 的错误。

  • 同一 root 只使用一个 Afero 实例写入,调用方不得绕过它修改对象。该实例内的 PutImmutable 串行检查与发布;afero.Fs 没有通用的跨进程“不覆盖重命名”操作。

  • root 应为由应用管理的可信目录,键不能逃逸 root;不将有外部修改者的符号链接树 作为隔离边界。.compactfs-put- 开头的路径分量保留给临时文件,List 隐藏遗留临时文件。 root 使用底层 Fs 的平台路径格式,建议绝对路径;对象键始终使用相对 / 路径, 不使用 s3:// 等 URI,也不预先 URL 转义。

  • Put 返回前消费输入,不关闭调用方的 reader;Get 返回的 reader 由调用方关闭。 取消在复制/读取边界检查,底层 Fs 的阻塞调用仍受其自身取消能力约束。

  • 适配器不拥有或关闭传入的 Fs,也不将 afero.File 冒充 *os.File。

S3 用法与边界

objects, err := backend.NewS3(ctx, backend.S3Config{
    URL:    "s3://compactfs-data/volumes/example", // 或 Bucket + Prefix
    Region: "us-east-1",
    // 兼容服务可指定 Endpoint: "https://s3.example.com" 和 AddressingStyle: "path"。
    // 如需显式凭据:AccessKeyID: accessKey, SecretAccessKey: secretKey,
    // 临时凭据还可指定 SessionToken: token。
})
if err != nil {
    return err
}
chunks := &chunk.Store{Backend: objects, Codec: codec.Raw{}}

AccessKeyID(AK)与 SecretAccessKey(SK)必须配对,SessionToken 可选。 未显式指定凭据时使用 AWS 官方 SDK v2 的默认凭据链: 环境变量 AWS_ACCESS_KEY_ID、AWS_SECRET_ACCESS_KEY、可选 AWS_SESSION_TOKEN, 或共享配置、工作负载身份。显式 AK/SK 优先于默认凭据链;库调用也可注入 Credentials provider 和 HTTPClient,provider 与显式 AK/SK 不能同时配置。 Region 优先使用显式配置和 SDK 配置,均为空时使用 us-east-1。

  • URL 使用 s3://bucket/prefix,与单独提供的 Bucket/Prefix 必须一致; URL 中空格、中文等按 URI 编码,禁止 userinfo、查询参数和 fragment,凭据单独传入。 Prefix 与对象键直接传未转义的相对 / 路径,禁止反斜杠、绝对路径和越界 ..。
  • AddressingStyle 支持 auto(默认,SDK 选择)、path 和 virtual。 对 endpoint https://objects.example.com,path 格式为 https://objects.example.com/bucket/prefix/key,virtual 格式为 https://bucket.objects.example.com/prefix/key。显式 virtual 要求 DNS 名称的 bucket/endpoint, TLS 下 bucket 不含点;IP endpoint 选择 path。原有 UsePathStyle: true 仍可用, 与显式 virtual 冲突时直接报错。格式参见 S3 寻址。
  • bucket 必须预先存在;构造函数不创建 bucket,也不修改其策略。对象放入独立的 Prefix/ 命名空间,List 自动分页并返回去除该前缀的键,ETag 作为不透明标识。
  • PutImmutable 使用服务端 If-None-Match: *;412 映射为 ErrExists,409 冲突及 其他错误向上传播,交由 SDK 或 chunk 重试。条件写不支持时返回错误,绝不退回覆盖写。 语义依据 S3 条件写入。
  • 上传验证长度并发送服务端校验的 Content-MD5。可 seek 的输入直接复用;其他 reader 先以有界内存复制到 TempDir(默认系统临时目录),供签名和重试读取。 临时文件在请求及重试完成或失败后关闭、删除;不关闭调用方的输入。
  • 单对象使用原子的 PutObject,最大 5 GiB,不使用 multipart;通常 chunk 远小于此限制。 Get 返回流由调用方关闭,不提供本地 FD 或文件硬链接导入能力。
  • 访问需要对象的 GetObject、PutObject、DeleteObject 权限以及 bucket 的 ListBucket 权限; Stat/删除存在检查通过 HeadObject 完成。服务端加密等额外策略需配套授权。
  • 切换对象后端不迁移元数据或 raw 缓存。恢复仍需要对应的本地元数据数据库; 条件对象发布也不提供多个命名空间写进程之间的协调。

S3 自动化测试使用真实 SDK 连接本地 HTTP/TLS 测试服务,覆盖签名、校验、条件竞争、 分页、重试与取消;还验证命令组装、原始/压缩数据提交、禁用缓存后的重开读回和 quota。 这些测试未连接真实云端 bucket。

命令与配置

CLI 默认 --backend-type local(disk 为别名),--backend 支持本地根目录, 也可传入 s3://bucket/prefix 自动选择 S3。显式选择 S3 时可用 --backend-type s3 --s3-url s3://bucket/prefix,或原有 bucket/prefix 参数。 凭据支持 --s3-access-key-id、--s3-secret-access-key、--s3-session-token, 也可写入 TOML 或使用上述 SDK 凭据链;config show 的文本/JSON 输出均隐藏这些凭据。 Memory、调用方自定义的 Afero Fs 由嵌入应用注入,不作为 CLI 的持久存储选择。

compactfs mount --backend-type s3 --s3-bucket compactfs-data \
  --s3-region us-east-1 --s3-prefix files --sync-mode backend /mnt/compactfs

# 兼容服务:按服务配置 endpoint、region 和寻址方式
compactfs blk --backend-type s3 --s3-bucket compactfs-data \
  --s3-endpoint https://s3.example.com --s3-region us-east-1 \
  --s3-addressing-style path --s3-prefix blocks --sync-mode backend

compactfs mount --backend s3://compactfs-data/files \
  --s3-endpoint https://s3.example.com --s3-addressing-style path /mnt/compactfs

compactfs quota show --backend-type s3 --s3-bucket compactfs-data \
  --s3-region us-east-1 --s3-prefix files

mount 与 quota 使用 [storage] / [storage.s3];blk 使用 [block.storage] / [block.storage.s3]。参数覆盖对应的 TOML 值,例如:

[storage]
backend_type = "s3"
metadata = "/data/compactfs/metadata.db"
cache = "/data1/compactfs-cache"

[storage.s3]
url = "s3://compactfs-data/files" # 也可分别配置 bucket 和 prefix
region = "us-east-1"
# endpoint = "https://s3.example.com"
# addressing_style = "path" # auto/path/virtual;旧 path_style=true 仍可用
# access_key_id = "YOUR_ACCESS_KEY_ID"
# secret_access_key = "YOUR_SECRET_ACCESS_KEY"
# session_token = "YOUR_SESSION_TOKEN" # 仅临时凭据需要
# temp_dir = "/data1/compactfs-upload-tmp" # 目录需预先存在

[block.storage]
backend_type = "s3"
metadata = "/data/compactfs/blk-metadata.db"
cache = "/data1/compactfs-blk-cache"

[block.storage.s3]
bucket = "compactfs-data"
region = "us-east-1"
prefix = "blocks"

不同实例使用各自的前缀、元数据和 raw 缓存。指定 S3 时本地 backend 路径不生效, 元数据和缓存仍按原配置保存在本地。启用写回时默认 local fsync 只确认本地恢复; --sync-mode backend 或 compactfs sync 才等待上传与元数据引用提交。 更换 bucket、prefix 或 backend 类型不会自动迁移旧对象,恢复现有命名空间需继续指向原后端。

验证:CGO_ENABLED=0 GOWORK=off go test ./fs/backend ./fs/chunk;并发检查使用 CGO_ENABLED=1 GOWORK=off go test -race ./fs/backend ./fs/chunk。

Documentation

Overview

Package backend provides object storage for content-addressed chunks.

Index

Constants

This section is empty.

Variables

View Source
var ErrExists = errors.New("backend object already exists")

ErrExists means an immutable import found an already published object. Callers must inspect its stored representation rather than overwrite it.

View Source
var ErrNotFound = errors.New("backend object not found")
View Source
var ErrNotSupported = errors.New("backend file import not supported")

ErrNotSupported asks the caller to fall back to streaming Put. ImportFile must not publish an object when returning this error.

Functions

This section is empty.

Types

type Afero

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

Afero stores objects in a caller-owned filesystem. The filesystem must provide atomic file Rename and meaningful file/directory Sync for durable storage. Use one Afero instance per root: publication is serialized within this instance, since afero.Fs has no portable cross-process rename-without-replacement API. The caller must not modify this root through another writer.

func NewAfero

func NewAfero(fs afero.Fs, root string, options ...AferoOptions) (*Afero, error)

NewAfero creates an object root without taking ownership of fs. Afero does not expose host file descriptors or close the supplied filesystem. At most one AferoOptions value is accepted; omitting it disables the object read cache.

func (*Afero) Delete

func (b *Afero) Delete(ctx context.Context, key string) error

func (*Afero) Get

func (b *Afero) Get(ctx context.Context, key string) (io.ReadCloser, error)

func (*Afero) List

func (b *Afero) List(ctx context.Context, prefix string) ([]Object, error)

func (*Afero) Put

func (b *Afero) Put(ctx context.Context, key string, r io.Reader, size int64) error

func (*Afero) PutImmutable

func (b *Afero) PutImmutable(ctx context.Context, key string, r io.Reader, size int64) error

PutImmutable preserves an existing object, including concurrent publications through this same backend instance.

func (*Afero) Stat

func (b *Afero) Stat(ctx context.Context, key string) (Object, error)

type AferoOptions

type AferoOptions struct {
	// Cache uses an existing cache and its capacity budget. The caller retains
	// ownership; do not also set CacheRoot or CacheBytes.
	Cache *cache.Cache
	// CacheRoot and CacheBytes create a local disk cache, independently of the
	// supplied afero.Fs. Both are required together; CacheBytes must be positive.
	// Keep the cache outside the source object root.
	CacheRoot  string
	CacheBytes int64
}

AferoOptions configures an optional bounded, local-disk object read cache. Zero values disable caching. This cache never acknowledges pending writes.

type Backend

type Backend interface {
	Put(ctx context.Context, key string, r io.Reader, size int64) error
	Get(ctx context.Context, key string) (io.ReadCloser, error)
	Stat(ctx context.Context, key string) (Object, error)
	Delete(ctx context.Context, key string) error
	List(ctx context.Context, prefix string) ([]Object, error)
}

Backend is the storage contract shared by local and object-storage implementations. The namespace currently persists through its own meta.Engine. Put consumes its reader before returning; it must not retain caller buffers. Get returns a reader owned and closed by the caller. List uses lexical key prefixes, not directory names.

type FileImporter

type FileImporter interface {
	ImportFile(ctx context.Context, key string, source *os.File, size int64) error
}

FileImporter optionally commits a complete immutable local file without copying its data. The source inode must remain immutable even after return: an implementation may share it with the object. Closing or unlinking the source pathname is allowed. A successful import is durable and survives it.

type FileOpener

type FileOpener interface {
	OpenFile(ctx context.Context, key string) (*os.File, error)
}

FileOpener optionally opens an immutable local object with a read-only fd. The caller owns and closes the fd. Unsupported backends return ErrNotSupported immediately, without fetching the object. An open fd survives unlink/eviction.

type ImmutablePutter

type ImmutablePutter interface {
	PutImmutable(ctx context.Context, key string, r io.Reader, size int64) error
}

ImmutablePutter atomically publishes an absent object, returning ErrExists without replacing a concurrent writer's representation. Mutable metadata continues using Backend.Put. The reader must be consumed before return; callers may then reuse its backing buffer.

type Local

type Local struct {
	Root string
	// contains filtered or unexported fields
}

Local stores backend objects in a directory. Writes are staged in the same directory and atomically renamed, so readers never observe partial chunks.

func NewLocal

func NewLocal(root string) (*Local, error)

func (*Local) Delete

func (b *Local) Delete(ctx context.Context, key string) error

func (*Local) Get

func (b *Local) Get(ctx context.Context, key string) (io.ReadCloser, error)

func (*Local) ImportFile

func (b *Local) ImportFile(ctx context.Context, key string, source *os.File, size int64) error

ImportFile hard-links an immutable open file when both paths share a filesystem. Linux publishes directly from the descriptor; other systems validate a temporary pathname link against the fd before publication. Unsupported or unlinked sources fall back to streaming in the chunk store.

func (*Local) List

func (b *Local) List(ctx context.Context, prefix string) ([]Object, error)

func (*Local) OpenFile

func (b *Local) OpenFile(ctx context.Context, key string) (*os.File, error)

func (*Local) Put

func (b *Local) Put(ctx context.Context, key string, r io.Reader, size int64) error

func (*Local) PutImmutable

func (b *Local) PutImmutable(ctx context.Context, key string, r io.Reader, size int64) error

func (*Local) Stat

func (b *Local) Stat(ctx context.Context, key string) (Object, error)

type Memory

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

Memory is a concurrency-safe backend used by tests and small embedded deployments.

func NewMemory

func NewMemory() *Memory

func (*Memory) Delete

func (b *Memory) Delete(ctx context.Context, key string) error

func (*Memory) Get

func (b *Memory) Get(ctx context.Context, key string) (io.ReadCloser, error)

func (*Memory) List

func (b *Memory) List(ctx context.Context, prefix string) ([]Object, error)

func (*Memory) Put

func (b *Memory) Put(ctx context.Context, key string, r io.Reader, size int64) error

func (*Memory) Stat

func (b *Memory) Stat(ctx context.Context, key string) (Object, error)

type Object

type Object struct {
	Key     string
	Size    int64
	ModTime time.Time
	ETag    string
}

Object describes one backend key.

type Prefix

type Prefix struct {
	Base   Backend
	Prefix string
}

Prefix returns a backend view that prefixes every key. It is useful for sharing a bucket or local root between several compactfs instances.

func (Prefix) Delete

func (p Prefix) Delete(ctx context.Context, key string) error

func (Prefix) Get

func (p Prefix) Get(ctx context.Context, key string) (io.ReadCloser, error)

func (Prefix) ImportFile

func (p Prefix) ImportFile(ctx context.Context, key string, source *os.File, size int64) error

func (Prefix) List

func (p Prefix) List(ctx context.Context, prefix string) ([]Object, error)

func (Prefix) OpenFile

func (p Prefix) OpenFile(ctx context.Context, key string) (*os.File, error)

func (Prefix) Put

func (p Prefix) Put(ctx context.Context, key string, r io.Reader, size int64) error

func (Prefix) PutImmutable

func (p Prefix) PutImmutable(ctx context.Context, key string, r io.Reader, size int64) error

func (Prefix) Stat

func (p Prefix) Stat(ctx context.Context, key string) (Object, error)

type S3

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

S3 stores objects with signed streaming requests. It owns no bucket or caller resources and performs no bucket creation. Conditional writes must be supported by the endpoint; PutImmutable never falls back to an unconditional write.

func NewS3

func NewS3(ctx context.Context, cfg S3Config) (*S3, error)

func (*S3) Delete

func (b *S3) Delete(ctx context.Context, key string) error

func (*S3) Get

func (b *S3) Get(ctx context.Context, key string) (io.ReadCloser, error)

func (*S3) List

func (b *S3) List(ctx context.Context, prefix string) ([]Object, error)

func (*S3) Put

func (b *S3) Put(ctx context.Context, key string, r io.Reader, size int64) error

func (*S3) PutImmutable

func (b *S3) PutImmutable(ctx context.Context, key string, r io.Reader, size int64) error

func (*S3) Stat

func (b *S3) Stat(ctx context.Context, key string) (Object, error)

type S3Config

type S3Config struct {
	// URL optionally supplies bucket and prefix as s3://bucket/prefix. Explicit
	// Bucket/Prefix values must agree with the URL when both are supplied.
	URL          string
	Bucket       string
	Region       string
	Endpoint     string
	Prefix       string
	UsePathStyle bool
	// AddressingStyle is auto (default), path or virtual. UsePathStyle remains
	// supported for callers using the earlier boolean option.
	AddressingStyle string
	// AccessKeyID and SecretAccessKey must be provided together. SessionToken is
	// optional. Static credentials and a Credentials provider are mutually exclusive.
	AccessKeyID     string
	SecretAccessKey string
	SessionToken    string
	// TempDir holds temporary uploads for non-seekable readers. Empty uses the
	// system temporary directory. The files are closed and removed before return.
	TempDir     string
	Credentials aws.CredentialsProvider
	HTTPClient  aws.HTTPClient
}

S3Config selects an existing bucket in AWS S3 or a compatible object store. Empty Region uses the SDK configuration, then us-east-1. Without explicit credentials, the SDK uses its environment/shared-file/workload-identity chain.

func (S3Config) Validate

func (cfg S3Config) Validate() error

Validate checks credentials, locations and addressing without loading AWS configuration or making requests. Errors never include credential values.

Jump to

Keyboard shortcuts

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