afero

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: 18 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

在应用内使用 Afero

github.com/lfhy/compactfs/export/afero 将 *core.FileSystem 导出为 afero.Fs / afero.File。应用直接调用文件接口,复用 compactfs 的分块、压缩、去重、缓存和备份,不需要 FUSE 挂载或 daemon,支持 CGO_ENABLED=0。

先运行一个持久化示例

在 compactfs 仓库根目录执行:

CGO_ENABLED=0 GOWORK=off go run ./examples/afero /data1/compactfs-afero-demo

输出 hello compactfs。完整代码在 examples/afero/main.go,它使用:

设置 示例取值
对象 backend backend.NewLocal(root/backend)
元数据 WithMetadata 打开 root/metadata.db;auto 新库默认 bbolt
算法与分块 codec.NewGzip(1),固定 4 MiB raw 窗口
配额 10 GiB 逻辑文件大小
备份 显式启用,上传至同一 backend
raw/编码对象磁盘缓存 不启用,文件关闭等待 backend
退出 先关闭 view,再关闭 core;汇总关闭错误

接入独立 Go 模块时添加 github.com/lfhy/compactfs 依赖。本文以当前源码 API 为准;使用尚未发版的本地代码时,可在应用自己的 go.mod 加本地 replace,无需上级 go.work:

go mod edit -replace=github.com/lfhy/compactfs=/path/to/compactfs
go get github.com/lfhy/compactfs

Afero 文件操作

下面代码放在成功创建 view 之后;引擎初始化、导入和完整错误处理见可运行示例。

if err := view.MkdirAll("documents", 0o750); err != nil {
    return err
}
if err := afero.WriteFile(view, "documents/hello.txt", []byte("hello compactfs"), 0o640); err != nil {
    return err
}
data, err := afero.ReadFile(view, "documents/hello.txt")
if err != nil {
    return err
}
fmt.Println(string(data))

支持 afero.ReadFile、WriteFile、Walk、NewBasePathFs、NewReadOnlyFs 等。使用 afero.NewIOFS(view) 可接入标准库 io/fs、fs.WalkDir、模板或 http.FS;适配器文件也实现 io/fs.ReadDirFile。

在哪里配置

SDK 不读取 ~/.compactfs/config.toml。应用用 core.New(option.Config{...}, options...) 配置存储;compactafero.New 只负责适配接口。公共选项在 fs/option,FUSE/Afero/blk 共用。

能力 Go 配置 默认或边界
元数据 WithMetadata(meta.Options{Path: path, Engine: meta.EngineAuto}) 必须提供元数据;新路径 auto 为 bbolt,已有库自动识别
Pebble block cache meta.Options{Engine: meta.EnginePebble, CacheBytes: 128 << 20} 128 MiB;不是进程 RSS 上限
Backend/算法 option.Config.Chunks: &chunk.Store{Backend: objects, Codec: algorithm} 由应用创建;codec.Raw{} 关闭压缩
固定窗口 WithChunkSize(4 << 20) 默认 4 MiB,必须匹配已有卷
分块策略 WithChunking(chunk.ChunkingOptions{Mode: chunk.Fixed}) 默认 fixed;FastCDC 显式开启
原始 NVMe 写回 WithStaging(raw) 默认关闭,需 writer.Open 创建
编码对象磁盘缓存 WithCache(encoded) 默认关闭,需 cache.New 创建
解码内存缓存 WithRead(option.ReadConfig{CacheBytes: 128 << 20, Workers: 4, Ahead: 4, RawRefill: true}) 省略时采用这些默认值;ReadConfig{} 关闭
并发、排队 WithWorkers(8)、WithWriteQueue(128) 有界队列;默认值由 core 根据运行环境确定
Chunk 重试 WithChunkRetry(3, 50*time.Millisecond) Store 未显式设置时使用
容量限制 WithQuotaBytes(10 << 30) 默认不限,按逻辑文件大小
后端同步 WithSyncBackend(true) 有 raw 缓存时默认允许本地恢复边界
自动元数据备份 WithMetadataBackup(option.MetadataBackupConfig{}) SDK 默认关闭;零配置开启后每 5 分钟、保留 7 份
目录分页 WithDirectoryPageSize(256) 默认 256,范围 1..4096

