files

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: 25 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/cluster/files 的 Client 实现共享 core.Access,FUSE、Afero 和块导出使用同一接入方式。Meta 控制调用走 WebSocket,文件数据走 HTTP,直连读取仍校验编码表示和原文 XXH3;网络错误不自动重放修改。

现有节点控制 RPC 也传递 Unix 路径 socket/FIFO 的类型、路径与属性;创建、改属性、改名和删除沿用相同授权及元数据确认。它们没有 chunk 数据句柄或 HTTP 传输计划。远程 FUSE 上的通信端点仍由当前客户端主机内核拥有,限同主机同挂载视图,不跨主机转发;元数据复制、备份和恢复不保存连接、监听状态或 FIFO 消息。Afero 只查询和管理这些节点元数据,NBD 仍使用普通文件镜像。详见使用边界。

Link 为同一命名空间的非目录 inode 增加名字;Unlink(parent,name) 与 RenameEntry(...) 修改实际目录项。 所有名字共用服务端 inode/DataFile,属性包含 Nlink,写入不复制数据;这些操作需要 writer 权限并遵守 direct lease 门禁。 删除或覆盖打开文件的最后链接仍返回 EBUSY,非最后链接的移除保留其他名字与句柄。完整备份保留名字表,历史按路径恢复使用新 inode。

兼容的 /v1/files/ HTTP 请求在用户门禁、排队和锁等待前绑定期限,取已验证 STS 到期时间与服务端 PlanTTL(默认 30 秒)的较早值。上传、下载和确认响应的 Flush 全程持有门禁;服务关闭、请求取消或超时会打断 socket 读写,释放所有权。写入结果未知时仍由调用方核对,客户端不会自动重放。

新客户端为 direct.read 和部分覆盖所需的 direct.begin 请求 grant_format=2。Meta 按相同文件版本、命名空间、卷、过期时间、Data 节点和磁盘 incarnation 分组,每张读取 STS 最多包含 256 个精确对象。128 个 CDC 叶子位于三个相同 Data 节点时,只签发三张票据。响应字典只保存每张票据一次,各叶子引用对应条目,避免反复复制整份授权对象列表。写入的 upload/attempt 票据继续逐次签发。

旧客户端未请求该格式时仍获得逐对象的 inline 票据;新客户端也接受旧服务端的 inline 响应。未知格式、越界字典引用或 Auth 失败均拒绝。反向代理需允许有界的多对象 STS 请求头,例如 Nginx 的 large_client_header_buffers 4 64k;TLS 继续由部署侧提供。

以下微基准使用 128 个唯一 CDC 叶子、RF3、热 bbolt placement 和真实 HMAC 票据。每次 issuer 调用人为等待 1ms;报告是控制计划生成开销、签票次数和响应大小,不代表跨机数据吞吐。

CGO_ENABLED=0 GOWORK=off go test ./fs/cluster/files -run '^$' \
  -bench '^BenchmarkDirectReadPlanIssuerRTT$' -benchtime=3x -count=3 -benchmem

Documentation

Overview

Package files exposes authoritative namespace cores over WebSocket control RPC and bounded HTTP file transfers, with an injected metadata authority gate.

Index

Constants

View Source
const DefaultMaxIO = 4 << 20
View Source
const NamespaceVersion = 14
View Source
const Version = 13

Variables

This section is empty.

Functions

func NewComputeHandler

func NewComputeHandler(cfg ComputeServerConfig) (cluster.RPCHandler, error)

NewComputeHandler issues bounded compute-only STS to volume writers. The caller's Members callback must exclude expired registry leases. Encoding remains an uncommitted computation; grants confer no data or namespace write.

Types

type Admission

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

Admission shares a bounded, work-conserving weighted FIFO scheduler across namespace services. A permit owns one request until its release function runs.

func NewAdmission

func NewAdmission(limit int) (*Admission, error)

func (*Admission) Acquire

func (a *Admission) Acquire(ctx context.Context, id string) (func(), error)

func (*Admission) Configure

func (a *Admission) Configure(id string, weight, limit int) error

type Client

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

func Dial

func Dial(ctx context.Context, cfg ClientConfig) (*Client, error)

func (*Client) ChunkSize

func (c *Client) ChunkSize() int

