Varnish Fetch Processor (VFP) to support the brotli compression algorithm for responses fetched from backends.
Find a file
2025-09-15 16:44:41 +02:00
src build: Don't use vcs_vmod_version if not present 2025-08-26 10:12:30 +02:00
.clang-tidy CI: Introduce clang-tidy 2025-08-26 10:12:30 +02:00
.dir-locals.el Initial commit, passes simple encode tests. 2019-02-11 22:30:53 +01:00
.gitignore Ignore vsctool droppings 2025-09-15 16:44:41 +02:00
.gitlab-ci.yml CI: fix for Ubuntu 2025-08-26 10:12:30 +02:00
bootstrap Migrate to VCDK 2025-06-17 11:41:02 +02:00
configure.ac build: Don't use vcs_vmod_version if not present 2025-08-26 10:12:30 +02:00
CONTRIBUTING.rst Migrate to VCDK 2025-06-17 11:41:02 +02:00
INSTALL.rst Migrate to VCDK 2025-06-17 11:41:02 +02:00
LICENSE Standardize LICENSE 2022-12-01 16:13:07 +01:00
Makefile.am build: Don't use vcs_vmod_version if not present 2025-08-26 10:12:30 +02:00
README.rst Use $Restrict 2023-06-13 15:34:19 +02:00

..
.. NB:  This file is machine generated, DO NOT EDIT!
..
.. Edit ./vfp_brotli.vcc and run make instead
..

.. role:: ref(emphasis)

===========
vmod_brotli
===========

--------------------------------------------------
Varnish Fetch Processor for brotli de-/compression
--------------------------------------------------

:Manual section: 3


SYNOPSIS
========

::

  import brotli;

  # The built-in "unbr" filter decompresses brotli-encoded backend
  # responses with default parameters.
  sub vcl_backend_response {
  	if (beresp.http.Content-Encoding == "br") {
		set beresp.filters = "unbr";
	}
  }

  # The built-in "br" filter compresses backend responses with default
  # parameters.
  sub vcl_backend_response {
  	if (bereq.http.Accept-Encoding ~ "\bbr\b") {
		set beresp.filters = "br";
	}
  }

  # Create a brotli compression filter with custom parameters.
  new <obj> = brotli.encoder(STRING name, BYTES buffer, INT quality,
                             BOOL large_win, INT lgwin, ENUM mode)
  VOID <obj>.create_stats()

  # Create a brotli decompression filter with custom parameters.
  new <obj> = brotli.decoder(STRING name, BYTES buffer, BOOL large_win)
  VOID <obj>.create_stats()

  # VFP version
  STRING brotli.version()

  # encoder library version
  STRING brotli.encoder_version()

  # decoder library version
  STRING brotli.decoder_version()

DESCRIPTION
===========

VFP brotli is a Varnish Fetch Processor to support the brotli
compression algorithm for responses fetched from backends. The VFP
integrates Varnish with the `Google brotli library`_.

The Brotli Compressed Data Format is specified in `RFC 7932`_. Details
of the compression algorithm are beyond the scope of this manual; see
the RFC and library documentation for more information.

A VFP is technically similar to a Varnish Module (VMOD). In
particular, it must be installed against Varnish in the same way a
VMOD is installed; and as with a VMOD, a VCL source must instruct
Varnish to load the VFP using the ``import`` statement. But unlike a
VMOD, a VFP's primary purpose is not to extend the VCL language;
instead, a VFP creates filters for backend fetches that can be named
as strings in the space-separated list assigned to the VCL variable
``beresp.filters`` (see ``vcl(7)``).

VFP brotli always creates two filters named ``"br"`` and ``"unbr"``,
for compression and decompression respectively, with default
parameters for the compression algorithm::

  import brotli;
  
  # Use the built-in "br" filter for brotli compression with default
  # parameters, if the Accept-Encoding request header indicates that
  # brotli compression is accepted.
  sub vcl_backend_response {
  	if (bereq.http.Accept-Encoding ~ "\bbr\b") {
		set beresp.filters = "br";
	}
  }
  
  # Use the built-in "unbr" filter for brotli decompression with
  # default parameters, if the Content-Encoding response header
  # indicates that the response is compressed using brotli.
  sub vcl_backend_response {
  	if (beresp.http.Content-Encoding == "br") {
		set beresp.filters = "unbr";
	}
  }

Note that the content encoding type ``br`` has been standardized to
indicate brotli compression, for use in headers such as
``Content-Encoding`` and ``Accept-Encoding``.

Note also that ``beresp.filters`` may only be written or read in the
VCL subroutine ``vcl_backend_response``.

