option

package
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Nov 5, 2026 License: MIT Imports: 5 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

各导出共用的存储选项

github.com/lfhy/compactfs/fs/option 定义公共 Config 与 With* 选项。 在 core.New 中配置一次,再选择 Afero、FUSE 或 blk 导出;切换导出时复用同一份配置代码。 本包不打开资源、不启动 worker,不依赖 core 或具体导出协议。

import (
    "github.com/lfhy/compactfs/fs/chunk"
    "github.com/lfhy/compactfs/fs/core"
    "github.com/lfhy/compactfs/fs/option"
)

// namespace 与 chunks 由应用创建;chunks 包含 backend、codec 和可选 CPU 回退。
shared := []option.Option{
    option.WithChunkSize(4 << 20),
    option.WithChunking(chunk.ChunkingOptions{Mode: chunk.Fixed}),
    option.WithRead(option.ReadConfig{CacheBytes: 128 << 20, Workers: 4, Ahead: 4}),
    option.WithDirectoryPageSize(256),
    option.WithQuotaBytes(100 << 30),
    option.WithMetadataBackup(option.MetadataBackupConfig{}), // 显式开启,需 bbolt 等支持快照的引擎
}
storage, err := core.New(option.Config{Namespace: namespace, Chunks: chunks}, shared...)
if err != nil { return err }
// 停止并关闭导出后,再关闭 storage;最后关闭 raw cache、metadata 和算法资源。

选项从左到右覆盖 Config 中的同名设置,最后一个生效;校验与默认值在 core 中统一处理。 core.Config、core.ReadConfig 和 core.MetadataBackupConfig 是这里类型的别名,原来的结构体配置仍可使用。 共享的配置值可复用,实际 namespace、chunk.Store、缓存等资源仍遵守各自所有权约束。 每个活跃引擎独占自己的 chunk.Store;不要把一个正在服务的 Store 重新交给另一个 core 初始化。

能力 共享 Go 选项 mount / blk CLI
本地元数据引擎 WithMetadata(meta.Options{Path: path, Engine: "pebble"}) 或 Config.Metadata --metadata-engine、--metadata-cache-bytes,storage/block.storage 同名下划线键
命名空间与对象/算法 Store WithNamespace、WithChunks 或 Config.Namespace/Chunks --metadata、backend、codec/worker 参数
raw 寻址窗口 WithChunkSize --chunk-size
fixed / FastCDC WithChunking --chunking、--chunk-min/avg/max
编码对象磁盘缓存 WithCache --cache、--cache-bytes
持久 raw 写回缓存 WithStaging --writeback、--writeback-bytes
解码内存缓存、预取和 raw 回填 WithRead --read-cache-bytes、--read-workers、--read-ahead、--read-raw-refill
目录句柄分页 WithDirectoryPageSize(默认 256,最大 4096) --directory-page-size,storage.directory_page_size / block.storage.directory_page_size
工作并发与有界队列 WithWorkers、WithWriteQueue --workers、--write-queue
chunk 重试默认值 WithChunkRetry --chunk-attempts、--retry-backoff
逻辑容量上限 WithQuotaBytes --quota
同步至少等待 backend WithSyncBackend(true) --sync-mode backend
文件历史(默认关闭) WithHistory(HistoryConfig{}) / WithoutHistory() --history、--history-max-versions、--history-max-age、--history-max-bytes、--history-mode、--history-journal-bytes、--history-journal-codec,见文件历史
自动元数据备份 WithMetadataBackup / WithoutMetadataBackup --metadata-backup 及 interval/timeout/retain/prefix 参数

WithCache(nil) 不注入引擎级编码缓存;若直接在 chunk.Store.Cache 上另配了缓存,需同时保持其配置一致。 WithChunkRetry 为 Store 中未设置的重试字段填默认值;Store 自身显式设置的值优先。 WithRead(option.ReadConfig{}) 关闭解码缓存和预取;省略 Read 则采用 core 的默认值。

默认仍为固定分块。需要内容分块时,把共享选项中的 WithChunking 改为:

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

CDC 在固定 raw 窗口内进行,窗口及分块策略在新卷创建时固定,详见内容分块。 库用户省略 MetadataBackup 默认不启动调度;显式 WithMetadataBackup(option.MetadataBackupConfig{}) 选择 5 分钟、10 分钟超时、保留 7 份,详见元数据维护。CLI 默认开启备份。

选择导出

