core

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Aug 11, 2026 License: MIT Imports: 23 Imported by: 0

Documentation

Overview

Package filex 提供自用对象存储核心引擎:本地盘后端、原子写入、 SHA256 完整性校验、对象元数据与分页枚举,错误语义统一走 errx, 日志与指标可注入 logx / metricsx 生态。

filex 不兼容 S3 / OSS / WebDAV 等第三方对象存储协议; 传输协议从 v0.2.0 起由 server / client 子包提供。

Index

Examples

Constants

View Source
const (
	CodeInvalidArgument    = errx.Code("filex_invalid_argument")
	CodeInvalidConfig      = errx.Code("filex_invalid_config")
	CodeInvalidBucket      = errx.Code("filex_invalid_bucket")
	CodeInvalidKey         = errx.Code("filex_invalid_key")
	CodeInvalidMetadata    = errx.Code("filex_invalid_metadata")
	CodeInvalidRange       = errx.Code("filex_invalid_range")
	CodeInternal           = errx.Code("filex_internal")
	CodeUnauthorized       = errx.Code("filex_unauthorized")
	CodeForbidden          = errx.Code("filex_forbidden")
	CodeNotModified        = errx.Code("filex_not_modified")
	CodePreconditionFailed = errx.Code("filex_precondition_failed")
	CodeCancelled          = errx.Code("filex_cancelled")
	CodeClosed             = errx.Code("filex_closed")
	CodeBucketExists       = errx.Code("filex_bucket_exists")
	CodeBucketNotFound     = errx.Code("filex_bucket_not_found")
	CodeBucketNotEmpty     = errx.Code("filex_bucket_not_empty")
	CodeObjectNotFound     = errx.Code("filex_object_not_found")
	CodeObjectTooLarge     = errx.Code("filex_object_too_large")
	CodeChecksumMismatch   = errx.Code("filex_checksum_mismatch")
	CodeMetadataCorrupt    = errx.Code("filex_metadata_corrupt")
	CodeStorageFailed      = errx.Code("filex_storage_failed")
	CodeUploadNotFound     = errx.Code("filex_upload_not_found")
	CodeUploadInvalid      = errx.Code("filex_upload_invalid")
	CodeUploadIncomplete   = errx.Code("filex_upload_incomplete")
	CodeVersionNotFound    = errx.Code("filex_version_not_found")
	CodeQuotaExceeded      = errx.Code("filex_quota_exceeded")
)

filex 错误码全集(统一前缀 filex_)。

Variables

This section is empty.

Functions

This section is empty.

Types

type BucketInfo

type BucketInfo struct {
	Name       string
	Versioning bool
	Quota      int64 // 0 表示不限
	Lifecycle  LifecycleOptions
	CreatedAt  time.Time
	UpdatedAt  time.Time
}

BucketInfo 是桶元数据快照。

type BucketStats

type BucketStats struct {
	ObjectCount  int
	VersionCount int
	Usage        int64
}

BucketStats 是桶统计快照。

type ByteRange

type ByteRange struct {
	Start int64
	End   int64
}

ByteRange 表示对象内容的字节范围(含端点)。

func (ByteRange) Length

func (r ByteRange) Length() int64

Length 返回范围长度。

type Config

type Config struct {
	// DataDir 是数据根目录(必填)。
	DataDir string
	// MaxObjectSize 是单对象大小上限;0 表示默认 4 GiB。
	MaxObjectSize int64
	// MaxKeyBytes 是键最大字节数;0 表示默认 1024。
	MaxKeyBytes int
	// MaxParts 是单次分片上传的部件数量上限;0 表示默认 10000。
	MaxParts int
	// UploadTTL 是分片会话保留时长;0 表示默认 24 小时。
	UploadTTL time.Duration
	// DisableSync 为 true 时跳过 fsync(默认 false,即默认落盘强一致)。
	DisableSync bool
	// EncryptionKey 是 32 字节主密钥;设置后启用服务端静态加密。
	EncryptionKey []byte
	// Logger 是可选结构化日志。
	Logger Logger
	// Metrics 是可选指标打点。
	Metrics Metrics
	// TraceHook 是可选链路追踪钩子。
	TraceHook TraceHook
	// EventHook 是可选事件钩子(默认 no-op),由 eventx 等外部适配器接入。
	EventHook EventHook
}