When a brotli filter appears in ``beresp.filters``, it is applied to
the incoming backend response body. The resulting response body is
passed to the client, and if the response is cached, then the body is
stored in the cache as it results from the filtering.

To use non-default settings for the compression algorithm, create an
``encoder`` or ``decoder`` object as specified below. The string
passed in the ``name`` parameter of the object constructor can be used
in a ``beresp.filters`` list, as with ``"br"`` and ``"unbr"``::

  import brotli;
  
  sub vcl_init {
	# Create a compression filter with a reduced quality level,
	# for faster processing, but larger compressed responses
	# (the default quality level is 11).
	new brQ10 = brotli.encoder("brQ10", quality=10);

	# Create a decompression filter that uses a 1MiB buffer
	# (the default buffer size is 32KiB).
	new unbr1M = brotli.decoder("unbr1M", buffer=1m);
  }

  sub vcl_backend_response {
  	# Use the custom compression filter defined above.
  	if (bereq.http.Accept-Encoding ~ "\bbr\b") {
		set beresp.filters = "brQ10";
	}

  	# Use the custom decompression filter.
	if (beresp.http.Content-Encoding == "br") {
		set beresp.filters = "unbr1M";
	}
  }

Parameter settings for the compression algorithm represent various
ways to affect the trade-off between speed of processing and the rate
of compression (how much compression reduces the size of an object).

The VFP always creates counter statistics, observable with a tool like
``varnishstat(1)``, for the standard ``"br"`` and ``"unbr"``
filters. You may also optionally create statistics for custom filters
created with the ``encoder`` and ``decoder`` constructors. See
`STATISTICS`_ below for details.

Compression and HTTP
--------------------

The brotli VFP interacts with the HTTP protocol (headers and response
codes) in much the same way that Varnish does with its built-in gzip
support:

* Compression filters (the built-in ``"br"`` filter, or a custom
  filter created from the ``encoder`` constructor) are not executed
  for a backend response that already has a ``Content-Encoding``
  header.

* Decompression filters (built-in ``"unbr"`` or a custom ``decoder``
  filter) are not executed unless the backend response has the
  ``Content-Encoding`` header set to ``br``.

* When a compression filter is applied, the VFP sets the
  ``Content-Encoding`` response header to ``br``; this header value
  may appear in a client response, and it may be cached with the
  response. The value ``Accept-Encoding`` is also added to the
  ``Vary`` response header.

* When a decompression filter is applied, the ``Content-Encoding``
  response header is removed.

* Any ``Content-Length`` response header fetched from the backend is
  removed -- Varnish may add a new ``Content-Length`` header in a
  client response, set to the changed size of the response body. When
  streaming is enabled, Varnish sends the client response for a fetch
  with chunked encoding (and hence with no ``Content-Length`` header).

* If the backend response has an ``ETag`` header, then the ``ETag``
  value is "weakened" (prefixed with ``W/``), for weak validation
  according to `RFC 7232`_ section 2.1. This is because the response
  after de-/compression is not byte-identical with the fetched
  response.

* The filters ignore partial responses to range requests (status 206
  for "Partial Content").

Note that (unlike gzip) brotli compression does not work together with
Edge Side Includes (ESI). See `LIMITATIONS`_ below for a discussion of
this issue, and of possible solutions with VCL.

.. _brotli.encoder():

new xencoder = brotli.encoder(STRING name, BYTES buffer, INT quality, BOOL large_win, INT lgwin, ENUM mode)
-----------------------------------------------------------------------------------------------------------

::

   new xencoder = brotli.encoder(
      STRING name,
      BYTES buffer=32768,
      INT quality=11,
      BOOL large_win=0,
      INT lgwin=22,
      ENUM {GENERIC, TEXT, FONT} mode=GENERIC
   )

Create a compression filter named ``name`` with custom parameters for
the brotli algorithm. The string given in ``name`` may then be used in
``beresp.filters``.

The default values for the parameters correspond to the defaults used
in the standard compression filter (so if you create a filter with all
defaults, it is functionally identical to the ``"br"`` filter).

The ``name`` MAY NOT be ``"br"`` or ``"unbr"``, or the same as any of
the standard filters built into Varnish: ``"esi"``, ``"esi_gzip"``,
``"gzip"``, ``"gunzip"`` or ``"testgunzip"``. The results are
undefined (and almost certainly not what you want) if you use a name
that is also used by another third-party VFP.

The parameters are:

* ``buffer`` (default 32KiB): Like the ``varnishd`` parameter
  ``gzip_buffer``, this is the size of the temporary internal buffer
  used for compression. As with ``gzip_buffer``, a buffer size that is
  too small results in more overhead, and if it is too large, then it
  probably wastes memory.