func (*Client) Close

func (c *Client) Close() error

func (*Client) Consistency

func (c *Client) Consistency() option.ConsistencyConfig

Consistency reports the normalized remote policy used for this session.

func (*Client) Create

func (c *Client) Create(ctx context.Context, parent uint64, name string, kind meta.Kind, mode, uid, gid uint32) (meta.Entry, error)

func (*Client) CreateData

func (c *Client) CreateData(ctx context.Context, parent uint64, name string, size int64) (core.DataFile, error)

func (*Client) CreateDevice

func (c *Client) CreateDevice(ctx context.Context, parent uint64, name string, kind meta.Kind, mode, uid, gid, rdev uint32) (meta.Entry, error)

func (*Client) DirectoryPageSize

func (c *Client) DirectoryPageSize() int

func (*Client) EnsureBlockGeometry

func (c *Client) EnsureBlockGeometry(ctx context.Context, inode uint64, size int64, readOnly bool) error

func (*Client) Format

func (c *Client) Format() fsformat.Volume

func (*Client) GetAttr

func (c *Client) GetAttr(ctx context.Context, inode uint64) (meta.Entry, error)

func (*Client) GetXattr

func (c *Client) GetXattr(ctx context.Context, inode uint64, name string) ([]byte, error)

Attribute names use byte fields on the wire, preserving non-UTF8 names.

func (*Client) HasWriteback

func (c *Client) HasWriteback() bool

func (*Client) HomeWriter

func (c *Client) HomeWriter() option.HomeWriter

HomeWriter reports the authority fence returned by the server volume handshake. It is useful to bind a caller's subsequent work to one home generation without exposing mutable client state.

func (*Client) IsRemote

func (c *Client) IsRemote() bool
func (c *Client) Link(ctx context.Context, inode, parent uint64, name string) (meta.Entry, error)

func (*Client) ListXattr

func (c *Client) ListXattr(ctx context.Context, inode uint64) ([]byte, error)

func (*Client) Lookup

func (c *Client) Lookup(ctx context.Context, parent uint64, name string) (meta.Entry, error)

func (*Client) MetadataCacheTTL

func (c *Client) MetadataCacheTTL() time.Duration

MetadataCacheTTL reports the explicitly configured bounded-stale lease for metadata queries. A zero result means strict metadata RPCs (or a client which has no cache). Export adapters may use this optional capability to align positive FUSE attribute/dentry leases with the same policy; it does not enable directory page caching or alter data I/O.

func (*Client) OpenData

func (c *Client) OpenData(ctx context.Context, inode uint64) (core.DataFile, error)

func (*Client) ReadDirectory

func (c *Client) ReadDirectory(ctx context.Context, parent uint64, cursor string, limit int) ([]meta.Entry, error)
func (c *Client) Readlink(ctx context.Context, inode uint64) (string, error)

func (*Client) Remove

func (c *Client) Remove(ctx context.Context, inode uint64) error

func (*Client) RemoveXattr

func (c *Client) RemoveXattr(ctx context.Context, inode uint64, name string) error

func (*Client) Rename

func (c *Client) Rename(ctx context.Context, inode, parent uint64, name string) error

func (*Client) RenameEntry

func (c *Client) RenameEntry(ctx context.Context, parent uint64, name string, newParent uint64, newName string) error

func (*Client) RenameEntryFlags

func (c *Client) RenameEntryFlags(ctx context.Context, parent uint64, name string, newParent uint64, newName string, flags meta.RenameFlags) error

func (*Client) RetainInode

func (c *Client) RetainInode(ctx context.Context, inode uint64) (core.InodeReference, error)

func (*Client) SetAttr

func (c *Client) SetAttr(ctx context.Context, inode uint64, a core.AttrUpdate) (meta.Entry, error)

func (*Client) SetXattr

func (c *Client) SetXattr(ctx context.Context, inode uint64, name string, value []byte, flags uint32) error
func (c *Client) Symlink(ctx context.Context, parent uint64, name, target string, uid, gid uint32) (meta.Entry, error)

func (*Client) Sync

func (c *Client) Sync(ctx context.Context) error

func (*Client) SyncMetadata