Config 是 Store 的配置。

type EventHook

type EventHook interface {
	// OnObjectEvent 在对象操作结束时调用。
	OnObjectEvent(ctx context.Context, e ObjectEvent)
}

EventHook 是可选事件钩子(默认 no-op)。 库本身不依赖任何事件总线实现,由 eventx 等外部适配器接入。

type GetOptions

type GetOptions struct {
	// Verify 为 true 时读取过程中流式复验 SHA256,EOF 处校验。
	Verify bool
	// Range 请求指定字节范围(含端点);与 Verify 互斥。
	Range *ByteRange
	// IfMatch 提供时仅当 ETag 匹配才返回内容(协议层使用)。
	IfMatch string
	// IfNoneMatch 提供时仅当 ETag 不匹配才返回内容(协议层使用)。
	IfNoneMatch string
}

GetOptions 是 Get 的选项。

type IntegrityReport

type IntegrityReport struct {
	Scanned int
	Corrupt int
	Errors  []string
}

IntegrityReport 是全量完整性审计报告。

type LifecycleOptions

type LifecycleOptions struct {
	ExpireDays  int // 0 表示不过期
	MaxVersions int // 0 表示不限制(仅版本化桶生效)
}

LifecycleOptions 是桶生命周期配置。

type LifecycleReport

type LifecycleReport struct {
	Scanned  int
	Expired  int
	Pruned   int
	Messages []string
}

LifecycleReport 是生命周期清理报告。

type ListOptions

type ListOptions struct {
	Prefix    string
	Marker    string // 排除字典序小于等于 marker 的键
	Limit     int    // 0 表示默认 1000,最大 10000
	Delimiter string // 通常为 "/",用于聚合公共前缀
}

ListOptions 是 List 的选项。

type ListResult

type ListResult struct {
	Objects        []ObjectInfo
	CommonPrefixes []string
	NextMarker     string
	IsTruncated    bool
}

ListResult 是 List 的结果。

type Logger

type Logger interface {
	Info(msg string, fields logx.FieldGroup)
	Warn(msg string, fields logx.FieldGroup)
	Error(msg string, fields logx.FieldGroup)
}

Logger 是 filex 使用的最小日志接口,logx.Logger 天然满足。

type Metrics

type Metrics = metricsx.Sink

Metrics 是 filex 的指标打点接口,可对接 metricsx。 Metrics 是最小指标协议(家族统一契约,定义见 metricsx.Sink)。

type Object

type Object struct {
	Info ObjectInfo
	io.ReadCloser
}

Object 是对象读取句柄:携带元数据快照与流式内容。

type ObjectEvent

type ObjectEvent struct {
	// Bucket 桶名。
	Bucket string
	// Key 对象键;List 等桶级操作为空。
	Key string
	// Action 操作类型:put / get / head / delete / list / copy / move。
	Action string
	// Err 操作结果错误;nil 表示成功。
	Err error
}

ObjectEvent 描述一次对象操作事件。

type ObjectInfo

type ObjectInfo struct {
	Bucket      string
	Key         string
	Size        int64
	ETag        string // 内容 SHA256 十六进制
	ContentType string
	Metadata    map[string]string
	VersionID   string
	Deleted     bool
	CreatedAt   time.Time
	UpdatedAt   time.Time
}

ObjectInfo 是对象元数据快照。

type PartInfo

type PartInfo struct {
	PartNumber int
	Size       int64
	SHA256     string
	UpdatedAt  time.Time
}

PartInfo 是已上传部件信息。

type PutOptions

type PutOptions struct {
	ContentType string
	Metadata    map[string]string
	// ExpectedSHA256 提供时写入前强制校验内容哈希(64 位十六进制)。
	ExpectedSHA256 string
}

PutOptions 是 Put 的选项。

type Store

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

Store 是本地盘对象存储引擎。

func New

func New(cfg Config) (*Store, error)

New 创建 Store。

func (*Store) AbortMultipartUpload

