backend

package
v1.0.3 Latest Latest
Warning

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

Go to latest
Published: Nov 19, 2026 License: MIT Imports: 35 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) 本地文件系统(如 XFS);支持 FD 读取、不可变文件硬链接导入
Afero NewAfero(fs, root, AferoOptions{...}) 调用方提供的 afero.Fs,可选有界本地对象读缓存
S3 NewS3(ctx, S3Config{...}) AWS S3 或支持条件写入的兼容对象存储
Array NewArray(ctx, options) / ArrayConfig.Open(ctx) 跨 Local/S3/Memory 的 RAID0/1/5/6/10/50/60、通用 EC
Prefix Prefix{Base: objects, Prefix: "instance"} 在同一 backend 上划分对象键空间

文件系统容量

可选 SpaceReporter.StorageSpace(ctx) 返回底层文件系统的容量、空闲、普通用户可用字节及 inode 计数, 每个 Space.ID 表示一个共享容量池。这是整个底层文件系统的实时采样,包含其他目录和应用的占用, 不是当前卷的逻辑用量,也不预测压缩或去重后的容量。

Linux Local 使用同一个临时目录 FD 的 fstat/fstatfs,查询返回前关闭 FD,不枚举或同步对象。 Prefix 透传池身份;RAID0 按池身份去重,因此同一 XFS 上配置多个成员目录不会将磁盘容量重复相加。 两次采样的空闲数可能随其他写入变化,重复池使用各项保守最小值。不同文件系统的容量由上层汇总, 查询本身不保证散列布局始终均衡,也不包含独立元数据、spool、写回缓存的容量限制。

RAID0 仅在所有叶支持且查询成功时返回完整列表,任何未知叶或失败都不返回部分容量。 镜像/EC 等其他布局、S3、Memory、Afero 以及非 Linux Local 当前不提供该能力,返回 ErrNotSupported; 不把原始物理空间合计冒充镜像或校验后的逻辑容量。

FUSE 的 df 口径由共享 core 的 Config.StatFSMode / option.WithStatFSMode 选择,CLI 为 --statfs-mode logical|physical,TOML 为 [storage] statfs_mode(blk 为 [block.storage])。默认 logical:有 quota 时显示独立逻辑额度;无 quota 时总量为逻辑已用加物理空闲,空闲/可用保留物理采样,物理容量未知则只报告已知逻辑用量和零可用。physical 始终显示真实物理池,不被 quota 遮盖。逻辑统计单位为 1 字节、inode 容量未知,物理单位为 4096 字节。显示模式不改变配额准入、卷格式或 NBD 几何;完整说明见容量与 df。

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。

RAID 与 EC 对象阵列

NewArray(ctx, ArrayOptions) 组合多个 Backend;成员可混合 Local、S3 和用于测试的 Memory,作为 chunk.Store.Backend 注入,FUSE/Afero/NBD 共用。它保护的是压缩后的对象,不是 Linux mdraid 或磁盘扇区。

level 布局 成员要求 每组可恢复的成员故障
raid0 按对象散列条带 至少 2 0
raid1 每个对象完整镜像 至少 2 镜像数减 1
raid5 组内数据片 + 1 校验片 至少 3 1
raid6 组内数据片 + 2 校验片 至少 4 2
raid10 对象条带到两成员镜像组 偶数且至少 4 每对 1
raid50 对象条带到 RAID5 组 至少两组,group_size ≥ 3 每组 1
raid60 对象条带到 RAID6 组 至少两组,group_size ≥ 4 每组 2
ec k 数据片 + m 校验片 成员数 = k + m 任意 m
local, err := backend.NewLocal("/data1/array/member-a")
// 检查 err;remote 可以是 backend.NewS3 创建的另一命名空间。
objects, err := backend.NewArray(ctx, backend.ArrayOptions{
    ID: "my-array-01", Level: "raid1", TempDir: "/data1/array/tmp",
    Members: []backend.ArrayMember{
        {ID: "a", Backend: local},
        {ID: "b", Backend: remote},
    },
})
// 检查 err,然后传入 chunk.Store{Backend: objects, Codec: algorithm}。

