Skip to content
djylbPublic

About

Stream compression for ordered byte streams in Go: zstd and snappy engines, window and ratio limits, shared encoder pools.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

compress

Compression for ordered byte streams. compress.Codecs.Wrap takes a stream (a reader and writer with a half-close and an abort) and returns one that compresses what is written and decompresses what is read, with zstd or snappy, each direction on its own. Every Write is flushed before it returns. A receiver can retain codec state until it consumes the frame. The core uses only the standard library. Each codec is an engine in a module of its own.

go get github.com/djylb/compress
go get github.com/djylb/compress/zstd    # zstd engine
go get github.com/djylb/compress/snappy  # snappy engine

Usage

Make one Codecs per process and share it between all streams:

codecs, err := compress.NewCodecs(compress.Config{Low: compress.LowMemory(totalMemory)},
	zstd.Algorithm(), snappy.Algorithm())
if err != nil {
	return err
}

// On the deciding endpoint, read the peer offer and select once.
alg := codecs.Choose(configured, peerAlgs) // configured may be nil
// Send alg in the handshake. The other endpoint verifies it offered alg
// (or accepts None), then passes the received number to Wrap.
limits := compress.StreamLimits{PeerWindow: peerDeclaredWindow}

s, err := codecs.Wrap(stream, alg, nil, limits) // an empty prefix preserves identity for None

stream is any compress.Stream:

type Stream interface {
	io.Reader
	io.Writer
	Close() error
	CloseWrite() error      // FIN: ends the write direction
	Cancel(cause error)     // abort both directions
}

Bytes that were already read from the transport before the wrap are passed as prefix. Wrap copies and replays them for every algorithm. Invalid, truncated, over-window or over-ratio input makes Read return an error that wraps compress.ErrCorrupt, after the transport was cancelled with that error; transport errors pass through unchanged. A graceful Close waits for pending writes and the frame trailer. Use Cancel to interrupt it if the peer stops reading. Write reports plaintext accepted by the encoder or by complete framed writes. After a compressed write fails, CloseWrite still sends FIN if the write direction is open. Subsequent Write, CloseWrite and Close calls return the first write error. All Codecs methods are safe for concurrent use. See the Stream type documentation for the transport and wrapper concurrency contract.

Negotiation

Algs lists what a Codecs can decompress, in its order of preference (the order of registration; with the low-memory mode, the lean algorithm, snappy, first). Choose(want, peer) picks the algorithm of a stream: the first of want that both sides support, or, with want empty, the first lean algorithm of the peer's offer in the low-memory mode and otherwise the peer's first supported one; None when nothing is common. Common intersects several offers. The numbers Zstd (1) and Snappy (2) are the ones for your protocol to carry. The application protocol defines reserved numbers and extension ranges. If the deciding endpoint prefers zstd and the other prefers snappy, and both offer both, the deciding endpoint sends 1. Both endpoints then use zstd.

The zstd stream is a sequence of standard frames without checksums. Frames omit the content size except when the send window is below 1 KiB. Those single-segment frames use the content size as their window. Snappy output uses the snappy framing format. Frames from other encoders are read as well: skippable frames, single-segment frames and checksums are handled.

Limits and sweeping

NewCodecs takes the process-wide Config. Wrap takes a StreamLimits for that stream. Numeric fields take their defaults at zero. A negative value lifts the corresponding limit. All window fields use int64 and count bytes, with an implementation ceiling of 512 MiB.

Field Meaning Default
Config.Low Enable low-memory mode false
Config.Streams Number of frames that can hold an encoder at once 256, or 32 in low-memory mode
Config.MaxWindow Receive window to declare, at most 64 KiB in low mode 8 MiB, or 64 KiB in low-memory mode
Config.Idle Idle time before a zstd frame ends 1 s
StreamLimits.PeerWindow The peer's receive window, which bounds frames sent No peer limit
StreamLimits.RecvWindow Hard limit on the window of frames received codecs.DeclaredWindow()
StreamLimits.SendWindow Local window limit for frames sent 64 KiB
StreamLimits.MaxRatio Output beyond 16 MiB + input × ratio is an error 4096
StreamLimits.Idle Idle time for this stream Config.Idle

