codec

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

codec

codec 组合编码器和解码器,为 chunk store、FUSE、NBD 和独立 worker 提供统一 入口;同时负责 FPGA 适配、四核调度、健康状态、压缩预测和 CPU 回退。

codec/
  encoder/            编码接口、Stats 和算法实现
    gzip.go
    lz4.go
    zstd.go
    minlz.go
    raw.go
  decoder/            解码接口和算法实现
    gzip.go
    gzip_fixed.go     gzip 固定 Huffman 快速路径
    lz4.go
    zstd.go
    minlz.go
    raw.go
  worker/             独立算法进程、通信与进程监督
    client.go
    server.go
    process.go
  codec.go            组合接口、文件操作能力和 worker 诊断
  cpu.go              CPU 编码器与对应解码器的组合
  fpga*.go            FPGA 适配与调度
  multifpga*.go       多算法 FPGA 适配
  prediction.go       压缩预测策略

Codec 嵌入 encoder.Encoder 与 decoder.Decoder;codec.Stats 引用 encoder.Stats。算法实现只依赖标准库和各自的压缩库,编码与解码之间不互相依赖。 codec 导入 encoder 和 decoder,这两个子包不反向导入父包。 codec/worker 依赖 codec 来调用算法;codec 不导入 codec/worker。 这样可以独立使用算法与 worker,并避免循环依赖。

value, err := codec.NewGzip(1)
if err != nil {
    return err
}
stats, err := value.Encode(ctx, raw, encoded)
// 读回时按数据保存的格式选择 codec。
err = value.Decode(ctx, src, dst)

仅编码或仅解码的调用方可直接使用 encoder 或 decoder。CPU gzip 与 FPGA gzip 共用 decoder.Gzip; 解码器的选择由已存储的格式决定,与板卡当前固件分离。

Documentation

Overview

Package codec combines encoders and decoders for chunk storage and workers, and adapts FPGA scheduling and CPU fallback to the same interface.

Index

Constants

View Source
const MultiAlgorithmSDKAvailable = false

The published v0.0.2 SDK has no generic transport. Keep ordinary builds reproducible against that release; local SDK workers enable fpga_multialgo.

Variables

View Source
var ErrUnavailable = errors.New("codec unavailable")

Functions

This section is empty.

Types

type Codec

type Codec interface {
	encoder.Encoder
	decoder.Decoder
}

Codec compresses one bounded read-only raw chunk and decodes one stored chunk. The chunk boundary is deliberate: it gives FUSE random reads a bounded decode cost and lets the storage layer deduplicate by raw content hash.

type FPGA

type FPGA struct {
	Hardware fpgagzip.Hardware
	// OpenHardware optionally supplies a fresh XDMA handle for each chunk. The
	// current fpga-gzip pipeline closes its H2C/C2H streams when one bounded
	// transaction ends, so a reusable FUSE mount must open a new handle before
	// the next chunk. Hardware remains supported for callers that intentionally
	// own a one-shot or compatible reusable implementation.
	OpenHardware func() (fpgagzip.Hardware, error)
	Options      fpgagzip.Options
	Report       func(fpgagzip.Progress)
	// contains filtered or unexported fields
}

FPGA uses the fpga-gzip SDK for one complete chunk. The shell needs the chunk length before H2C starts, which is naturally available at this layer.

func (*FPGA) Decode

func (f *FPGA) Decode(ctx context.Context, src io.Reader, dst io.Writer) error

func (*FPGA) Encode

func (f *FPGA) Encode(ctx context.Context, raw []byte, dst io.Writer) (Stats, error)

func (*FPGA) Health

func (f *FPGA) Health() error

Health reports the first error that opened the FPGA circuit breaker. A nil error means the codec is currently allowed to submit work.

func (*FPGA) Name

func (f *FPGA) Name() string

func (*FPGA) ResetHealth

func (f *FPGA) ResetHealth()

ResetHealth re-enables FPGA submissions after the device has been reprogrammed or its XDMA streams have been repaired. It is safe to call while other goroutines are waiting in Encode.

type FPGAGroup

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

FPGAGroup schedules whole chunks on independent gzip cores. Each FPGA keeps its own transaction lock and circuit breaker; failed cores leave the group while healthy cores continue. A group must never share a stream/control bank.

func NewFPGAGroup

func NewFPGAGroup(cores ...*FPGA) (*FPGAGroup, error)

func (*FPGAGroup) Decode

func (*FPGAGroup) Decode(ctx context.Context, src io.Reader, dst io.Writer) error

func (*FPGAGroup) Encode

func (g *FPGAGroup) Encode(ctx context.Context, raw []byte, dst io.Writer) (Stats, error)

func (*FPGAGroup) Name

func (*FPGAGroup) Name() string

type Fallback

type Fallback struct {
	Primary  Codec
	Fallback Codec
}