导出 共享引擎入口 留在导出层的选项
Afero compactafero.New(storage, compactafero.Options{...}) 接口 Context、额外的 SyncBackend 要求
FUSE compactfuse.Mount(storage, mountpoint, compactfuse.Options{...}) 挂载参数、AttrTTL、UID/GID 映射及权限掩码;权限指导
blk blk.Open(ctx, blk.VolumeConfig{FileSystem: storage, ...}) 卷名、大小、只读、额外同步要求;NBD 网络参数在 blk.Config

WithSyncBackend(true) 是所有导出的最低确认边界;Afero Options 或 blk VolumeConfig 中的 false 不能把它降回 local。共享设置为 false 时,单个适配器或请求仍可要求更强的 backend 同步。 普通 Write 不因此变成同步压缩,要求作用于 fsync / File.Sync / FLUSH / FUA 等同步操作。

各适配器保持原来的生命周期:先停用导出和句柄,再关闭 core,最后关闭注入的资源。 同 inode 不能交给多个独立前端同时维护可变内容;切换导出前应停止旧入口并完成所需同步。 新建另一引擎时重用选项值并重新提供该引擎独占的资源,不能借选项在线改已有卷策略。

新能力维护

新增共享能力必须提供 Config 字段及相应选项,逐项检查三种导出、CLI/TOML、默认值、持久化边界与示例; 更新根、fs/option 和各 export 的 AGENTS.md 与 codemap。协议专属参数保留在各自导出包。

export_test.go 使用同一组选项验证默认 fixed、显式 fixed、FastCDC 三种配置, 通过 Afero、FUSE Node/Handle、blk 卷实际读写,以阻塞编码器检查 backend 同步, 并验证自动备份恢复到新数据库、无原 raw 缓存时的完整读回。FUSE 用例不挂内核文件系统,blk 用例不挂接 NBD 设备。

CGO_ENABLED=0 GOWORK=off go test ./fs/option ./fs/core ./export/... ./cmd
CGO_ENABLED=1 GOWORK=off go test -race ./fs/option ./fs/core ./export/... ./cmd

目录分页作用于 FUSE 和 Afero 的有限数量读取,blk 通过同一 core 接收设置,但 NBD 无目录枚举请求。 Afero Readdir(-1) 明确请求全部剩余结果,返回切片仍按结果数占用内存;Readdir(n>0) 只在句柄保留一页。

元数据引擎与所有权

option.WithMetadata(meta.Options{Path: "/data1/app/metadata", Engine: "pebble", CacheBytes: 128 << 20}) 允许 core 创建并拥有本地数据库,storage.Close() 在 workers 和最终备份结束后同步关闭它。 Engine: "auto" 根据已有文件/目录识别 bbolt/Pebble,新路径默认 bbolt;选择与已有路径不匹配时报错,不能在线转换。 Pebble 的 CacheBytes 仅限制 block cache,当前 Namespace 仍有全量 RAM 索引。

该选项与 WithNamespace 互相替换,最后一个生效;直接同时设置 Config.Metadata 和 Namespace 会被拒绝。 选项自身不打开资源;应用须保证同一数据库只有一个活跃写入实例。 继续注入 Namespace 时,core 不会关闭其引擎,由调用方在 core 关闭后释放。 FUSE/Afero/blk 均复用这一入口,切换导出不需要重配元数据。

跨导出测试覆盖两种引擎的 fixed/FastCDC、raw writeback、backend 同步和最终备份, 再恢复到另一种引擎并在无原缓存条件下读回数据;另验证失败初始化与并发 Close 的资源释放。

RAID / EC 与三个导出

用 backend.ArrayConfig.Open(ctx) 或 backend.NewArray(ctx, options) 创建对象 backend, 再通过 WithChunks(&chunk.Store{Backend: objects, Codec: algorithm}) 注入。 FUSE、Afero、blk 都使用此共享 core;无需单独的协议层 RAID 参数。 自动元数据备份也写入该阵列。配置示例和容错边界见后端指导。

array_export_test.go 验证三个导出在 EC 成员丢失、进程资源重新打开且无原缓存后仍可读回 gzip 数据, 并拒绝元数据绑定到另一个阵列。FUSE 此处测试 Node/Handle,内核挂载验证另行记录。

文件历史与恢复

option.WithHistory(option.HistoryConfig{Mode: "journal", MaxVersions: 64, JournalBytes: 64 << 20})

