diff --git a/Cargo.lock b/Cargo.lock index 46ec39663f4..c98db39d525 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7420,6 +7420,15 @@ dependencies = [ "winapi", ] +[[package]] +name = "ruzstd" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7c1c839d570d835527c9a5e4db7cb2198683a988cb9d7293fc8674e6bd58fc8" +dependencies = [ + "twox-hash", +] + [[package]] name = "ryu" version = "1.0.20" @@ -8446,6 +8455,7 @@ dependencies = [ "v8", "wasmtime", "wasmtime-internal-fiber", + "zstd 0.13.3", ] [[package]] @@ -8925,8 +8935,10 @@ dependencies = [ "native-tls", "once_cell", "prometheus", + "ruzstd", "shlex", "spacetimedb-client-api-messages", + "spacetimedb-core", "spacetimedb-data-structures", "spacetimedb-lib", "spacetimedb-metrics", @@ -8940,6 +8952,7 @@ dependencies = [ "wasm-bindgen", "wasm-bindgen-futures", "web-sys", + "zstd 0.13.3", ] [[package]] @@ -10292,6 +10305,12 @@ dependencies = [ "utf-8", ] +[[package]] +name = "twox-hash" +version = "2.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86a801b3cea342a06d468c8710662aa29e5e05e4f5c0d62f00bbb7f2ad7941c2" + [[package]] name = "typed-path" version = "0.12.3" diff --git a/Cargo.toml b/Cargo.toml index e1dfbb62909..ac21fad1d1f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -383,6 +383,7 @@ tikv-jemallocator = { version = "0.6.0", features = ["profiling", "stats"] } tikv-jemalloc-ctl = { version = "0.6.0", features = ["stats"] } jemalloc_pprof = { version = "0.8", features = ["symbolize", "flamegraph"] } zstd-framed = { version = "0.1.1", features = ["tokio"] } +zstd = "0.13.3" # Vendor the openssl we rely on, rather than depend on a # potentially very old system version. diff --git a/crates/client-api-messages/src/websocket/common.rs b/crates/client-api-messages/src/websocket/common.rs index c33b74b4b71..1d59f9ad7a0 100644 --- a/crates/client-api-messages/src/websocket/common.rs +++ b/crates/client-api-messages/src/websocket/common.rs @@ -42,6 +42,8 @@ pub enum Compression { Brotli, /// Compress using gzip if a certain size threshold was met. Gzip, + /// Opt in to Zstandard compression. Requires a server and client with Zstd support. + Zstd, } /// The tag recognized by the host and SDKs to mean no compression of a `ServerMessage`. @@ -53,6 +55,33 @@ pub const SERVER_MSG_COMPRESSION_TAG_BROTLI: u8 = 1; /// The tag recognized by the host and SDKs to mean gzip compression of a `ServerMessage`. pub const SERVER_MSG_COMPRESSION_TAG_GZIP: u8 = 2; +/// Standard Zstandard frame, negotiated through `compression=Zstd`. +/// Existing clients retain their selected codec and are never sent this tag. +pub const SERVER_MSG_COMPRESSION_TAG_ZSTD: u8 = 3; + +#[cfg(test)] +mod compression_tests { + use super::*; + + #[test] + fn zstd_opt_in_preserves_defaults_and_existing_tags() { + assert_eq!(Compression::default(), Compression::Brotli); + assert_eq!( + serde_json::from_str::("\"Zstd\"").unwrap(), + Compression::Zstd + ); + assert_eq!( + [ + SERVER_MSG_COMPRESSION_TAG_NONE, + SERVER_MSG_COMPRESSION_TAG_BROTLI, + SERVER_MSG_COMPRESSION_TAG_GZIP, + SERVER_MSG_COMPRESSION_TAG_ZSTD + ], + [0, 1, 2, 3] + ); + } +} + /// Websocket close code sent when a connection supplies a `session_id` /// which another live connection of the same identity still holds. /// diff --git a/crates/core/Cargo.toml b/crates/core/Cargo.toml index b89e55b3330..bf192828078 100644 --- a/crates/core/Cargo.toml +++ b/crates/core/Cargo.toml @@ -42,6 +42,7 @@ async-trait.workspace = true base64.workspace = true blake3.workspace = true brotli.workspace = true +zstd.workspace = true bytemuck.workspace = true bytes.workspace = true bytesize.workspace = true diff --git a/crates/core/src/client/messages.rs b/crates/core/src/client/messages.rs index 6999a3cd0da..2ab6ad6a218 100644 --- a/crates/core/src/client/messages.rs +++ b/crates/core/src/client/messages.rs @@ -115,6 +115,10 @@ fn finalize_binary_serialize_buffer( buffer.compress_with_tag(ws_common::SERVER_MSG_COMPRESSION_TAG_BROTLI, brotli_compress) } ws_v1::Compression::Gzip => buffer.compress_with_tag(ws_common::SERVER_MSG_COMPRESSION_TAG_GZIP, gzip_compress), + ws_v1::Compression::Zstd => buffer.compress_with_tag( + ws_common::SERVER_MSG_COMPRESSION_TAG_ZSTD, + crate::subscription::websocket_building::zstd_compress, + ), } } diff --git a/crates/core/src/subscription/websocket_building.rs b/crates/core/src/subscription/websocket_building.rs index 1edb6ba0962..87cca54c7a5 100644 --- a/crates/core/src/subscription/websocket_building.rs +++ b/crates/core/src/subscription/websocket_building.rs @@ -180,7 +180,8 @@ impl BuildableWebsocketFormat for ws_v1::BsatnFormat { let qu_len_would_have_been = bsatn::to_len(&qu).unwrap(); match decide_compression(qu_len_would_have_been, compression) { - ws_v1::Compression::None => ws_v1::CompressableQueryUpdate::Uncompressed(qu), + // Zstd is outer-message compression only. + ws_v1::Compression::None | ws_v1::Compression::Zstd => ws_v1::CompressableQueryUpdate::Uncompressed(qu), ws_v1::Compression::Brotli => { let bytes = bsatn::to_vec(&qu).unwrap(); let mut out = Vec::new(); @@ -230,3 +231,11 @@ pub fn gzip_compress(bytes: &[u8], out: &mut impl io::Write) { encoder.write_all(bytes).unwrap(); encoder.finish().expect("should be able to gzip compress `bytes`"); } + +pub(crate) fn zstd_compress(bytes: &[u8], out: &mut impl io::Write) { + // Zstd fast-2, with a checksum so clients can reject damaged frames. + let mut encoder = zstd::stream::write::Encoder::new(out, -2).expect("valid Zstd level"); + encoder.include_checksum(true).expect("enable Zstd checksum"); + encoder.write_all(bytes).expect("should be able to encode Zstd"); + encoder.finish().expect("should be able to finish Zstd frame"); +} diff --git a/sdks/rust/Cargo.toml b/sdks/rust/Cargo.toml index 7f1f24f6ff7..e89de78898b 100644 --- a/sdks/rust/Cargo.toml +++ b/sdks/rust/Cargo.toml @@ -62,8 +62,14 @@ tokio-tungstenite.workspace = true # native-tls 0.2.17 fails to compile with Rust 1.93.0 due non-exhaustive # matching in upstream code. Pin until upstream ships a compatible release. native-tls = "=0.2.14" +zstd.workspace = true + +[target.'cfg(target_arch = "wasm32")'.dependencies] +ruzstd = "0.8" [dev-dependencies] +spacetimedb-core.workspace = true +ruzstd = "0.8" futures-channel.workspace = true shlex = "1.3.0" diff --git a/sdks/rust/src/compression.rs b/sdks/rust/src/compression.rs index 591da11be34..affd5563837 100644 --- a/sdks/rust/src/compression.rs +++ b/sdks/rust/src/compression.rs @@ -16,6 +16,32 @@ fn gzip_decompress(bytes: &[u8]) -> Result, io::Error> { Ok(decompressed) } +#[cfg(not(target_arch = "wasm32"))] +fn zstd_decompress(bytes: &[u8]) -> Result, io::Error> { + zstd::stream::decode_all(bytes) +} + +// Browser targets must not depend on native libzstd. Also exercised on native +// test runs against frames produced by the same encoder as the server. +#[cfg(any(target_arch = "wasm32", test))] +fn zstd_decompress_portable(bytes: &[u8]) -> Result, io::Error> { + let mut decoder = ruzstd::decoding::StreamingDecoder::new(bytes).map_err(io::Error::other)?; + let mut output = Vec::new(); + decoder.read_to_end(&mut output)?; + // ruzstd exposes the stored/calculated checksums but does not compare them. + if let Some(expected) = decoder.decoder.get_checksum_from_data() + && decoder.decoder.get_calculated_checksum() != Some(expected) + { + return Err(io::Error::new(io::ErrorKind::InvalidData, "Zstd checksum mismatch")); + } + Ok(output) +} + +#[cfg(target_arch = "wasm32")] +fn zstd_decompress(bytes: &[u8]) -> Result, io::Error> { + zstd_decompress_portable(bytes) +} + /// Decompresses a `ServerMessage` encoded in BSATN into the raw BSATN /// for further deserialization. pub(crate) fn decompress_server_message(raw: &[u8]) -> Result, WsError> { @@ -34,6 +60,115 @@ pub(crate) fn decompress_server_message(raw: &[u8]) -> Result, WsE [ws::common::SERVER_MSG_COMPRESSION_TAG_GZIP, bytes @ ..] => { gzip_decompress(bytes).map(Cow::Owned).map_err(err_decompress("gzip")) } + [ws::common::SERVER_MSG_COMPRESSION_TAG_ZSTD, bytes @ ..] => { + zstd_decompress(bytes).map(Cow::Owned).map_err(err_decompress("zstd")) + } [c, ..] => Err(WsError::UnknownCompressionScheme { scheme: *c }), } } + +#[cfg(all(test, not(target_arch = "wasm32")))] +mod tests { + use super::*; + use std::io::Write; + + fn encode(bytes: &[u8]) -> Vec { + let mut encoder = zstd::stream::write::Encoder::new(Vec::new(), -2).unwrap(); + encoder.include_checksum(true).unwrap(); + encoder.write_all(bytes).unwrap(); + encoder.finish().unwrap() + } + + #[test] + fn zstd_frames_decode_on_native_and_portable_paths() { + let message = ws::v2::ServerMessage::SubscriptionError(ws::v2::SubscriptionError { + request_id: Some(7), + query_set_id: ws::common::QuerySetId::new(3), + error: "example error ".repeat(400000).into(), + }); + let bytes = spacetimedb_sats::bsatn::to_vec(&message).unwrap(); + let frame = encode(&bytes); + assert_eq!(zstd_decompress_portable(&frame).unwrap(), bytes); + let mut wire = vec![ws::common::SERVER_MSG_COMPRESSION_TAG_ZSTD]; + wire.extend_from_slice(&frame); + assert_eq!(decompress_server_message(&wire).unwrap().as_ref(), bytes); + let decoded = crate::websocket::WsConnection::parse_response(&wire).unwrap(); + assert_eq!(spacetimedb_sats::bsatn::to_vec(&decoded).unwrap(), bytes); + } + + #[test] + fn actual_server_frames_decode_in_the_sdk() { + use spacetimedb::client::{ + messages::{serialize_v2, SerializeBuffer}, + ClientConfig, WsVersion, + }; + use spacetimedb::subscription::row_list_builder_pool::BsatnRowListBuilderPool; + + let pool = BsatnRowListBuilderPool::new(); + for size in [32, 2048, 5 * 1024 * 1024] { + for compression in [ + ws::common::Compression::None, + ws::common::Compression::Brotli, + ws::common::Compression::Gzip, + ws::common::Compression::Zstd, + ] { + let message = ws::v2::ServerMessage::SubscriptionError(ws::v2::SubscriptionError { + request_id: Some(8), + query_set_id: ws::common::QuerySetId::new(4), + error: "a".repeat(size).into(), + }); + let expected = spacetimedb_sats::bsatn::to_vec(&message).unwrap(); + let config = ClientConfig { + compression, + version: WsVersion::V2, + ..ClientConfig::for_test() + }; + let (in_use, frame) = serialize_v2(&pool, SerializeBuffer::new(config), message, compression); + let decoded = crate::websocket::WsConnection::parse_response(&frame).unwrap(); + assert_eq!(spacetimedb_sats::bsatn::to_vec(&decoded).unwrap(), expected); + if frame[0] == ws::common::SERVER_MSG_COMPRESSION_TAG_ZSTD { + assert_eq!(zstd_decompress_portable(&frame[1..]).unwrap(), expected); + } + drop(frame); + assert!(in_use.try_reclaim().is_some()); + } + } + } + + #[test] + fn zstd_truncation_and_corruption_are_errors() { + let frame = encode(&vec![42; 1024 * 1024]); + for end in [0, 1, frame.len() / 2, frame.len() - 1] { + assert!(zstd_decompress(&frame[..end]).is_err()); + assert!(zstd_decompress_portable(&frame[..end]).is_err()); + } + let mut corrupted = frame; + *corrupted.last_mut().unwrap() ^= 1; + assert!(zstd_decompress(&corrupted).is_err()); + assert!(zstd_decompress_portable(&corrupted).is_err()); + let mut wire = vec![ws::common::SERVER_MSG_COMPRESSION_TAG_ZSTD]; + wire.extend_from_slice(&corrupted); + assert!(matches!( + decompress_server_message(&wire), + Err(WsError::Decompress { scheme: "zstd", .. }) + )); + } + + #[test] + fn legacy_tags_and_uncompressed_frames_still_work() { + assert!(matches!(decompress_server_message(&[]), Err(WsError::EmptyMessage))); + assert!(matches!( + decompress_server_message(&[255]), + Err(WsError::UnknownCompressionScheme { .. }) + )); + assert_eq!(decompress_server_message(&[0, 10, 20]).unwrap().as_ref(), &[10, 20]); + let mut brotli = vec![ws::common::SERVER_MSG_COMPRESSION_TAG_BROTLI]; + brotli::BrotliCompress(&mut &b"payload"[..], &mut brotli, &Default::default()).unwrap(); + assert_eq!(decompress_server_message(&brotli).unwrap().as_ref(), b"payload"); + let mut gzip = vec![ws::common::SERVER_MSG_COMPRESSION_TAG_GZIP]; + let mut encoder = flate2::write::GzEncoder::new(&mut gzip, flate2::Compression::fast()); + encoder.write_all(b"payload").unwrap(); + encoder.finish().unwrap(); + assert_eq!(decompress_server_message(&gzip).unwrap().as_ref(), b"payload"); + } +} diff --git a/sdks/rust/src/db_connection.rs b/sdks/rust/src/db_connection.rs index c1810f7e5dd..c3fe0312482 100644 --- a/sdks/rust/src/db_connection.rs +++ b/sdks/rust/src/db_connection.rs @@ -1090,6 +1090,10 @@ but you must call one of them, or else the connection will never progress. /// The current threshold used by the host is 1KiB for the entire server message /// and for individual query updates. /// Note however that this threshold is not guaranteed and may change without notice. + /// + /// Brotli is the default. [`Compression::Zstd`](ws::common::Compression::Zstd) + /// explicitly opts in to Zstandard and requires a server supporting that codec; + /// older servers reject this option rather than silently choosing another codec. pub fn with_compression(mut self, compression: ws::common::Compression) -> Self { self.params.compression = compression; self diff --git a/sdks/rust/src/websocket.rs b/sdks/rust/src/websocket.rs index 916748165fd..77b2d4c1215 100644 --- a/sdks/rust/src/websocket.rs +++ b/sdks/rust/src/websocket.rs @@ -185,6 +185,7 @@ fn make_uri_impl( match params.compression { ws::common::Compression::None => path.push_str("?compression=None"), ws::common::Compression::Gzip => path.push_str("?compression=Gzip"), + ws::common::Compression::Zstd => path.push_str("?compression=Zstd"), // The host uses the same default as the sdk, // but in case this changes, we prefer to be explicit now. ws::common::Compression::Brotli => path.push_str("?compression=Brotli"), @@ -647,3 +648,31 @@ impl WsConnection { (incoming_rx, outgoing_tx) } } + +#[cfg(test)] +mod compression_tests { + use super::*; + + #[test] + fn zstd_is_explicitly_negotiated_and_brotli_remains_default() { + for (compression, expected) in [ + (ws::common::Compression::Zstd, "compression=Zstd"), + (ws::common::Compression::default(), "compression=Brotli"), + (ws::common::Compression::None, "compression=None"), + (ws::common::Compression::Gzip, "compression=Gzip"), + ] { + let uri = make_uri_impl( + "https://localhost".parse().unwrap(), + "example", + None, + WsParams { + compression, + ..Default::default() + }, + None, + ) + .unwrap(); + assert_eq!(uri.query(), Some(expected)); + } + } +}