Compress responses
Gzip response bodies for every route with the tower-http CompressionLayer in the pre-dispatch stage.
Large text responses leave the server gzipped when the client sends accept-encoding: gzip. CompressionLayer is a tower::Layer, so PreDispatch::layer takes it as it is.
The recipe builds on examples/17-http-pre-dispatch. It compiled and ran on port 0 against tower-http 0.7.1 with the compression-gzip feature.
tower-http = { version = "0.7", features = ["compression-gzip"] }The code
use tower_http::compression::CompressionLayer;
use ulo::{App, AppBuilder, Module, ModuleDef, ModuleIdentity, controller, handlers, module};
use ulo_http::PreDispatch;
pub struct CompressionModule;
impl Module for CompressionModule {
fn identity(&self) -> ModuleIdentity {
ModuleIdentity::of_type::<Self>()
}
fn register(&self, m: &mut ModuleDef<'_>) {
m.meta::<PreDispatch>().layer(CompressionLayer::new());
}
}
#[controller]
pub struct ReportController;
#[handlers]
impl ReportController {
#[ulo_http::get("/report")]
fn report(&self) -> String {
"row,total\n".repeat(500)
}
#[ulo_http::get("/tiny")]
fn tiny(&self) -> &'static str {
"ok"
}
}
#[module(imports = [CompressionModule], controllers = [ReportController])]
pub struct AppModule;
pub fn builder() -> AppBuilder {
App::builder(AppModule)
}What each seam does
CompressionLayer::new() wraps the whole stage. It reads accept-encoding from the request and adds vary: accept-encoding to the reply. Each encoding is a cargo feature of tower-http. The page enables gzip only.
Observed with curl against GET /report, a 5000-byte body:
| Request | Answer |
|---|---|
accept-encoding: gzip | content-encoding: gzip, transfer-encoding: chunked, no content-length, 58 bytes on the wire |
no accept-encoding | content-length: 5000, vary: accept-encoding |
accept-encoding: br | content-length: 5000, uncompressed |
accept-encoding: gzip on GET /tiny (2 bytes) | content-length: 2, uncompressed |
curl --compressed http://host/report received the full 5000-byte body.
Failure modes
An encoding the build lacks is ignored. The brotli request above got the plain body because only compression-gzip is enabled. Enable compression-br, compression-deflate or compression-zstd for the others.
A small body is sent as is. /tiny answered uncompressed. The default predicate skips a body under 32 bytes and the content types of gRPC, images and server-sent events (read in the tower-http source, only the size rule was run). An #[sse] route therefore streams unbuffered. A predicate with a higher threshold or other exclusions is set with CompressionLayer::new().compress_when(..).
The compressed reply has no content-length. The length of the encoded body is unknown when the head is written, so the reply is chunked. A proxy that wants a length must buffer.
Reference
- Middleware:
PreDispatch::layerand layer order. - Responses: what a handler returns.