Fallback retries into a private buffer so a failed primary codec cannot leave partial bytes in the caller's destination.

func (Fallback) Decode

func (f Fallback) Decode(ctx context.Context, src io.Reader, dst io.Writer) error

func (Fallback) Encode

func (f Fallback) Encode(ctx context.Context, raw []byte, dst io.Writer) (Stats, error)

func (Fallback) Name

func (f Fallback) Name() string

type FileDecoder

type FileDecoder interface {
	DecodeFile(ctx context.Context, source *os.File, rawSize int64, dst io.Writer) error
}

FileDecoder optionally decodes an immutable read-only file. The source's ownership and offset remain with the caller; rawSize is the exact expected output length. No bytes may reach dst before a complete validated result. ErrUnavailable requests the ordinary Decode path without consuming src/dst.

type FileEncoder

type FileEncoder interface {
	EncodeFile(ctx context.Context, source *os.File, dst io.Writer) (Stats, error)
}

FileEncoder optionally encodes an immutable read-only file without sending its entire input through an IPC byte stream. Offset and ownership are kept. A raw result may write no bytes and return Name="raw", RawSize=StoredSize= file size; callers retain the original bytes and must use that representation.

type FileResult

type FileResult struct {
	Stats Stats
	File  *os.File
}

func (*FileResult) Close

func (r *FileResult) Close() error

Close releases the owned temporary file and its name. Backend hard links survive this cleanup. It is safe to close a result more than once.

type FileResultEncoder

type FileResultEncoder interface {
	EncodeFileResult(ctx context.Context, source *os.File) (*FileResult, error)
}

FileResultEncoder returns a private immutable encoded file. The caller closes the result after its storage consumer completes. A raw result has no File and refers to the original input. ErrUnavailable requests the normal FileEncoder/Codec path without treating capability absence as an error.

type FirmwareIdentity

type FirmwareIdentity struct {
	Algorithm string
	Cores     int
	Build     uint64
}

type Gzip

type Gzip encoder.Gzip

Gzip combines the gzip encoder and decoder for chunk-store and worker use. Encoder state stays in encoder.Gzip, including Level and its bounded pool.

func NewGzip

func NewGzip(level int) (*Gzip, error)

func (*Gzip) Decode

func (*Gzip) Decode(ctx context.Context, src io.Reader, dst io.Writer) error

func (*Gzip) Encode

func (g *Gzip) Encode(ctx context.Context, raw []byte, dst io.Writer) (Stats, error)

func (*Gzip) Name

func (*Gzip) Name() string

type LZ4

type LZ4 encoder.LZ4

LZ4 combines the standard frame encoder and decoder.

func (LZ4) Decode

func (LZ4) Decode(ctx context.Context, src io.Reader, dst io.Writer) error

func (LZ4) Encode

func (l LZ4) Encode(ctx context.Context, raw []byte, dst io.Writer) (Stats, error)

func (LZ4) Name

func (LZ4) Name() string

type MinLZ

type MinLZ encoder.MinLZ

MinLZ combines the MinLZ encoder and decoder. Do not copy after first use.

func NewMinLZ

func NewMinLZ(level int) (*MinLZ, error)

func (*MinLZ) Decode

func (m *MinLZ) Decode(ctx context.Context, src io.Reader, dst io.Writer) error

func (*MinLZ) Encode

func (m *MinLZ) Encode(ctx context.Context, raw []byte, dst io.Writer) (Stats, error)

func (*MinLZ) Name

func (*MinLZ) Name() string

type MultiFPGA

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

MultiFPGA follows versioned images without binding a mount's decoder to the current image. A switch or hardware failure falls back to the same CPU format; auto uses the last observed format (gzip before the first successful probe). Failed cores are disabled for that build and re-enabled by a new image ID.

func NewMultiFPGA

func NewMultiFPGA(options MultiFPGAOptions) (*MultiFPGA, error)

func (*MultiFPGA) Decode

func (m *MultiFPGA) Decode(ctx context.Context, src io.Reader, dst io.Writer) error

func (*MultiFPGA) Encode

func (m *MultiFPGA) Encode(ctx context.Context, raw []byte, dst io.Writer) (Stats, error)

func (*MultiFPGA) Name

func (m *MultiFPGA) Name() string

func (*MultiFPGA) WithAlgorithm

func (m *MultiFPGA) WithAlgorithm(algorithm string) (*MultiFPGA, error)

WithAlgorithm selects a format while retaining the same core leases and health state. All aliases for one card in a worker must share this state: fpga-auto and fpga-lz4 can otherwise target the same DMA core concurrently.

type MultiFPGAOptions

type MultiFPGAOptions struct {
	Algorithm    string // gzip/lz4/zstd/minlz/raw, or auto to follow the loaded image
	UserDevice   string
	Cores        int
	OpenHardware func(core int) (fpgagzip.Hardware, error)
	BeforeOpen   func() error
	Options      fpgagzip.Options
	CPU          map[string]Codec
}

type Prediction

type Prediction struct {
	Checked     bool
	Skip        bool
	SampleBytes int64
	Nanos       int64
	Ratio       float64
	Entropy     float64
}

Prediction describes one chunk, never a permanent classification of a file. A false positive only forgoes compression; the original bytes are retained.

type PredictionMetrics

type PredictionMetrics struct {
	Mode          string  `json:"mode"`
	Checks        int64   `json:"checks"`
	RawBytes      int64   `json:"raw_bytes"`
	SampleBytes   int64   `json:"sample_bytes"`
	Nanos         int64   `json:"nanos"`
	SkippedChunks int64   `json:"skipped_chunks"`
	SkippedBytes  int64   `json:"skipped_bytes"`
	Errors        int64   `json:"errors"`
	LastRatio     float64 `json:"last_ratio,omitempty"`
	LastEntropy   float64 `json:"last_entropy,omitempty"`
}

PredictionMetrics counts successful RPCs observed by this mount, including across worker replacements. It does not include other mounts sharing a worker.

type PredictionOptions

type PredictionOptions struct {
	Mode             string  `json:"mode"`
	SampleBytes      int     `json:"sample_bytes"`
	DeflateRatio     float64 `json:"deflate_ratio"`
	EntropyThreshold float64 `json:"entropy_threshold"`
}

PredictionOptions controls a bounded content precheck. Ratios are sample output/input: 0.94 requires an estimated saving greater than six percent.

func DefaultPredictionOptions

func DefaultPredictionOptions() PredictionOptions

type Predictor

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

Predictor uses only Go code and reuses sample/Deflate buffers between chunks. A nil predictor disables the precheck.

func NewPredictor

func NewPredictor(options PredictionOptions) (*Predictor, error)

func (*Predictor) Options

func (p *Predictor) Options() PredictionOptions

func (*Predictor) Predict

func (p *Predictor) Predict(ctx context.Context, raw []byte) (result Prediction, err error)

type Raw

type Raw encoder.Raw

Raw combines the byte-for-byte encoder and decoder for uncompressed chunks.

func (Raw) Decode

func (Raw) Decode(ctx context.Context, src io.Reader, dst io.Writer) error

func (Raw) Encode

func (r Raw) Encode(ctx context.Context, raw []byte, dst io.Writer) (Stats, error)

func (Raw) Name

func (Raw) Name() string

type Stats

type Stats = encoder.Stats

type WorkerStatus

type WorkerStatus struct {
	PID                int                `json:"pid"`
	Socket             string             `json:"socket"`
	Version            string             `json:"version"`
	Protocol           int                `json:"protocol"`
	Retries            int64              `json:"retries"`
	LastCodec          string             `json:"last_codec,omitempty"`
	CPUFallbacks       int64              `json:"cpu_fallbacks"`
	Prediction         *PredictionMetrics `json:"prediction,omitempty"`
	FileRequests       int64              `json:"file_requests"`
	FileBytes          int64              `json:"file_bytes"`
	FileFallbacks      int64              `json:"file_fallbacks"`
	FileOutputRequests int64              `json:"file_output_requests"`
	FileOutputBytes    int64              `json:"file_output_bytes"`
	FileDecodeRequests int64              `json:"file_decode_requests"`
	FileDecodeBytes    int64              `json:"file_decode_bytes"`
}

WorkerStatus describes the process serving a remote codec. It is diagnostic state only; chunk refs retain their encoding names independently of workers.

type Zstd

type Zstd encoder.Zstd

Zstd combines the Zstandard encoder and decoder. Level only affects encoding.

func NewZstd

func NewZstd(level int) (*Zstd, error)

func (*Zstd) Decode

func (z *Zstd) Decode(ctx context.Context, src io.Reader, dst io.Writer) error

func (*Zstd) Encode

func (z *Zstd) Encode(ctx context.Context, raw []byte, dst io.Writer) (Stats, error)

func (*Zstd) Name

func (*Zstd) Name() string

Directories

Path Synopsis
Package cluster schedules bounded chunk compression over HTTP, independently of storage.
Package cluster schedules bounded chunk compression over HTTP, independently of storage.
Package decoder implements pure Go chunk decoders independently of storage, worker protocols, and the corresponding encoders.
Package decoder implements pure Go chunk decoders independently of storage, worker protocols, and the corresponding encoders.
Package encoder implements pure Go chunk encoders independently of storage, worker protocols, and the corresponding decoders.
Package encoder implements pure Go chunk encoders independently of storage, worker protocols, and the corresponding decoders.
Package worker runs chunk codecs in an independently updatable process.
Package worker runs chunk codecs in an independently updatable process.

Jump to

Keyboard shortcuts

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