func (s *Store) AbortMultipartUpload(ctx context.Context, bucket, key, uploadID string) error

AbortMultipartUpload 中止并清理上传会话。

func (*Store) BucketStats

func (s *Store) BucketStats(ctx context.Context, bucket string) (BucketStats, error)

BucketStats 返回桶的对象数、版本数与字节用量(均不含删除标记)。

func (*Store) BucketUsage

func (s *Store) BucketUsage(ctx context.Context, bucket string) (int64, error)

BucketUsage 返回桶内非删除对象的字节总量(含全部版本)。

func (*Store) Close

func (s *Store) Close() error

Close 关闭 Store;关闭后所有操作返回 filex_closed。

func (*Store) CompleteMultipartUpload

func (s *Store) CompleteMultipartUpload(ctx context.Context, bucket, key, uploadID string) (ObjectInfo, error)

CompleteMultipartUpload 合并部件并提交对象;成功后删除会话。

func (*Store) Copy

func (s *Store) Copy(ctx context.Context, srcBucket, srcKey, dstBucket, dstKey string) (info ObjectInfo, err error)

Copy 复制对象(保留源内容类型与元数据)。

func (*Store) CreateBucket

func (s *Store) CreateBucket(ctx context.Context, name string) (BucketInfo, error)

CreateBucket 创建桶。

func (*Store) Delete

func (s *Store) Delete(ctx context.Context, bucket, key string) (err error)

Delete 删除对象。元数据先删,数据删除失败时交由孤儿清理。

func (*Store) DeleteBucket

func (s *Store) DeleteBucket(ctx context.Context, name string) error

DeleteBucket 删除空桶;存在对象时返回 filex_bucket_not_empty。

func (*Store) DeleteVersion

func (s *Store) DeleteVersion(ctx context.Context, bucket, key, versionID string) error

DeleteVersion 永久删除指定版本(含删除标记)。

func (*Store) Get

func (s *Store) Get(ctx context.Context, bucket, key string, opts GetOptions) (obj *Object, err error)

Get 读取对象;opts.Verify 开启时 EOF 复验 SHA256。

func (*Store) GetVersion

func (s *Store) GetVersion(ctx context.Context, bucket, key, versionID string, opts GetOptions) (*Object, error)

GetVersion 读取指定版本(删除标记返回 filex_object_not_found)。

func (*Store) Head

func (s *Store) Head(ctx context.Context, bucket, key string) (info ObjectInfo, err error)

Head 读取对象元数据,不打开内容。

func (*Store) HeadBucket

func (s *Store) HeadBucket(ctx context.Context, name string) (BucketInfo, error)

HeadBucket 读取桶元数据。

func (*Store) HeadVersion

func (s *Store) HeadVersion(ctx context.Context, bucket, key, versionID string) (ObjectInfo, error)

HeadVersion 查询指定版本元数据。

func (*Store) Health

func (s *Store) Health(ctx context.Context) error

Health 检查存储引擎可用性。

func (*Store) InitiateMultipartUpload

func (s *Store) InitiateMultipartUpload(ctx context.Context, bucket, key string, opts PutOptions) (UploadInfo, error)

InitiateMultipartUpload 创建分片上传会话。

func (*Store) List

func (s *Store) List(ctx context.Context, bucket string, opts ListOptions) (result ListResult, err error)

List 枚举对象,支持 prefix / marker / limit / delimiter。

func (*Store) ListBuckets

func (s *Store) ListBuckets(ctx context.Context) ([]BucketInfo, error)

ListBuckets 返回全部桶,按名称排序。

func (*Store) ListParts

func (s *Store) ListParts(ctx context.Context, bucket, key, uploadID string) ([]PartInfo, error)

ListParts 返回已上传部件列表(按部件号排序)。

func (*Store) ListVersions

func (s *Store) ListVersions(ctx context.Context, bucket, key string) ([]ObjectInfo, error)

ListVersions 枚举指定键的全部版本(新→旧),含删除标记。

func (*Store) Move

func (s *Store) Move(ctx context.Context, srcBucket, srcKey, dstBucket, dstKey string) (info ObjectInfo, err error)