WithMetadata 由 core 创建和关闭数据库;使用 WithNamespace 注入已有命名空间时,元数据库仍由应用负责。不要把同一个数据库交给多个活跃引擎;切换到 Pebble 不会移除当前生产 Namespace 的全量 RAM 索引。

开启 NVMe 异步写回

在示例 run 中,root 已经是绝对路径。在创建 core 之前打开 raw 缓存并注册关闭:

// 额外导入 github.com/lfhy/compactfs/fs/cache/writer。
metadataPath := filepath.Join(root, "metadata.db")
raw, err := writer.Open(filepath.Join(root, "raw-cache"), 8 << 30, metadataPath)
if err != nil {
    return err
}
defer func() { err = errors.Join(err, raw.Close()) }()

给随后原有的 core.New 增加选项,其余代码和两个 Close defer 保持原顺序:

option.WithStaging(raw),
option.WithWorkers(8),
option.WithWriteQueue(128),

这样注册 defer 后,关闭顺序为 view → core → raw。owner 使用与 WithMetadata 相同的元数据绝对路径;容量至少能容纳一个 raw 窗口。core 会在启动时恢复缓存中的待提交数据,不需要应用重新实现队列。

写入先进入有界队列,本地同步后可以由后台继续压缩和上传。clean raw 数据保留为读缓存,需要空间时才淘汰;dirty 数据必须等到 backend 提交和元数据持久化之后才可淘汰。详细边界见写回指导。

编码对象缓存可独立选择,用 cache.New(root, bytes) 创建后传入 WithCache;关闭缓存前先停止使用它的 core。通常不需要同时在 chunk.Store 和 backend.Afero 再放重复的编码缓存。

启用 CDC 或更强同步

默认固定分块不执行 CDC 扫描。在创建新卷时可以加入:

option.WithChunking(chunk.ChunkingOptions{
    Mode: chunk.FastCDC,
    MinSize: 64 << 10, AvgSize: 256 << 10, MaxSize: 1 << 20,
}),

raw 寻址窗口保持 4 MiB,后台按内容切分子块。重开时必须匹配原分块参数,见内容分块。

compactafero.Options 仅控制接口 context 和额外同步要求:

view, err := compactafero.New(storage, compactafero.Options{
    Context: ctx,       // 默认 context.Background()
    SyncBackend: true, // 文件同步/关闭等待 backend
})

共享 WithSyncBackend(true) 会要求所有导出至少等待 backend;适配器不能降低该要求。普通 Write 返回始终不代表已持久化。

操作 有 raw 缓存,默认本地同步 无 raw 缓存,或要求 SyncBackend
File.Sync / File.Close / O_SYNC 写入 raw 与元数据本地可恢复 等待该文件 backend 持久化
FS.Close 关闭适配句柄,按本地边界同步 关闭适配句柄并等待 backend
FS.Sync(ctx) 显式等待后台提交到 backend 同样等待 backend

迁移、停用缓存或交给另一个导出前,先停止应用写入并调用 view.Sync(ctx),再关闭 view 和 core。有取消 context 时先关闭再取消。File.Close 失败可检查并重试;FS.Close 开始后句柄失效,未完成同步可再次 FS.Close 重试。

再用 FUSE 访问同一卷

示例使用的持久卷可以直接交给 CLI,不用重新导入文件。应用关闭 view/core 后运行:

CGO_ENABLED=0 GOWORK=off go build -trimpath -o bin/compactfs .
mkdir -p "$HOME/mnt/compactfs-afero"
./bin/compactfs mount \
  --backend-type local \
  --backend /data1/compactfs-afero-demo/backend \
  --metadata /data1/compactfs-afero-demo/metadata.db \
  --metadata-engine auto \
  --cache /data1/compactfs-afero-demo/fuse-cache \
  --codec gzip --gzip-level 1 --chunk-size 4MiB --chunking fixed \
  --quota 10GiB \
  "$HOME/mnt/compactfs-afero"

在另一终端读取 ~/mnt/compactfs-afero/documents/hello.txt。挂载内写入后,先 ./bin/compactfs sync "$HOME/mnt/compactfs-afero",再 fusermount3 -u "$HOME/mnt/compactfs-afero" 并等待挂载进程结束;应用即可重开读取。