ID、成员顺序和布局固定在各成员的二进制 superblock 中,重开不能擅自修改。新成员必须使用空的独立目录/bucket prefix;Memory 不持久,不能作为重启后的唯一副本。TempDir 需预先存在,应用在 core 停止之后才释放成员资源。

正常写入要求所有选定成员的分片和提交记录落盘,再确认成功;本地 + S3 镜像的 backend 同步会等待 S3。前台异步性能仍由 core 的 NVMe raw 写回层提供。读取可以在容错范围内降级,校验每片和重建全文;objects.Repair(ctx, key) 重建损坏/缺失片和记录,可在更换空成员命名空间后使用原成员 ID 修复。布局变更需要另建阵列并复制逻辑对象,不提供原地 reshape。

Stat 要求组内记录完整,必要时补齐中断的复制,因此成员故障期间可能拒绝新写入/去重;已知引用的 Get 仍可降级。删除先完整复制 tombstone,再删除分片;旧版本、失败上传留下的孤立分片尚无自动空间回收。阵列可变 Put/Delete/Repair 要求单 writer;同实例并发安全,普通不可变对象竞争由主成员条件写选择表示。

编码复用 klauspost/reedsolomon,支持无 cgo 构建。逐对象最多使用组宽 × 256 KiB 的编码 stripe,元数据备份不整体读入内存;物理容量还包括 padding、提交记录和校验片,List/Stat 的 Size 返回逻辑编码对象长度。

写入与读回的私有 spool 以固定 1 MiB 池缓冲复制并计算 SHA-256,每次复制结束后归还缓冲; 输入仍只消费一次,文件快照与调用方 Close 删除责任保持。内存随同时复制数增长,不随对象大小增长。

阵列配置文件

CLI 的 --backend-type array 使用 [storage.array],块模式使用 [block.storage.array]。成员只从配置读取,几何和并发参数可由 CLI 覆盖:

[storage]
backend_type = "array"

[storage.array]
id = "my-array-01"
level = "raid1"
temp_dir = "/data1/compactfs/spool"
parallel = 8

[[storage.array.members]]
id = "nvme"
type = "local"
path = "/data1/compactfs/member-a"

[[storage.array.members]]
id = "s3"
type = "s3"
[storage.array.members.s3]
url = "s3://my-bucket/compactfs-mirror"
region = "us-east-1"
# endpoint = "https://s3.example.com"
# addressing_style = "path"
# 凭据默认使用 AWS SDK 链,也支持 access_key_id / secret_access_key / session_token。

通用 EC 额外设置 level="ec"、data_shards=4、parity_shards=2,并配置 6 个成员。RAID50/60 设置 group_size。测试成员使用 type="memory";它们随进程退出消失。

每块本地盘可先挂载 XFS,再将各盘上的独立目录配置为 type="local" 成员;Array 负责对象级 RAID/EC 聚合,Local 负责文件和目录同步。

SDK 可用 backend.ArrayConfig.Open(ctx) 打开同样的成员配置,它会创建配置指定的临时目录。裸 NewArray 的 TempDir 则由调用方创建,成员资源也由调用方管理,先停止导出/core 再释放。成员目录或 S3 prefix 不得相同或互相嵌套。

卷元数据另外固定阵列布局指纹,打开其他阵列会报错,即使本地缓存仍命中。元数据迁移、导出和自动备份保留这一绑定;仅切换 TOML 不会迁移数据对象。各成员 ID、顺序和几何不能通过编辑配置在线改变。

离线 CLI 修复:停止挂载后运行 compactfs array repair -c /path/volume.toml --all,块卷追加 --block;单对象用 --key。命令复用存储锁且不启动 worker。Stat/不可变去重还检查各片存在及长度,逐对象修复后不会把尚缺片的其他对象确认成完整副本。