Move 移动对象(复制成功后删除源)。

func (*Store) Put

func (s *Store) Put(ctx context.Context, bucket, key string, r io.Reader, opts PutOptions) (info ObjectInfo, err error)

Put 写入对象。同一键并发写时以后完成者生效(原子 rename 保证完整)。

Example
package main

import (
	"context"
	"fmt"
	"os"
	"strings"

	"github.com/lcylpzls/filex"
)

func main() {
	dir, _ := os.MkdirTemp("", "filex-example-*")
	defer os.RemoveAll(dir)
	store, err := filex.New(filex.Config{DataDir: dir})
	if err != nil {
		panic(err)
	}
	defer store.Close()

	ctx := context.Background()
	_, _ = store.CreateBucket(ctx, "demo")
	info, err := store.Put(ctx, "demo", "hello.txt",
		strings.NewReader("你好,filex"), filex.PutOptions{ContentType: "text/plain"})
	if err != nil {
		panic(err)
	}
	obj, err := store.Get(ctx, "demo", "hello.txt", filex.GetOptions{Verify: true})
	if err != nil {
		panic(err)
	}
	data := make([]byte, 0, info.Size)
	buf := make([]byte, 32)
	for {
		n, err := obj.Read(buf)
		data = append(data, buf[:n]...)
		if err != nil {
			break
		}
	}
	_ = obj.Close()
	fmt.Printf("内容:%s(%d 字节)\n", data, info.Size)
}
Output:
内容:你好,filex(14 字节)

func (*Store) RestoreVersion

func (s *Store) RestoreVersion(ctx context.Context, bucket, key, versionID string) (ObjectInfo, error)

RestoreVersion 将历史版本复制为新的当前版本。

func (*Store) RunLifecycle

func (s *Store) RunLifecycle(ctx context.Context, bucket string) (LifecycleReport, error)

RunLifecycle 执行过期删除与版本数收敛。

func (*Store) SetBucketLifecycle

func (s *Store) SetBucketLifecycle(ctx context.Context, bucket string, opts LifecycleOptions) (BucketInfo, error)

SetBucketLifecycle 设置桶生命周期配置。

func (*Store) SetBucketQuota

func (s *Store) SetBucketQuota(ctx context.Context, name string, quota int64) (BucketInfo, error)

SetBucketQuota 设置桶配额(0 表示不限)。

func (*Store) SetBucketVersioning

func (s *Store) SetBucketVersioning(ctx context.Context, name string, enabled bool) (BucketInfo, error)

SetBucketVersioning 开关桶版本化。

func (*Store) SweepOrphans

func (s *Store) SweepOrphans(ctx context.Context) (SweepReport, error)

SweepOrphans 巡检全部桶并清理孤儿数据与临时文件。

func (*Store) UploadPart

func (s *Store) UploadPart(ctx context.Context, bucket, key, uploadID string, partNumber int, r io.Reader) (PartInfo, error)

UploadPart 上传单个部件;同部件重复上传为幂等覆盖。

func (*Store) VerifyAll

func (s *Store) VerifyAll(ctx context.Context, concurrency int) (IntegrityReport, error)

VerifyAll 并发审计全部桶的当前对象与全部版本(跳过删除标记)。

func (*Store) VerifyObject

func (s *Store) VerifyObject(ctx context.Context, bucket, key string) error

VerifyObject 校验单个对象内容哈希。

type SweepReport

type SweepReport struct {
	Buckets         int
	RemovedData     int
	RemovedTmp      int
	RemovedDirs     int
	RemovedSessions int
}

SweepReport 是孤儿巡检报告。

type TraceAttr

type TraceAttr = contract.TraceAttr

TraceAttr 链路追踪属性(家族统一契约,定义见 tracex/contract)。

type TraceHook

type TraceHook = contract.TraceHook

TraceHook 链路追踪钩子(家族统一契约,定义见 tracex/contract)。

type UploadInfo

type UploadInfo struct {
	UploadID  string
	Bucket    string
	Key       string
	CreatedAt time.Time
}

UploadInfo 是分片上传会话信息。

Jump to

Keyboard shortcuts

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