2026-11-04 已在 /data1 的独立测试卷验证以上 bbolt/gzip/fixed 流程:Afero 写入 → FUSE 读写 → sync/卸载 → Afero 重开,双向内容检查通过;项目 README 的 TOML 也经过实际挂载读写验证。这是功能验证,吞吐指标另见性能总览。

必须对应的设置 Afero → CLI
数据对象 chunk.Store.Backend → 同一个 --backend-type / --backend,S3 还需同 bucket/prefix
元数据 meta.Options.Path/Engine → --metadata / --metadata-engine
raw 窗口 WithChunkSize → --chunk-size
CDC WithChunking → --chunking / --chunk-min/avg/max
逻辑配额 WithQuotaBytes → --quota,策略由各入口配置
新写入算法 示例 gzip level 1 → --codec gzip --gzip-level 1;已有对象按引用格式解码

新缓存目录要求源卷先排空到 backend。原应用已经启用 raw 写回时,不能在脏数据尚未提交时丢开它;也不能让两个进程同时写同一个元数据库。CLI 有进程所有权锁,SDK 应用须自行排除其他使用者。完整操作也见项目 README。

接口边界

  • 一个 core 使用一个 Afero 适配器,应用可以共享该实例或其 Afero wrapper。不同适配器或多个导出同时修改 inode 暂无统一打开句柄管理。
  • 绝对与相对路径都以虚拟根 inode 1 为起点,词法清理后的 .. 不会越过根;不使用宿主当前目录。
  • 支持 OpenFile 标志、追加、定位读写、Seek、Truncate、属性、目录枚举与重命名。ReadAt / WriteAt 不改偏移,追加句柄不允许 WriteAt,扩展区域读零。
  • Remove/RemoveAll 和覆盖 Rename 遇到打开的目标返回 EBUSY;源文件可以在打开时重命名。尚不支持 unlink 后继续访问。
  • 目录按名称排序,有限数量的 Readdir/ReadDir 使用有界页;全部结果请求仍会分配完整结果。跨页不维持数据库快照,Seek(0) 重新枚举。
  • mode/uid/gid/mtime 会保存,不执行宿主权限检查,不存 atime,不支持符号链接或硬链接。
  • 路径错误为 *os.PathError,Rename 为 *os.LinkError,可用 errors.Is / os.IsNotExist 判断。

export/afero 是“把 compactfs 作为 Fs 使用”;backend.NewAfero 则是“把已有 Fs 作为对象存储”,两者方向不同。后者配置见后端指导。备份与双引擎迁移见元数据维护,开发规则见 AGENTS。

Documentation

Overview

Package afero exports compactfs directly to Go applications as an afero.Fs. It owns its adapter and file handles, not the supplied shared storage engine.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type FS

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

FS implements afero.Fs without a FUSE mount, kernel device or daemon. Use one FS per core.FileSystem, and share it (or afero wrappers around it) in the app. Relative and absolute paths address the same virtual root, not the host cwd.

func New

func New(storage *core.FileSystem, options ...Options) (*FS, error)

New adapts an existing storage engine. It accepts at most one Options value; omitting it selects a background context and local-cache durability.

Example
package main

import (
	"context"
	"fmt"

	"github.com/lfhy/compactfs/codec"
	compactafero "github.com/lfhy/compactfs/export/afero"
	"github.com/lfhy/compactfs/fs/backend"
	"github.com/lfhy/compactfs/fs/chunk"
	"github.com/lfhy/compactfs/fs/core"
	"github.com/lfhy/compactfs/fs/meta"
	"github.com/lfhy/compactfs/fs/option"
	"github.com/spf13/afero"
)