Declare codecs.DeclaredWindow() to the peer once per session. The peer passes it as its PeerWindow, and the receiver enforces the declared value on every zstd frame it reads. If a session declares a different value, pass it as RecvWindow on that receiver. Snappy uses 64 KiB plaintext chunks independently of session windows.

Positive idle durations round up to whole sweep periods, with a 50 ms minimum period. Negative Config.Idle disables idle frame ends and stall resets for all streams. Negative StreamLimits.Idle disables them for that stream. Start one sweeper per Codecs and cancel its context to stop it.

go codecs.RunSweeper(ctx, func(f func()) { go f() })

If the application already runs a periodic loop, call codecs.Sweep(spawn) every codecs.SweepPeriod(). Ending a frame writes to the stream and can wait for flow control. The sweeper hands each end to spawn, or runs it inline when spawn is nil. Sweep also resets a received frame that waits continuously on the transport for three rounded stream idle intervals (at least six sweep periods). Set the receiving idle interval to cover the peer's idle interval.

Memory

  • The zstd sender returns its encoder to the pool when it ends a frame. The receiver returns its decoder when it consumes the frame end. Codec pools are keyed by window size.
  • The snappy sender returns its chunk buffer after each write. A receiver keeps a partially read chunk until it delivers the remaining bytes or the stream is closed or cancelled.
  • At most Streams frames hold an encoder. The others send passthrough frames (stored zstd blocks, a few bytes per block, or uncompressed snappy chunks) until a slot is free. Available tells whether a new stream may take a slot now; Stats returns the encoders, open frames, receiving zstd streams and buffers out of the pool. The transport supplies read deadlines for incomplete Snappy chunks.
  • Adaptive skip: if the writes (Snappy chunks) through the first 64 KiB boundary compress to 95% or more of their size, the direction is passthrough for good. Receivers read passthrough frames like any others.
  • The low-memory mode (Config{Low: true}) prefers the lean algorithm, defaults to fewer encoders and declares a 64 KiB window. LowMemory(total) tells whether a machine with that much memory (0 = unknown) is below LowMemoryTotal (1 GiB), and MemLimit(total) suggests a soft memory limit for it (MemLimitPercent of the total). These helpers are advisory.

Engines

The core frames the data and manages windows, limits and pools; an engine only compresses. The interfaces are small:

type ZstdEngine interface {
	NewEncoder(window uint64) (ZstdEncoder, error) // fastest level, no checksum
	NewDecoder(maxWindow uint64) (ZstdDecoder, error)
}

type ZstdEncoder interface { // reusable: Reset starts a new frame
	io.Writer
	Reset(w io.Writer)
	Flush() error // ends a block: what was written so far is decodable
	Close() error // ends the frame
}

type ZstdDecoder interface { // over exactly one frame
	io.Reader
	Reset(r io.Reader) error // attach the input; defer reading it until Read
}

type SnappyEngine interface { // blocks of at most 64 KiB
	MaxEncodedLen(n int) int
	Encode(dst, src []byte) []byte
	DecodedLen(block []byte) (int, error)
	Decode(dst, block []byte) ([]byte, error)
}

Register an engine with compress.NewZstd(engine) or compress.NewSnappy(engine) and pass the result to NewCodecs. The modules github.com/djylb/compress/zstd and github.com/djylb/compress/snappy provide the engines; the zstd module also has EncodeFile and DecodeFile for whole files. The encoder writes one frame with a content size and checksum. The decoder enforces FileWindow and an output limit in bytes. A zero output limit uses DefaultFileLimit (64 MiB) and a negative one allows unlimited output.

Use zstd.EncodePatch(base, target) when the receiver already has the base file. Decode the patch with zstd.DecodePatch(reader, base, limit). A base dictionary ID mismatch returns zstd.ErrPatchBase. Patch frames carry the size and checksum of the target. The encoder returns nil for input beyond its codec window.

Layout and tests

The repository has four modules. The standard-library-only core is tested with fake engines. The two engine modules supply codecs, and the conformance module tests the real engines and their interoperability. Run GOWORK=off go test -race -count=1 -timeout 30s ./... in each module, or create an optional local workspace at the root and test all four together.

go work init . ./zstd ./snappy ./conformance
go test -race -count=1 -timeout 30s ./... ./zstd/... ./snappy/... ./conformance/...

License

Apache-2.0

About

Stream compression for ordered byte streams in Go: zstd and snappy engines, window and ratio limits, shared encoder pools.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages