Skip to content

Commit 36a6e8e

Browse files
committed
Implement compression with Tower layer
1 parent d68cae7 commit 36a6e8e

File tree

4 files changed

+9
-46
lines changed

4 files changed

+9
-46
lines changed

Cargo.toml

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@ wasm-bindgen-cli-support = "0.2"
1818

1919
axum = { version = "0.5", default-features = false, features = ["http1", "headers"] }
2020
tokio = { version = "1.11", default-features = false, features = ["rt-multi-thread"] }
21-
tower-http = { version = "0.3", features = ["fs", "set-header", "trace"] }
21+
tower-http = { version = "0.3", features = ["compression-full", "fs", "set-header", "trace"] }
2222
tower = "0.4"
2323
fastrand = "1.5"
24-
flate2 = "1.0"

src/main.rs

Lines changed: 0 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
use std::path::PathBuf;
22

33
use anyhow::{anyhow, ensure};
4-
use tracing::info;
54
use tracing_subscriber::EnvFilter;
65

76
use crate::server::Options;
@@ -32,20 +31,8 @@ fn main() -> Result<(), anyhow::Error> {
3231

3332
let output = wasm_bindgen::generate(&wasm_file)?;
3433

35-
info!("compressed wasm output is {} large", pretty_size(output.compressed_wasm.len()));
36-
3734
let rt = tokio::runtime::Runtime::new()?;
3835
rt.block_on(server::run_server(options, output))?;
3936

4037
Ok(())
4138
}
42-
43-
fn pretty_size(size_in_bytes: usize) -> String {
44-
let size_in_kb = size_in_bytes as f32 / 1024.0;
45-
if size_in_kb < 1024.0 {
46-
return format!("{:.2}kb", size_in_kb);
47-
}
48-
49-
let size_in_mb = size_in_kb / 1024.0;
50-
return format!("{:.2}mb", size_in_mb);
51-
}

src/server.rs

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
11
use std::net::SocketAddr;
22

3-
use axum::headers::{ContentEncoding, HeaderName};
3+
use axum::headers::HeaderName;
44
use axum::http::{HeaderValue, StatusCode};
55
use axum::response::{Html, IntoResponse, Response};
66
use axum::routing::{get, get_service};
7-
use axum::{Router, TypedHeader};
7+
use axum::Router;
88
use tower::ServiceBuilder;
9+
use tower_http::compression::CompressionLayer;
910
use tower_http::services::ServeDir;
1011
use tower_http::set_header::SetResponseHeaderLayer;
1112

@@ -22,9 +23,10 @@ pub struct Options {
2223
}
2324

2425
pub async fn run_server(options: Options, output: WasmBindgenOutput) -> Result<()> {
25-
let WasmBindgenOutput { js, compressed_wasm } = output;
26+
let WasmBindgenOutput { js, wasm } = output;
2627

2728
let middleware_stack = ServiceBuilder::new()
29+
.layer(CompressionLayer::new())
2830
.layer(SetResponseHeaderLayer::if_not_present(
2931
HeaderName::from_static("cross-origin-opener-policy"),
3032
HeaderValue::from_static("same-origin"),
@@ -41,14 +43,10 @@ pub async fn run_server(options: Options, output: WasmBindgenOutput) -> Result<(
4143

4244
let serve_dir = get_service(ServeDir::new(".")).handle_error(internal_server_error);
4345

44-
let serve_wasm = || async move {
45-
(TypedHeader(ContentEncoding::gzip()), WithContentType("application/wasm", compressed_wasm))
46-
};
47-
4846
let app = Router::new()
4947
.route("/", get(move || async { Html(html) }))
5048
.route("/api/wasm.js", get(|| async { WithContentType("application/javascript", js) }))
51-
.route("/api/wasm.wasm", get(serve_wasm))
49+
.route("/api/wasm.wasm", get(|| async { WithContentType("application/wasm", wasm) }))
5250
.route("/api/version", get(move || async { version }))
5351
.fallback(serve_dir)
5452
.layer(middleware_stack);

src/wasm_bindgen.rs

Lines changed: 2 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,10 @@
11
use crate::Result;
2-
use anyhow::Context;
32
use std::path::Path;
43
use tracing::debug;
54

6-
const COMPRESSION_LEVEL: u32 = 2;
7-
85
pub struct WasmBindgenOutput {
96
pub js: String,
10-
pub compressed_wasm: Vec<u8>,
7+
pub wasm: Vec<u8>,
118
}
129
pub fn generate(wasm_file: &Path) -> Result<WasmBindgenOutput> {
1310
debug!("running wasm-bindgen...");
@@ -26,23 +23,5 @@ pub fn generate(wasm_file: &Path) -> Result<WasmBindgenOutput> {
2623
let wasm = output.wasm_mut().emit_wasm();
2724
debug!("emitting wasm took {:?}", start.elapsed());
2825

29-
debug!("compressing wasm...");
30-
let start = std::time::Instant::now();
31-
let compressed_wasm = compress(&wasm).context("failed to compress wasm file")?;
32-
debug!("compressing took {:?}", start.elapsed());
33-
34-
Ok(WasmBindgenOutput { js, compressed_wasm })
35-
}
36-
37-
fn compress(bytes: &[u8]) -> Result<Vec<u8>, std::io::Error> {
38-
use flate2::write::GzEncoder;
39-
use flate2::Compression;
40-
use std::io::prelude::*;
41-
42-
let mut encoder = GzEncoder::new(Vec::new(), Compression::new(COMPRESSION_LEVEL));
43-
44-
encoder.write_all(bytes)?;
45-
let compressed = encoder.finish()?;
46-
47-
Ok(compressed)
26+
Ok(WasmBindgenOutput { js, wasm })
4827
}

0 commit comments

Comments
 (0)