afero

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Nov 3, 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

在应用内使用 compactfs

导入 github.com/lfhy/compactfs/export/afero,将已有 *core.FileSystem 适配为真正的 afero.Fs。不需要 FUSE 挂载、NBD 设备或 daemon; 继续复用 chunk 去重、codec、缓存、配额和异步上传。产品可 CGO_ENABLED=0 构建。

import (
    compactafero "github.com/lfhy/compactfs/export/afero"
    "github.com/spf13/afero"
)

// storage 是应用已创建的 *core.FileSystem。
view, err := compactafero.New(storage)
if err != nil {
    return err
}
defer view.Close() // 生产调用方应检查关闭错误。

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")

支持 afero 的 ReadFile、WriteFile、Walk、NewBasePathFs、NewReadOnlyFs 等工具。 也可以通过 afero.NewIOFS(view) 接入标准库 io/fs、fs.WalkDir、模板和 http.FS。 适配器文件还实现 io/fs.ReadDirFile。

创建持久存储引擎

应用通过公开包组装引擎;下面使用本地日志和 backend,默认 gzip level 1:

import (
    "context"
    "path/filepath"

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

ctx := context.Background()
engine, err := meta.OpenLog(filepath.Join(root, "metadata.log"), meta.LogOptions{})
if err != nil { return err }
defer engine.Close()
namespace, err := meta.OpenNamespace(ctx, engine)
if err != nil { return err }
objects, err := backend.NewLocal(filepath.Join(root, "backend"))
if err != nil { return err }
algorithm, err := codec.NewGzip(1)
if err != nil { return err }
encoded, err := cache.New(filepath.Join(root, "encoded-cache"), 1 << 30)
if err != nil { return err }
storage, err := core.New(core.Config{
    Namespace: namespace,
    Chunks: &chunk.Store{Backend: objects, Codec: algorithm},
    Cache: encoded, // 编码对象的本地磁盘缓存,1 GiB 上限。
    Read: &core.ReadConfig{CacheBytes: 128 << 20, Workers: 4, Ahead: 4},
})
if err != nil { return err }
defer storage.Close()
view, err := compactafero.New(storage)
if err != nil { return err }
defer view.Close()

上例没有 raw 缓存,文件同步/关闭会等待 backend。需要异步压缩时,在 core.New 前 打开 fs/cache/writer.Store,将其设为 Config.Staging;owner 使用元数据日志的绝对路径, raw 容量至少容纳一个 chunk。上例的编码读缓存通过 Config.Cache 注入,设为 nil 可关闭。 原始层不依赖 FUSE,应用内同样先本地持久化,再由后台编码上传,详见写回说明。 FPGA 或独立算法进程通过 chunk.Store.Codec 注入,连接方式见worker 指导。

应用内 afero 直接复用 core 的三类缓存,构造引擎时通过公开配置注入:

缓存 选项 默认值与关闭方式
编码对象本地磁盘缓存 core.Config.Cache,用 cache.New(root, bytes) 创建 默认不启用,nil 关闭
原始 chunk 持久写回缓存 core.Config.Staging,用 writer.Open(root, bytes, owner) 创建 默认不启用,nil 关闭;脏数据不可直接删除
解码内存缓存与顺序预取 core.Config.Read nil 为 128 MiB/4 workers/4 块预取;&core.ReadConfig{} 关闭缓存与预取

compactafero.Options 控制 context 和同步边界,缓存由创建 core 时的配置决定。 如果对象 backend 本身也是 Afero,另有可选的 backend.AferoOptions 对象缓存, 详见后端用法;通常选择一处编码对象缓存即可。

这些 defer 用于展示所有权和逆序关闭;生产应用应汇总各个关闭错误。 view.Close 只关闭适配器并使其句柄失效,不关闭传入的 engine。停用顺序是 应用句柄 → view → core → raw cache → metadata → 算法资源;保持算法与元数据可用直到 core 停止。

接口与同步

FS 实现全部 afero.Fs 方法:Create、Open/OpenFile、Mkdir/MkdirAll、Stat、Remove/RemoveAll、 Rename、Chmod、Chown、Chtimes 和 Name。File 实现顺序/定位读写、Seek、Stat、Sync、Truncate、 WriteString、目录枚举和 Close。

  • 支持 O_CREATE、O_EXCL、O_TRUNC、O_APPEND、O_SYNC 和访问模式,保留每个句柄独立的偏移。
  • 同 inode 的句柄在一个适配器中共用 core.File;追加位置与实际写入按 inode 同步,普通定位 IO 可并发。
  • ReadAt/WriteAt 不改变偏移,追加句柄的 WriteAt 返回错误;截断扩展区域读零。
  • 目录按名称排序,分批读取共用游标;Seek(0, io.SeekStart) 重新枚举。
  • 路径错误使用 *os.PathError,Rename 使用 *os.LinkError,可通过 errors.Is/os.IsNotExist 判断。
view, err := compactafero.New(storage, compactafero.Options{
    Context: ctx,       // 接口没有 context 参数时使用;默认 Background。
    SyncBackend: true, // 如需每次文件同步/关闭都等待 backend。
})
操作 默认有 raw 缓存 SyncBackend=true,或无 raw 缓存
普通 Write 接收/入队,不代表已持久化 接收/入队,不代表已持久化
File.Sync、File.Close、O_SYNC 写入 raw 与元数据本地可恢复,压缩仍可后台执行 等待该文件后端持久化
FS.Close 关闭所有适配句柄,本地状态可恢复 关闭句柄并等待后台提交
FS.Sync(ctx) 显式排空到 backend 同样排空到 backend,无 raw 缓存也可调用

File.Close 失败后句柄可继续检查并重试关闭。FS.Close 开始后所有适配句柄失效, 未成功同步的状态仍可通过再次 FS.Close 重试。使用带取消的 Options.Context 时,先关闭再取消; 迁移或移除 raw 缓存前,应先在停止写入后调用 view.Sync(ctx)。

当前语义边界

  • 这是虚拟根目录。绝对与相对路径都从 inode 1 开始,路径按当前平台分隔符转换并词法清理,.. 不会越过虚拟根;不读取宿主当前目录。
  • 一个 core 使用一个此适配器,应用共享该实例或其 afero wrapper。多个独立适配器,或其他导出同时修改相同 inode 的可变内容,目前没有跨前端的统一打开句柄管理。
  • Remove/RemoveAll 以及 Rename 覆盖目标遇到打开句柄返回 EBUSY。源文件可在打开时重命名;目标不存在或已关闭时支持原子替换。尚未提供 POSIX 的 unlink 后继续访问语义。
  • RemoveAll 会先检查打开目标;RemoveAll("/") 清空虚拟根内容并保留根 inode,Remove("/") 返回错误。
  • 元数据记录 mode/uid/gid/mtime;不实施宿主用户权限检查,不存储 atime,Chtimes 只更新 mtime。FileInfo.Sys 返回无 chunk 列表的 *meta.Entry 副本。
  • 不实现符号链接、硬链接或额外的 afero 可选链接接口。backend 内部的不可变硬链接导入不等于应用层文件硬链接能力。

开发约定见 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/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)
	}
	storage, err := core.New(core.Config{Namespace: namespace,
		Chunks: &chunk.Store{Backend: backend.NewMemory(), Codec: algorithm}})
	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.
	SyncBackend bool
}

Options controls the lifetime context and durability boundary of the adapter. Configure encoded, raw writeback and decoded caches in core.Config before New; the adapter shares those caches and does not own or reconfigure the engine.

Jump to

Keyboard shortcuts

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