Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

encode: Add zstd compression level support #6140

Merged
merged 10 commits into from
Apr 16, 2024
37 changes: 35 additions & 2 deletions modules/caddyhttp/encode/zstd/zstd.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,12 @@ func init() {
}

// Zstd can create Zstandard encoders.
type Zstd struct{}
type Zstd struct {
// List of all available levels: fastest, default, better, best
Level string `json:"level,omitempty"`
// Compression level refer to type constants value from zstd.SpeedFastest to zstd.SpeedBestCompression
WeidiDeng marked this conversation as resolved.
Show resolved Hide resolved
level zstd.EncoderLevel
}

// CaddyModule returns the Caddy module information.
func (Zstd) CaddyModule() caddy.ModuleInfo {
Expand All @@ -39,6 +44,27 @@ func (Zstd) CaddyModule() caddy.ModuleInfo {

// UnmarshalCaddyfile sets up the handler from Caddyfile tokens.
func (z *Zstd) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
d.Next() // consume option name
if !d.NextArg() {
return nil
}
levelStr := d.Val()
if ok, _ := zstd.EncoderLevelFromString(levelStr); !ok {
return d.Errf("unexpected compression level, use one of '%s', '%s', '%s', '%s'",
zstd.SpeedFastest,
zstd.SpeedDefault,
zstd.SpeedBetterCompression,
zstd.SpeedBestCompression,
)
}

z.Level = levelStr
return nil
}

// Provision provisions z's configuration.
func (z *Zstd) Provision(ctx caddy.Context) error {
_, z.level = zstd.EncoderLevelFromString(z.Level)
mholt marked this conversation as resolved.
Show resolved Hide resolved
return nil
}

Expand All @@ -51,12 +77,19 @@ func (z Zstd) NewEncoder() encode.Encoder {
// The default of 8MB for the window is
// too large for many clients, so we limit
// it to 128K to lighten their load.
writer, _ := zstd.NewWriter(nil, zstd.WithWindowSize(128<<10), zstd.WithEncoderConcurrency(1), zstd.WithZeroFrames(true))
writer, _ := zstd.NewWriter(
nil,
zstd.WithWindowSize(128<<10),
zstd.WithEncoderConcurrency(1),
zstd.WithZeroFrames(true),
zstd.WithEncoderLevel(z.level),
)
return writer
}

// Interface guards
var (
_ encode.Encoding = (*Zstd)(nil)
_ caddyfile.Unmarshaler = (*Zstd)(nil)
_ caddy.Provisioner = (*Zstd)(nil)
)
Loading