在 core.New 启动前加入共享选项,Afero、FUSE、blk 都生效。默认关闭;开启后每次实际到达 core 的 Write/WriteAt、截断、属性修改、删除、替换重命名和 TRIM 保留操作前版本。Mode=backend 时 Write 返回前等待 backend 和元数据同步;示例选择 journal,保留窗口聚合、追加本地增量,Write 不等待压缩,持久性由 fsync/backend sync 确认。

storage.CheckpointFile(ctx, inode, label) 保存当前内容;storage.HistoryVersions(ctx, meta.HistoryQuery{Path: "/file"}) 分页查询,已删除路径仍可查询。停止导出和所有句柄后,storage.RestoreVersion(ctx, versionID, parent, name, replace) 恢复为新 inode;replace=false 拒绝覆盖。直接操作 Namespace 或底层 Engine 不受自动历史保护。关闭 recording 不删除已有记录。

历史保存每个文件的完整引用列表,版本间复用数据对象;不是整个目录树的原子快照,也不是 POSIX unlink-open/hardlink 的补全。块卷保护整个 /.blk/<name> 镜像,不能将单个 sector 版本当成 guest 文件系统的一致快照。默认 64 版本/7 天/256 MiB 记录上限,不包括 backend 历史数据;尚无物理 chunk GC。恢复、备份与限制详见文件历史。

HistoryConfig.Mode 默认 backend(每次写远端持久);journal 需要 Staging,将每次写追加本地日志,fsync 确认本地,Sync/backend/backup/关闭才确认远端历史。日志默认 64 MiB、每 epoch 最多 256 次写,满时 checkpoint 反压;所有导出复用相同逻辑。详细同步、恢复与缓存绑定见文件历史。

JournalCodec 默认 minlz,仅压缩本地日志且仅在变小时采用,raw 关闭;backend 算法独立。日志按原文记预算,避免高压缩率导致回放工作无界;stat.history 区分两种字节数。

Documentation

Overview

Package option defines storage settings shared by all compactfs exports. Apply them when constructing core.FileSystem, then pass that engine to FUSE, Afero or blk. Options never reconfigure an engine that is already running.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

type Config struct {
	Namespace *meta.Namespace
	// Metadata selects a native database opened and owned by core. Use either
	// Metadata or an injected Namespace, never both. Nil does not open a DB.
	Metadata *meta.Options
	Chunks   *chunk.Store
	Cache    *cache.Cache
	Staging  *writer.Store
	// SyncBackend sets the minimum file-sync durability for every export.
	// With Staging and false, sync may stop at recoverable local storage.
	// An individual sync request may strengthen this boundary, never weaken it.
	SyncBackend bool
	ChunkSize   int
	// Chunking controls backend subdivision; raw cache windows stay ChunkSize.
	// The zero value keeps fixed chunks; FastCDC is explicitly enabled.
	Chunking chunk.ChunkingOptions

	// DirectoryPageSize bounds attributes retained per directory handle. Zero
	// selects meta.DefaultDirectoryPageSize; the maximum is meta.MaxDirectoryPageSize.
	DirectoryPageSize int
	Workers           int
	WriteQueue        int
	ChunkAttempts     int
	ChunkRetryBackoff time.Duration
	// Read controls decoded backend caching and sequential read ahead. Nil
	// selects bounded defaults, independently of the optional SSD cache.
	Read *ReadConfig
	// QuotaBytes limits the sum of logical file sizes in the namespace. Zero is
	// unlimited; compressed backend bytes are reported separately by quota.
	QuotaBytes int64
	// MetadataBackup enables periodic standalone metadata snapshots in Backend.
	// Nil leaves scheduling to the embedding application.
	MetadataBackup *MetadataBackupConfig
	History        *HistoryConfig
}

Config is the shared storage configuration, independent of export protocol. The caller owns injected resources and must close the engine before them. Core supplies defaults and validates the final configuration before use.

type HistoryConfig added in v1.0.2

type HistoryConfig struct {
	MaxVersions  int
	MaxAge       time.Duration
	MaxBytes     int64
	Mode         string
	JournalBytes int64
	// JournalCodec is minlz (default) or raw. This only encodes local log
	// records; the selected backend chunk algorithm remains independent.
	JournalCodec string
}

HistoryConfig bounds optional PRE-operation versions. Mode="backend" (the default) synchronizes every write to backend. Mode="journal" appends local byte deltas, follows the ordinary fsync boundary, and requires Staging. JournalBytes bounds its local log separately from the raw cache (64 MiB by default). Nil Config.History leaves the original asynchronous path unchanged.

func (HistoryConfig) Normalize added in v1.0.2

func (h HistoryConfig) Normalize() (meta.HistoryRetention, error)

type MetadataBackupConfig

type MetadataBackupConfig struct {
	Interval  time.Duration
	Timeout   time.Duration
	Retention int
	Prefix    string
	TempDir   string
}

MetadataBackupConfig enables standalone binary metadata backups in Backend. Zero values select a five-minute interval, ten-minute timeout, seven retained images, the metadata/backups prefix and the system temporary directory.

type Option

type Option func(*Config)

Option updates a storage configuration before core.New starts its workers. Options apply from left to right after Config; the last setting wins. A list can be reused with any export, but injected resources keep their own ownership rules and a chunk.Store belongs to one live engine.

func WithCache

func WithCache(encoded *cache.Cache) Option

WithCache sets the engine's encoded-object disk cache. Nil supplies no cache; it does not clear a separate cache already configured directly on Chunks.

func WithChunkRetry

func WithChunkRetry(attempts int, backoff time.Duration) Option

WithChunkRetry sets retry defaults for a Store whose own retry fields are zero.

func WithChunkSize

func WithChunkSize(size int) Option

WithChunkSize selects the raw addressing window in bytes; zero uses the core default. Existing volumes require their original window size.

func WithChunking

func WithChunking(chunking chunk.ChunkingOptions) Option

WithChunking selects fixed or content-defined backend chunks for a new volume. Core normalizes the bounds and verifies them when reopening.

func WithChunks

func WithChunks(store *chunk.Store) Option

WithChunks injects the object store, codec, fallback and optional decoders. The option does not modify or copy the store; core initializes it once.

func WithDirectoryPageSize

func WithDirectoryPageSize(size int) Option

WithDirectoryPageSize bounds per-handle metadata pages for FUSE and Afero. Zero selects 256; the largest permitted page is 4096 entries.

func WithHistory added in v1.0.2

func WithHistory(history HistoryConfig) Option

WithHistory enables per-operation versions shared by all exports. Backend mode confirms every write remotely; journal mode follows the fsync boundary.

func WithMetadata

func WithMetadata(metadata meta.Options) Option

WithMetadata selects a bbolt or Pebble database which core.New opens and core.Close closes. Auto detects an existing database; a new path defaults to bbolt. This replaces an injected namespace without opening any resources here. The application must exclude other writers for the lifetime of the core.

func WithMetadataBackup

func WithMetadataBackup(backup MetadataBackupConfig) Option

WithMetadataBackup opts in to automatic backend snapshots. A zero config selects the backup defaults; the metadata engine must support snapshots.

func WithNamespace

func WithNamespace(namespace *meta.Namespace) Option

WithNamespace injects the authoritative metadata namespace.

func WithQuotaBytes

func WithQuotaBytes(size int64) Option

WithQuotaBytes limits logical file sizes; zero is unlimited.

func WithRead

func WithRead(read ReadConfig) Option

WithRead sets decoded caching and prefetch. ReadConfig{} disables both.

func WithStaging

func WithStaging(raw *writer.Store) Option

WithStaging sets the durable raw writeback cache. Nil selects direct backend writes; removing an existing raw cache requires draining its dirty data first.

func WithSyncBackend

func WithSyncBackend(enabled bool) Option

WithSyncBackend requires file syncs in every export to wait for backend persistence. False permits local durability when a raw cache is configured.

func WithWorkers

func WithWorkers(workers int) Option

WithWorkers selects local raw and background upload concurrency.

func WithWriteQueue

func WithWriteQueue(size int) Option

WithWriteQueue selects the bounded raw/encoding queue capacity.

func WithoutHistory added in v1.0.2

func WithoutHistory() Option

WithoutHistory disables future recording; retained versions remain readable.

func WithoutMetadataBackup

func WithoutMetadataBackup() Option

WithoutMetadataBackup disables a previously configured backup scheduler.

type ReadConfig

type ReadConfig struct {
	CacheBytes int64
	Workers    int
	Ahead      int
	// RawRefill asynchronously retains decoded backend data in the optional
	// raw SSD cache. Nil Config.Read enables it; explicit ReadConfig opts in.
	RawRefill bool
}

ReadConfig controls decoded caching and raw SSD refill. Nil in Config selects 128 MiB, four concurrent loads and four chunks of sequential read ahead. CacheBytes=0 disables this cache and read ahead. Ahead=0 disables only read ahead. The byte limit includes cached data and reserved raw load bytes; callers can retain returned slices until their read replies complete.

Jump to

Keyboard shortcuts

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