func main() {
	ctx := context.Background()
	metadata := meta.NewMemoryEngine()
	namespace, err := meta.OpenNamespace(ctx, metadata)
	if err != nil {
		panic(err)
	}
	algorithm, err := codec.NewGzip(1)
	if err != nil {
		panic(err)
	}
	shared := []option.Option{
		option.WithChunking(chunk.ChunkingOptions{Mode: chunk.Fixed}),
		option.WithQuotaBytes(100 << 20),
	}
	storage, err := core.New(option.Config{Namespace: namespace,
		Chunks: &chunk.Store{Backend: backend.NewMemory(), Codec: algorithm}}, shared...)
	if err != nil {
		panic(err)
	}
	view, err := compactafero.New(storage)
	if err != nil {
		panic(err)
	}
	if err := view.MkdirAll("documents", 0o750); err != nil {
		panic(err)
	}
	if err := afero.WriteFile(view, "documents/hello.txt", []byte("hello compactfs"), 0o640); err != nil {
		panic(err)
	}
	data, err := afero.ReadFile(view, "documents/hello.txt")
	if err != nil {
		panic(err)
	}
	fmt.Println(string(data))
	if err := view.Close(); err != nil {
		panic(err)
	}
	if err := storage.Close(); err != nil {
		panic(err)
	}
	if err := metadata.Close(); err != nil {
		panic(err)
	}
}
Output:
hello compactfs

func (*FS) Chmod

func (f *FS) Chmod(name string, mode os.FileMode) error

func (*FS) Chown

func (f *FS) Chown(name string, uid, gid int) error

func (*FS) Chtimes

func (f *FS) Chtimes(name string, atime, mtime time.Time) error

Chtimes updates mtime. The current metadata format does not store atime.

func (*FS) Close

func (f *FS) Close() error

Close invalidates adapter handles and synchronizes the configured durability boundary. It does not close the supplied engine, caches, metadata or worker. Failed syncs remain retryable by calling Close again.

func (*FS) Create

func (f *FS) Create(name string) (aferofs.File, error)

func (*FS) Mkdir

func (f *FS) Mkdir(name string, perm os.FileMode) error

func (*FS) MkdirAll

func (f *FS) MkdirAll(name string, perm os.FileMode) error

func (*FS) Name

func (*FS) Name() string

func (*FS) Open

func (f *FS) Open(name string) (aferofs.File, error)

func (*FS) OpenFile

func (f *FS) OpenFile(name string, flag int, perm os.FileMode) (aferofs.File, error)

func (*FS) Remove

func (f *FS) Remove(name string) error

func (*FS) RemoveAll

func (f *FS) RemoveAll(name string) error

func (*FS) Rename

func (f *FS) Rename(oldname, newname string) error

func (*FS) Stat

func (f *FS) Stat(name string) (os.FileInfo, error)

func (*FS) Sync

func (f *FS) Sync(ctx context.Context) error

Sync drains open files and background uploads to the backend. Concurrent writers should be stopped if the application needs a stable global snapshot.

type File

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

File is an application handle. Offsets and directory cursors belong to the handle; mutable file content belongs to the shared inode in FS.

func (*File) Close

func (f *File) Close() error

func (*File) Name

func (f *File) Name() string

func (*File) Read

func (f *File) Read(data []byte) (int, error)

func (*File) ReadAt

func (f *File) ReadAt(data []byte, off int64) (int, error)

func (*File) ReadDir

func (f *File) ReadDir(count int) ([]fs.DirEntry, error)

func (*File) Readdir

func (f *File) Readdir(count int) ([]os.FileInfo, error)

func (*File) Readdirnames

func (f *File) Readdirnames(count int) ([]string, error)

func (*File) Seek

func (f *File) Seek(offset int64, whence int) (int64, error)

func (*File) Stat

func (f *File) Stat() (os.FileInfo, error)

func (*File) Sync

func (f *File) Sync() error

func (*File) Truncate

func (f *File) Truncate(size int64) error

func (*File) Write

func (f *File) Write(data []byte) (int, error)

func (*File) WriteAt

func (f *File) WriteAt(data []byte, off int64) (int, error)

func (*File) WriteString

func (f *File) WriteString(value string) (int, error)

type Options

type Options struct {
	// Context is used for interface methods which cannot accept a context.
	// Nil means context.Background. Close the adapter before cancelling it.
	Context context.Context
	// SyncBackend makes File.Sync, File.Close and FS.Close wait for backend
	// persistence. The default confirms local raw data and metadata when a raw
	// cache is configured; without that cache all syncs wait for the backend.
	// A shared option.WithSyncBackend(true) also requires backend persistence.
	SyncBackend bool
}

Options controls the lifetime context and durability boundary of the adapter. Configure shared storage settings with fs/option in core.New; the adapter shares the engine and does not own or reconfigure it.

Jump to

Keyboard shortcuts

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