Documentation

Overview

Package backend provides object storage for content-addressed chunks.

Index

Constants

This section is empty.

Variables

View Source
var ErrArrayLayout = errors.New("array layout mismatch")
View Source
var ErrArrayUnavailable = errors.New("array members unavailable")

ErrArrayUnavailable means the requested durability or reconstruction threshold cannot be met. Missing/corrupt pieces are never returned as successful data.

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 operation not supported")

ErrNotSupported means an optional backend capability is unavailable. Import callers may fall back to streaming Put; an unsupported ImportFile must not publish an object before returning this error.

Functions

func ValidateArray added in v1.0.2

func ValidateArray(o ArrayOptions) error

ValidateArray checks geometry without opening or writing storage.

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 Array added in v1.0.2

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

Array borrows resources supplied to NewArray. One writer instance must own an array; operations on that instance are concurrency safe. All selected members must persist data and commit records before a write succeeds. Reads can reconstruct already committed objects with failed members.

func NewArray added in v1.0.2

func NewArray(ctx context.Context, options ArrayOptions) (*Array, error)

NewArray checks persistent member identities. Entirely empty arrays are initialized; a missing member in a nonempty array stays degraded until Repair. Wrong IDs, order or geometry are rejected, including when data is still cached.

func (*Array) Delete added in v1.0.2

func (a *Array) Delete(ctx context.Context, key string) error

func (*Array) Get added in v1.0.2

func (a *Array) Get(ctx context.Context, key string) (io.ReadCloser, error)

func (*Array) List added in v1.0.2

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

func (*Array) Put added in v1.0.2

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

func (*Array) PutImmutable added in v1.0.2

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

func (*Array) Repair added in v1.0.2

func (a *Array) Repair(ctx context.Context, key string) error

Repair verifies the logical object, reconstructs missing/corrupt parts, and restores the selected group's member identities and commit records. Member configuration/IDs must match the original array; this does not reshape it.

func (*Array) Stat added in v1.0.2

func (a *Array) Stat(ctx context.Context, key string) (Object, error)

Stat also completes interrupted commit-record replication. It never lets a failed partial write be accepted as a fully redundant deduplication hit.

func (*Array) StorageIdentity added in v1.0.2

func (a *Array) StorageIdentity() string

func (*Array) StorageSpace added in v1.0.3

func (a *Array) StorageSpace(ctx context.Context) ([]Space, error)

StorageSpace reports the distinct physical filesystems behind RAID0 members. It does not predict compression/deduplication gains, placement balance or metadata/spool limits. Mirror and parity layouts need different accounting.

type ArrayConfig added in v1.0.2

type ArrayConfig struct {
	ID           string         `toml:"id" mapstructure:"id"`
	Level        string         `toml:"level" mapstructure:"level"`
	Members      []MemberConfig `toml:"members" mapstructure:"members"`
	DataShards   int            `toml:"data_shards,omitempty" mapstructure:"data_shards"`
	ParityShards int            `toml:"parity_shards,omitempty" mapstructure:"parity_shards"`
	GroupSize    int            `toml:"group_size,omitempty" mapstructure:"group_size"`
	TempDir      string         `toml:"temp_dir,omitempty" mapstructure:"temp_dir"`
	Parallel     int            `toml:"parallel,omitempty" mapstructure:"parallel"`
}

func (ArrayConfig) Open added in v1.0.2

func (c ArrayConfig) Open(ctx context.Context) (*Array, error)

Open builds independent leaf backends, then checks the persisted array identities. It never formats devices or creates an S3 bucket.

func (ArrayConfig) Validate added in v1.0.2

func (c ArrayConfig) Validate() error

Validate checks geometry and independent namespaces without touching members.

type ArrayMember added in v1.0.2

type ArrayMember struct {
	ID      string
	Backend Backend
}

ArrayMember is an independent object namespace. ID and order are persistent. Replacing a failed member keeps its ID and requires Repair.