func (c *Client) SyncMetadata(ctx context.Context) error
func (c *Client) Unlink(ctx context.Context, parent uint64, name string, kind meta.UnlinkKind) error

func (*Client) VolumeID

func (c *Client) VolumeID() string

type ClientConfig

type ClientConfig struct {
	NamespaceID                                     string
	Server                                          string
	DataRoute                                       string
	ClusterID, NodeID, AccessKeyID, SecretAccessKey string
	HTTPClient                                      *http.Client
	Consistency                                     option.ConsistencyConfig
	// MetadataCache explicitly permits bounded-stale metadata reads. Nil keeps
	// every metadata query on the authoritative, gated RPC path.
	MetadataCache *MetadataCacheConfig
}

type ComputeMembers

type ComputeMembers struct {
	Version int              `json:"version"`
	Members []compute.Member `json:"members"`
	Policy  ComputePolicy    `json:"policy"`
}

type ComputePlan

type ComputePlan struct {
	Job         compute.Job         `json:"job"`
	Credentials cluster.Credentials `json:"credentials"`
}

type ComputePolicy

type ComputePolicy struct {
	MaxChunkBytes         int64         `json:"max_chunk_bytes"`
	MaxConcurrent         int           `json:"max_concurrent"`
	QueueDepth            int           `json:"queue_depth"`
	RemoteTimeout         time.Duration `json:"remote_timeout"`
	MinBytes              int64         `json:"min_bytes"`
	LocalBytesPerSecond   float64       `json:"local_bytes_per_second"`
	NetworkBytesPerSecond float64       `json:"network_bytes_per_second"`
	RoundTrip             time.Duration `json:"round_trip"`
	EstimatedRatio        float64       `json:"estimated_ratio"`
	ForceRemote           bool          `json:"force_remote"`
}

ComputePolicy contains scheduling estimates, never codec implementation or credential material. Zero fields retain codec/cluster defaults.

type ComputeServerConfig

type ComputeServerConfig struct {
	Authority *cluster.Authority
	Issue     cluster.Issuer
	Members   func() []compute.Member
	Policy    ComputePolicy
	TTL       time.Duration
}

type File

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

File is a server-owned handle. The server orders operations with all other handles of the same inode. Handle operations always use the server; the optional namespace metadata cache never hides a stale handle generation.

func (*File) Close

func (f *File) Close(ctx context.Context) error

func (*File) CloseLocal

func (f *File) CloseLocal(ctx context.Context) error

func (*File) Discard

func (f *File) Discard(ctx context.Context, off, size int64) error

func (*File) Flush

func (f *File) Flush(ctx context.Context) syscall.Errno

func (*File) Fsync

func (f *File) Fsync(ctx context.Context) syscall.Errno

func (*File) Inode

func (f *File) Inode() uint64

func (*File) Read

func (f *File) Read(ctx context.Context, p []byte, off int64) (core.ReadResult, syscall.Errno)

func (*File) ReadAt

func (f *File) ReadAt(ctx context.Context, p []byte, off int64) (int, error)

func (*File) Release

func (f *File) Release(ctx context.Context) syscall.Errno

func (*File) SetAttr

func (f *File) SetAttr(ctx context.Context, a core.AttrUpdate) (meta.Entry, error)

func (*File) Stat

func (f *File) Stat(ctx context.Context) (meta.Entry, error)

func (*File) Sync

func (f *File) Sync(ctx context.Context, backend bool) error

func (*File) Truncate

func (f *File) Truncate(ctx context.Context, size int64) error

func (*File) WriteAt

func (f *File) WriteAt(ctx context.Context, p []byte, off int64) (int, error)

type MetadataCacheConfig

type MetadataCacheConfig = option.MetadataCacheConfig

MetadataCacheConfig explicitly opts into bounded-stale remote metadata reads. It is shared with storage options; nil retains strict per-query authority RPC.

type MetadataState

type MetadataState struct {
	Consistency option.ConsistencyMode
	HomeEpoch   string
	MinSeq      uint64
}

MetadataState describes the metadata generation and committed position currently served by a namespace. The position must reflect the namespace's visible state, rather than a replica log which has not been published yet.

type Server

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

func NewServer

func NewServer(cfg ServerConfig) (*Server, error)

func (*Server) AddNamespace

func (s *Server) AddNamespace(id string, child *Server) error