* ``quality`` (default 11): sets a compression level, where 0
  represents the fastest execution, and 11 represents the highest
  compression rate (smallest compressed result). ``quality`` MUST be
  in the range 0 to 11, inclusive.

* ``large_win`` (default ``false``): if ``true``, use Large Window
  Brotli, which may yield better results for response bodies larger
  than 16 MiB.  The Large Window algorithm differs from the standard
  algorithm; under certain circumstances, it may be necessary to use
  the Large Window setting for both compression and decompression.

* ``lgwin`` (default 22): set the size of the LZ77 sliding window used
  by the brotli algorithm.  The window size is (2 ^ ``lgwin`` - 16),
  and larger window sizes may result in better compression rates.
  ``lgwin`` MUST be in the range 10 to 24, inclusive.

* ``mode`` (default ``GENERIC``): provide a hint about the expected
  contents of the response body; the compression may benefit from
  optimizations based on assumptions about the content. Possible
  values are:

  * ``GENERIC``: no assumptions are made about the content

  * ``TEXT``: for UTF-8 formatted text

  * ``FONT``: for the WOFF 2.0 font format (the original application
    for brotli)

For more details about the parameters and their effects, see `RFC
7932`_ and the library documentation.

Example::

  import brotli;
  
  sub vcl_init {
	# Create a compression filter with a 1MiB buffer, optimized
	# for WOFF.
	new br_woff = brotli.encoder("br_woff", buffer=1m, mode=FONT);
  }

  sub vcl_backend_response {
  	# Use the custom filter for the WOFF media type.
  	if (beresp.http.Content-Type ~ "\bfont/woff2?\b") {
		set beresp.filters = "br_woff";
	}
  }

.. _xencoder.create_stats():

VOID xencoder.create_stats()
----------------------------

Create statistics, observable with a tool like ``varnishstat(1)``, for
the custom compression filter. These are the same as the counters
created for the standard ``"br"`` filter. See `STATISTICS`_ below for
details.

Restricted to: ``vcl_init``.

Example::

  import brotli;
  
  sub vcl_init {
	# Create a custom compression filter with stats.
	new mybr = brotli.encoder("mybr", buffer=64k);
	mybr.create_stats();
  }

.. _brotli.decoder():

new xdecoder = brotli.decoder(STRING name, BYTES buffer, BOOL large_win)
------------------------------------------------------------------------

::

   new xdecoder = brotli.decoder(
      STRING name,
      BYTES buffer=32768,
      BOOL large_win=0
   )

Create a decompression filter named ``name`` with custom parameters,
suitable for use in ``beresp.filters``.

As with the ``encoder`` object, the default values for the parameters
correspond to the defaults used in the standard ``"unbr"``
decompression filter.

Also as with ``encoder``, the ``name`` MAY NOT be ``"br"`` or
``"unbr"``, or the same as any of Varnish's standard filters. It
SHOULD NOT be the same as a name used by another third-party VFP.

The parameters are:

* ``buffer`` (default 32KiB): like the ``buffer`` parameter for the
  ``encoder`` object, this is the size of the temporary internal
  buffer used for decompression.

* ``large_win`` (default ``false``): if ``true``, use Large Window
  Brotli. As noted above, it may be necessary to use the Large Window
  setting for both compression and decompression.

Example::

  import brotli;
  
  sub vcl_init {
	# Create a decompression filter with a small buffer size.
	new unbr_small = brotli.decoder("unbr_small", buffer=1k);
  }

  sub vcl_backend_response {
  	# Use the custom filter when the URL begins with "/tiny"
  	if (bereq.url ~ "/tiny" && beresp.http.Content-Encoding ~ "br") {
		set beresp.filters = "unbr_tiny";
	}
  }

.. _xdecoder.create_stats():

VOID xdecoder.create_stats()
----------------------------

Create statistics for the custom decompression filter, like the
``.create_stats()`` method for ``encoder``. See `STATISTICS`_ below
for details.

As with ``encoder.create_stats()``, this method MAY NOT be called in
any VCL subroutine besides ``vcl_init``, otherwise VCL failure is invoked.

.. _brotli.encoder_version():

STRING encoder_version()
------------------------

Return the version string for the brotli encoder library.

Example::

  std.log("Using brotli encoder version: " + brotli.encoder_version());

.. _brotli.decoder_version():

STRING decoder_version()
------------------------

Return the version string for the brotli decoder library.

Example::

  std.log("Using brotli decoder version: " + brotli.decoder_version());

.. _brotli.version():

STRING version()
----------------

Return the version string for this VFP.

Example::

  std.log("Using VFP brotli version: " + brotli.version());

STATISTICS
==========