type ArrayOptions added in v1.0.2

type ArrayOptions struct {
	ID           string
	Level        string
	Members      []ArrayMember
	DataShards   int
	ParityShards int
	GroupSize    int
	// TempDir holds private streaming spool files, removed before return/Close.
	// Memory is bounded by group width, not object or metadata-backup size.
	TempDir  string
	Parallel int
}

ArrayOptions places encoded objects across storage members. Level is raid0, raid1, raid5, raid6, raid10, raid50, raid60 or ec. RAID0 stripes objects, not sectors. RAID10/50/60 stripe objects across fixed mirror/parity groups.

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)

func (*Local) StorageSpace added in v1.0.3

func (b *Local) StorageSpace(ctx context.Context) ([]Space, error)

type MemberConfig added in v1.0.2

type MemberConfig struct {
	ID   string   `toml:"id" mapstructure:"id"`
	Type string   `toml:"type" mapstructure:"type"`
	Path string   `toml:"path,omitempty" mapstructure:"path"`
	S3   S3Config `toml:"s3,omitempty" mapstructure:"s3"`
}

MemberConfig is a serializable leaf namespace. Memory is intentionally ephemeral and exists for tests; S3 credentials can use the AWS provider chain.

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) PutImmutable added in v1.0.2

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

PutImmutable publishes one representation under the same lock as Put/Delete.

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)

func (Prefix) StorageIdentity added in v1.0.2

func (p Prefix) StorageIdentity() string

func (Prefix) StorageSpace added in v1.0.3

func (p Prefix) StorageSpace(ctx context.Context) ([]Space, 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 `toml:"url,omitempty" mapstructure:"url"`
	Bucket       string `toml:"bucket,omitempty" mapstructure:"bucket"`
	Region       string `toml:"region,omitempty" mapstructure:"region"`
	Endpoint     string `toml:"endpoint,omitempty" mapstructure:"endpoint"`
	Prefix       string `toml:"prefix,omitempty" mapstructure:"prefix"`
	UsePathStyle bool   `toml:"path_style,omitempty" mapstructure:"path_style"`
	// AddressingStyle is auto (default), path or virtual. UsePathStyle remains
	// supported for callers using the earlier boolean option.
	AddressingStyle string `toml:"addressing_style,omitempty" mapstructure:"addressing_style"`
	// AccessKeyID and SecretAccessKey must be provided together. SessionToken is
	// optional. Static credentials and a Credentials provider are mutually exclusive.
	AccessKeyID     string `toml:"access_key_id,omitempty" mapstructure:"access_key_id"`
	SecretAccessKey string `toml:"secret_access_key,omitempty" mapstructure:"secret_access_key"`
	SessionToken    string `toml:"session_token,omitempty" mapstructure:"session_token"`
	// TempDir holds temporary uploads for non-seekable readers. Empty uses the
	// system temporary directory. The files are closed and removed before return.
	TempDir     string                  `toml:"temp_dir,omitempty" mapstructure:"temp_dir"`
	Credentials aws.CredentialsProvider `toml:"-" mapstructure:"-"`
	HTTPClient  aws.HTTPClient          `toml:"-" mapstructure:"-"`
}

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.

type Space added in v1.0.3

type Space struct {
	ID                                    string
	TotalBytes, FreeBytes, AvailableBytes uint64
	Files, FreeFiles                      uint64
}

Space describes one backing filesystem, not the logical size of its objects. ID identifies the same space across directory and Prefix views. Bytes include other users of that filesystem; AvailableBytes excludes reserved free space.

type SpaceReporter added in v1.0.3

type SpaceReporter interface {
	StorageSpace(context.Context) ([]Space, error)
}

SpaceReporter optionally reports all backing filesystems as an owned snapshot. Unknown or incomplete capacity must return ErrNotSupported or an error rather than a successful partial list. Querying space does not scan or sync objects.

Jump to

Keyboard shortcuts

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