AddNamespace publishes a fully initialized service. Ownership transfers only on success; the caller closes an unpublished child after any error.

func (*Server) Close

func (s *Server) Close(ctx context.Context) error

func (*Server) Quiesce

func (s *Server) Quiesce(ctx context.Context, capture func() error) error

Quiesce blocks control calls and HTTP mutations, drains mutable file owners, then runs capture. The callback may acquire the unified authority barrier.

func (*Server) ServeHTTP

func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)

func (*Server) SetNamespaceResolver

func (s *Server) SetNamespaceResolver(resolve func(context.Context, string) (*Server, error))

SetNamespaceResolver is called once before publishing the router.

type ServerConfig

type ServerConfig struct {
	// NamespaceID is derived from the authenticated identity, never a request path.
	NamespaceID string
	// Namespaces contains additional, independently owned file services. The
	// default service routes authenticated requests and owns their lifecycle.
	Namespaces         map[string]*Server
	ResolveNamespace   func(context.Context, string) (*Server, error)
	AuthorizePrincipal func(context.Context, cluster.Principal) error
	BeginPrincipal     func(context.Context, cluster.Principal) (func(), error)
	Admission          *Admission
	FileSystem         core.Access
	Store              *clusterstore.Store
	DataKeys           map[string]cluster.NodeKeys
	Encoder            string
	Gate               func(context.Context) error
	// ReadMetadataChanges is an immediate, bounded journal read. The caller
	// explicitly enables the namespace journal and owns its lifetime. Waiting
	// polls may invoke it without Gate for a private RAM-only change hint; only
	// freshly gated samples are delivered. It must not block or access storage.
	ReadMetadataChanges func(context.Context, meta.ChangeCursor, int) (meta.ChangePage, error)
	// MetadataCacheEpoch changes on authority term/activation transitions. A
	// random server-instance ID additionally fences service reconstruction.
	MetadataCacheEpoch func() string
	// MetadataState samples one coherent metadata position during each gated
	// volume handshake. The caller owns publication and durability; an error
	// rejects the handshake rather than advertising an older fallback state.
	MetadataState func(context.Context) (MetadataState, error)
	// HomeEpoch and MinSeq provide a static strict fence when MetadataState is
	// nil. Dynamic authority implementations should supply MetadataState.
	HomeEpoch                   string
	MinSeq                      uint64
	ClusterID, NodeID           string
	Keys                        map[string]cluster.Identity
	Authority                   *cluster.Authority
	Issue                       cluster.Issuer
	Authenticate                cluster.Authenticator
	MaxIO, MaxHandles, MaxPlans int
	PlanTTL, SessionTTL         time.Duration
	// Other handles node registration and discovery without exposing storage KV.
	Other   cluster.RPCHandler
	Compute cluster.RPCHandler
}

type Storage

type Storage interface {
	core.Access
	Close() error
}

Storage owns either a local core or its remote connection. Close it after all export adapters have stopped, before closing any injected local resources.

func Open

func Open(ctx context.Context, config option.Config, options ...option.Option) (Storage, error)

type VolumeInfo

type VolumeInfo struct {
	NamespaceID       string          `json:"namespace_id,omitempty"`
	Direct            bool            `json:"direct,omitempty"`
	Encoder           string          `json:"encoder,omitempty"`
	Version           int             `json:"version"`
	VolumeID          string          `json:"volume_id"`
	Format            fsformat.Volume `json:"format"`
	DirectoryPageSize int             `json:"directory_page_size"`
	HasWriteback      bool            `json:"has_writeback"`
	MaxIO             int             `json:"max_io"`
	NodeID            string          `json:"node_id"`
	MetadataChanges   bool            `json:"metadata_changes,omitempty"`
	// HomeEpoch and MinSeq fence clients to an authority generation and the
	// minimum committed sequence observed by this service.
	HomeEpoch string `json:"home_epoch,omitempty"`
	MinSeq    uint64 `json:"min_seq,omitempty"`
	// Consistency is the server's admission policy. Strict clients reject an
	// eventual server; an omitted value preserves the legacy strict policy.
	Consistency option.ConsistencyMode `json:"consistency,omitempty"`
}

Jump to

Keyboard shortcuts

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