The VFP creates counters in the ``BROTLI.*`` namespace, which can be
read and monitored with a tool like ``varnishstat(1)``, or any other
client of the Varnish statistics API.

Counters for the built-in filters ``"br"`` and ``"unbr"`` are always
created, with names of the form ``BROTLI.br.*`` and
``BROTLI.unbr.*``. If you use the ``encoder`` and/or ``decoder``
objects to create filters with custom parameters, you may optionally
use the ``.create_stats()`` method for either object type to create
counters for the custom filters. If so, then these counters have names
of the form::

  BROTLI.<vcl_name>.<filter_name>.*

... where ``<vcl_name>`` is the name of the VCL configuration, and
``<filter_name>`` is the name of the filter as used in
``beresp.filters``.

The stats are:

* ``ops``: total number of de-/compression operations. Always incremented
  even when the filter does not make any changes, for example when a
  compression filter finds that a backend response already has a
  ``Content-Encoding`` header.

* ``in``: total number of input bytes processed by the filter

* ``out``: total number of ouput bytes produced by the filter

All three stats are counters, meaning that they are always monotonic
increasing, except when the Varnish worker process restarts and they
are reset to 0.

So these stats are always created when the VFP is imported:

* ``BROTLI.br.ops``
* ``BROTLI.br.in``
* ``BROTLI.br.out``
* ``BROTLI.unbr.ops``
* ``BROTLI.unbr.in``
* ``BROTLI.unbr.out``

And stats for custom filters are also created if you so choose.

The work of the VFP in individual request/response transactions can
also be monitored in the Varnish log, recorded with the ``VfpAcct``
tag (see ``vsl(7)``). By default, ``VfpAcct`` is not written to the
log; to see it, set the ``varnishd`` parameter ``vsl_mask`` to
``+VfpAcct``.

ERRORS
======

If errors are encountered during compression or decompression, they
are reported in the Varnish log with the tag ``FetchError`` (see
``vsl(7)``). The ``FetchError`` message for decompression errors
includes the error message from the brotli decoder library.

If the decoder reaches end-of-stream indicators, signaling a completed
decompression, but there are still additional bytes in the response
body, then the filter fails with the ``FetchError`` message "Junk
after brotli data".

The backend fetch fails when any VFP filter fails, which can lead to a
"503 Backend fetch failed" response from Varnish. When streaming is
enabled (i.e when the VCL variable ``beresp.do_stream`` variable is
``true``, which is the default), the error might not be detected until
after the response code and header have already been sent to the
client; then it is too late to change the response status. In such
cases, the client response body may be empty, and the network
connection to the client is closed.

REQUIREMENTS
============

The VFP currently requires the Varnish master branch since commit
``54af42d``.

The VFP also requires the `Google brotli library`_, see
`INSTALL.rst <INSTALL.rst>`_ in the source directory for details.

The VFP has been tested with version 1.0.5 of both the encoder and
decoder libraries.

If you are building the VFP from source, you will need development
versions of the brotli libraries. See `INSTALL.rst <INSTALL.rst>`_.

INSTALLATION
============

See `INSTALL.rst <INSTALL.rst>`_ in the source repository.

LIMITATIONS
===========

Memory and CPU usage for compression and decompression is largely
driven by the choice of parameters for the brotli algorithm. If you
need to limit resource consumption, consider using custom filters, and
adjusting the parameters as needed.

Memory used by the VFP, such as the temporary internal buffer and
other internal structures, is allocated from the heap, and hence is
limited by available virtual memory.

As noted above, brotli compression does not work together with Edge
Side Includes, or ESI includes, as gzip support does for standard
Varnish. If you are using ESI, then brotli-compressed backend
responses will have to be decompressed on fetch. Without any special
measures taken in VCL, client responses with ESI-included content will
have to be delivered uncompressed.

SEE ALSO
========

* varnishd(1)
* vcl(7)
* varnishstat(1)
* vsl(7)
* VMOD source repository: https://code.uplex.de/uplex-varnish/libvfp-brotli
* brotli library repository: https://github.com/google/brotli
* RFC 7932 (brotli specification): https://tools.ietf.org/html/rfc7932
* RFC 7232 (HTTP conditional requests, with the specification for weak
  validation): https://tools.ietf.org/html/rfc7232

COPYRIGHT
=========

::

  Copyright (c) 2019 UPLEX Nils Goroll Systemoptimierung
  All rights reserved
 
  Author: Geoffrey Simmons <geoffrey.simmons@uplex.de>
 
  See LICENSE
 

.. _Google brotli library: https://github.com/google/brotli

.. _RFC 7932: https://tools.ietf.org/html/rfc7932

.. _RFC 7232: https://tools.ietf.org/html/rfc7232