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..9917808ba67 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, features = ["zstdmt"] } 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..fdf7043ecad 100644 --- a/crates/core/src/client/messages.rs +++ b/crates/core/src/client/messages.rs @@ -3,7 +3,7 @@ use crate::client::consume_each_list::ConsumeEachBuffer; use crate::host::module_host::{EventStatus, ModuleEvent, ProcedureCallError}; use crate::host::{ArgsTuple, ProcedureCallResult}; use crate::subscription::row_list_builder_pool::BsatnRowListBuilderPool; -use crate::subscription::websocket_building::{brotli_compress, decide_compression, gzip_compress}; +use crate::subscription::websocket_building::{decide_compression, gzip_compress}; use bytes::{BufMut, Bytes, BytesMut}; use bytestring::ByteString; use derive_more::From; @@ -83,13 +83,13 @@ impl SerializeBuffer { /// Compress the data from a `write_with_tag` call, and change the tag. fn compress_with_tag( - self, + mut self, tag: u8, - write: impl FnOnce(&[u8], &mut bytes::buf::Writer), + write: impl FnOnce(&mut BytesMut, &mut bytes::buf::Writer), ) -> (InUseSerializeBuffer, Bytes) { let mut writer = self.compressed.writer(); writer.get_mut().put_u8(tag); - write(&self.uncompressed[1..], &mut writer); + write(&mut self.uncompressed, &mut writer); let compressed = writer.into_inner().freeze(); let in_use = InUseSerializeBuffer::Compressed { uncompressed: self.uncompressed, @@ -111,10 +111,20 @@ fn finalize_binary_serialize_buffer( ) -> (InUseSerializeBuffer, Bytes) { match decide_compression(uncompressed_len, compression) { ws_v1::Compression::None => buffer.uncompressed(), - ws_v1::Compression::Brotli => { - buffer.compress_with_tag(ws_common::SERVER_MSG_COMPRESSION_TAG_BROTLI, brotli_compress) + ws_v1::Compression::Brotli => buffer.compress_with_tag( + ws_common::SERVER_MSG_COMPRESSION_TAG_BROTLI, + crate::compression::brotli_compress_frame, + ), + ws_v1::Compression::Gzip => { + buffer.compress_with_tag(ws_common::SERVER_MSG_COMPRESSION_TAG_GZIP, |frame, out| { + gzip_compress(&frame[1..], out); + }) + } + ws_v1::Compression::Zstd => { + buffer.compress_with_tag(ws_common::SERVER_MSG_COMPRESSION_TAG_ZSTD, |frame, out| { + crate::compression::zstd_compress(&frame[1..], out); + }) } - ws_v1::Compression::Gzip => buffer.compress_with_tag(ws_common::SERVER_MSG_COMPRESSION_TAG_GZIP, gzip_compress), } } diff --git a/crates/core/src/compression.rs b/crates/core/src/compression.rs new file mode 100644 index 00000000000..d452b73ac8e --- /dev/null +++ b/crates/core/src/compression.rs @@ -0,0 +1,334 @@ +//! Websocket compression CPU policy. Callers retain the existing encode +//! executor and release database transaction locks before compressing. +use crate::subscription::websocket_building::{brotli_compress, brotli_params}; +use bytes::{Bytes, BytesMut}; +use std::{ + io, + sync::{ + atomic::{AtomicUsize, Ordering}, + OnceLock, + }, +}; + +const BROTLI_MT_MIN_BYTES: usize = 512 * 1024; +const FOUR_THREADS_MIN_BYTES: usize = 64 * 1024 * 1024; +const ZSTD_LEVEL: i32 = -2; +const ZSTD_MT_MIN_BYTES: usize = 4 * 1024 * 1024; + +// Share half the available CPUs across MT jobs, rather than allowing just one +// job or creating an independent allowance per connection. Count coordinators +// as well as workers; synchronous encode work remains on the existing executor. +static MT_BUDGET: OnceLock = OnceLock::new(); + +struct MtBudget { + available: AtomicUsize, +} + +struct MtPermit<'a> { + budget: &'a MtBudget, + slots: usize, +} + +impl MtBudget { + const fn new(capacity: usize) -> Self { + Self { + available: AtomicUsize::new(capacity), + } + } + + /// Atomically reserve up to `desired` slots without waiting for capacity. + /// Fewer than two slots cannot run an MT job, so leave them unclaimed. + fn try_acquire(&self, desired: usize) -> Option> { + self.available + .fetch_update(Ordering::Acquire, Ordering::Relaxed, |free| { + let slots = desired.min(free); + (slots >= 2).then_some(free - slots) + }) + .ok() + .map(|free| MtPermit { + budget: self, + slots: desired.min(free), + }) + } +} + +impl Drop for MtPermit<'_> { + fn drop(&mut self) { + self.budget.available.fetch_add(self.slots, Ordering::Release); + } +} + +fn mt_cpu_budget(available: usize) -> usize { + available / 2 +} + +fn mt_budget(available: usize) -> &'static MtBudget { + // Initialize once from the CPU quota/affinity visible to the encode worker. + // A restart is required to change this capacity after CPU limits change. + MT_BUDGET.get_or_init(|| MtBudget::new(mt_cpu_budget(available))) +} + +fn thread_count(len: usize, minimum: usize, available: usize) -> usize { + if len < minimum { + return 1; + } + let desired = if len >= FOUR_THREADS_MIN_BYTES { 4 } else { 2 }; + desired.min(available.max(1)) +} + +fn available_threads() -> usize { + // Codec children inherit affinity. A pinned encode worker cannot safely + // assume access to the process's other reserved CPUs. + if cfg!(feature = "core-pinning") { + return 1; + } + std::thread::available_parallelism().map_or(1, |n| n.get()) +} + +struct SharedInput(Bytes); +impl brotli::SliceWrapper for SharedInput { + fn slice(&self) -> &[u8] { + &self.0 + } +} + +fn brotli_parallel(bytes: Bytes, threads: usize) -> io::Result> { + use brotli::enc::{ + compress_multi, BrotliEncoderMaxCompressedSizeMulti, Owned, SendAlloc, StandardAlloc, UnionHasher, + }; + let bound = BrotliEncoderMaxCompressedSizeMulti(bytes.len(), threads); + let mut out = Vec::new(); + out.try_reserve_exact(bound).map_err(io::Error::other)?; + out.resize(bound, 0); + let mut input = Owned::new(SharedInput(bytes)); + let mut allocators: Vec<_> = (0..threads) + .map(|_| SendAlloc::new(StandardAlloc::default(), UnionHasher::Uninit)) + .collect(); + let len = compress_multi(&brotli_params(), &mut input, &mut out, &mut allocators) + .map_err(|err| io::Error::other(format!("Brotli compression: {err:?}")))?; + out.truncate(len); + Ok(out) +} + +pub(crate) fn brotli_compress_frame(frame: &mut BytesMut, out: &mut impl io::Write) { + let len = frame.len() - 1; + if len < BROTLI_MT_MIN_BYTES { + brotli_compress(&frame[1..], out); + return; + } + let available = available_threads(); + let threads = thread_count(len, BROTLI_MT_MIN_BYTES, available); + if threads > 1 + && let Some(permit) = mt_budget(available).try_acquire(threads) + { + // Share the serialized body with the codec without reallocating it. + let input = std::mem::take(frame).freeze(); + let result = brotli_parallel(input.slice(1..), permit.slots); + *frame = input.try_into_mut().expect("Brotli must release shared input"); + match result { + Ok(compressed) => { + // Do not retain the MT API's maximum-sized allocation in the + // connection's reusable serialization buffer. + out.write_all(&compressed) + .expect("should be able to write Brotli output"); + return; + } + Err(err) => log::warn!("Parallel Brotli failed; retrying synchronously: {err}"), + } + } + brotli_compress(&frame[1..], out); +} + +fn zstd_worker_count(len: usize, available: usize) -> u32 { + if len < ZSTD_MT_MIN_BYTES { + return 0; + } + // Zstd counts additional workers, whereas Brotli counts all lanes. + let desired = if len >= FOUR_THREADS_MIN_BYTES { 4 } else { 2 }; + desired.min(available.saturating_sub(1)) as u32 +} + +fn zstd_encode(bytes: &[u8], out: &mut impl io::Write, workers: u32) { + use io::Write; + let mut encoder = zstd::stream::write::Encoder::new(out, ZSTD_LEVEL).expect("valid Zstd level"); + encoder.include_checksum(true).expect("enable Zstd checksum"); + if workers > 0 + && let Err(err) = encoder.multithread(workers) + { + log::warn!("Parallel Zstd unavailable; using synchronous compression: {err}"); + } + encoder.write_all(bytes).expect("should be able to encode Zstd"); + encoder.finish().expect("should be able to finish Zstd frame"); +} + +pub(crate) fn zstd_compress(bytes: &[u8], out: &mut impl io::Write) { + if bytes.len() < ZSTD_MT_MIN_BYTES { + zstd_encode(bytes, out, 0); + return; + } + let available = available_threads(); + let workers = zstd_worker_count(bytes.len(), available); + let permit = (workers > 0) + .then(|| mt_budget(available).try_acquire(workers as usize + 1)) + .flatten(); + let workers = permit.as_ref().map_or(0, |permit| (permit.slots - 1) as u32); + zstd_encode(bytes, out, workers); +} + +#[cfg(test)] +mod tests { + use super::*; + use std::io::Read; + + #[test] + fn parallel_thresholds_and_cpu_cap() { + assert_eq!(thread_count(BROTLI_MT_MIN_BYTES - 1, BROTLI_MT_MIN_BYTES, 8), 1); + assert_eq!(thread_count(BROTLI_MT_MIN_BYTES, BROTLI_MT_MIN_BYTES, 8), 2); + assert_eq!(thread_count(FOUR_THREADS_MIN_BYTES, BROTLI_MT_MIN_BYTES, 8), 4); + assert_eq!(thread_count(FOUR_THREADS_MIN_BYTES, BROTLI_MT_MIN_BYTES, 2), 2); + assert_eq!(thread_count(FOUR_THREADS_MIN_BYTES, BROTLI_MT_MIN_BYTES, 1), 1); + } + + #[test] + fn budget_is_nonblocking_and_released_on_unwind() { + let budget = MtBudget::new(8); + let other = budget.try_acquire(3).unwrap(); + let result = std::panic::catch_unwind(|| { + let permit = budget.try_acquire(5).unwrap(); + assert_eq!(permit.slots, 5); + assert!(budget.try_acquire(2).is_none()); + panic!("test permit cleanup"); + }); + assert!(result.is_err()); + assert_eq!(budget.available.load(Ordering::Relaxed), 5); + drop(other); + assert_eq!(budget.available.load(Ordering::Relaxed), 8); + } + + #[test] + fn budget_uses_half_available_cpus_and_keeps_small_machines_synchronous() { + for (cpus, slots) in [(0, 0), (1, 0), (2, 1), (3, 1), (4, 2), (5, 2), (32, 16), (64, 32)] { + assert_eq!(mt_cpu_budget(cpus), slots); + let budget = MtBudget::new(slots); + assert_eq!(budget.try_acquire(4).is_some(), slots >= 2); + } + } + + #[test] + fn multiple_jobs_share_slots_and_can_take_partial_allocations() { + let budget = MtBudget::new(mt_cpu_budget(32)); + let brotli = budget.try_acquire(4).unwrap(); + let zstd_a = budget.try_acquire(5).unwrap(); + let zstd_b = budget.try_acquire(5).unwrap(); + assert_eq!((brotli.slots, zstd_a.slots, zstd_b.slots), (4, 5, 5)); + let reduced_zstd = budget.try_acquire(5).unwrap(); + assert_eq!(reduced_zstd.slots, 2); // one worker plus the coordinator + assert!(budget.try_acquire(2).is_none()); + drop(brotli); + let replacement = budget.try_acquire(5).unwrap(); + assert_eq!(replacement.slots, 4); + drop((zstd_a, zstd_b, reduced_zstd, replacement)); + assert_eq!(budget.available.load(Ordering::Relaxed), 16); + + let permits: Vec<_> = (0..8).map(|_| budget.try_acquire(2).unwrap()).collect(); + assert!(budget.try_acquire(2).is_none()); + drop(permits); + assert_eq!(budget.available.load(Ordering::Relaxed), 16); + } + + #[test] + fn one_remaining_slot_is_not_consumed_by_an_mt_request() { + let budget = MtBudget::new(3); + let permit = budget.try_acquire(2).unwrap(); + assert!(budget.try_acquire(4).is_none()); + assert!(budget.try_acquire(1).is_none()); + assert!(budget.try_acquire(0).is_none()); + assert_eq!(budget.available.load(Ordering::Relaxed), 1); + drop(permit); + assert_eq!(budget.available.load(Ordering::Relaxed), 3); + } + + #[test] + fn concurrent_reservations_never_exceed_capacity() { + use std::sync::{Arc, Barrier}; + let budget = Arc::new(MtBudget::new(16)); + let start = Arc::new(Barrier::new(16)); + let active = Arc::new(AtomicUsize::new(0)); + let mut threads = Vec::new(); + for i in 0..16 { + let (budget, start, active) = (budget.clone(), start.clone(), active.clone()); + threads.push(std::thread::spawn(move || { + start.wait(); + for _ in 0..100 { + if let Some(permit) = budget.try_acquire(2 + i % 4) { + assert!((2..=2 + i % 4).contains(&permit.slots)); + let total = active.fetch_add(permit.slots, Ordering::SeqCst) + permit.slots; + assert!(total <= 16); + std::thread::yield_now(); + active.fetch_sub(permit.slots, Ordering::SeqCst); + } + } + })); + } + for thread in threads { + thread.join().unwrap(); + } + assert_eq!(active.load(Ordering::Relaxed), 0); + assert_eq!(budget.available.load(Ordering::Relaxed), 16); + } + + #[test] + fn brotli_sync_and_parallel_roundtrip() { + let input = Bytes::from((0..1024 * 1024).map(|i| (i % 251) as u8).collect::>()); + let mut sync = Vec::new(); + brotli_compress(&input, &mut sync); + for frame in [ + sync, + brotli_parallel(input.clone(), 2).unwrap(), + brotli_parallel(input.clone(), 3).unwrap(), + brotli_parallel(input.clone(), 4).unwrap(), + ] { + let mut decoded = Vec::new(); + brotli::Decompressor::new(frame.as_slice(), 4096) + .read_to_end(&mut decoded) + .unwrap(); + assert_eq!(decoded, input); + } + assert!(input.is_unique(), "MT must release all shared input references"); + } + + #[test] + fn zstd_workers_respect_size_and_cpu_budget() { + assert_eq!(zstd_worker_count(ZSTD_MT_MIN_BYTES - 1, 8), 0); + assert_eq!(zstd_worker_count(ZSTD_MT_MIN_BYTES, 8), 2); + assert_eq!(zstd_worker_count(FOUR_THREADS_MIN_BYTES, 8), 4); + assert_eq!(zstd_worker_count(FOUR_THREADS_MIN_BYTES, 2), 1); + assert_eq!(zstd_worker_count(FOUR_THREADS_MIN_BYTES, 1), 0); + assert_eq!(zstd_worker_count(FOUR_THREADS_MIN_BYTES, 0), 0); + } + + #[cfg(feature = "core-pinning")] + #[test] + fn pinned_builds_keep_codec_workers_disabled() { + assert_eq!(available_threads(), 1); + assert_eq!( + thread_count(FOUR_THREADS_MIN_BYTES, BROTLI_MT_MIN_BYTES, available_threads()), + 1 + ); + assert_eq!(zstd_worker_count(FOUR_THREADS_MIN_BYTES, available_threads()), 0); + } + + #[test] + fn zstd_sync_parallel_and_checksum_validation() { + let input: Vec<_> = (0..5 * 1024 * 1024).map(|i| (i % 251) as u8).collect(); + for workers in [0, 1, 2, 3, 4] { + let mut frame = Vec::new(); + zstd_encode(&input, &mut frame, workers); + assert_eq!(zstd::stream::decode_all(frame.as_slice()).unwrap(), input); + let end = frame.len() - 1; + assert!(zstd::stream::decode_all(&frame[..end]).is_err()); + frame[end] ^= 1; + assert!(zstd::stream::decode_all(frame.as_slice()).is_err()); + } + } +} diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 81a40406646..9b66f4783ad 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -13,6 +13,7 @@ pub use spacetimedb_lib::identity; pub use spacetimedb_sats::hash; pub mod callgrind_flag; pub mod client; +mod compression; pub mod config; pub mod database_logger; pub mod host; diff --git a/crates/core/src/subscription/websocket_building.rs b/crates/core/src/subscription/websocket_building.rs index 1edb6ba0962..075298f34dd 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(); @@ -211,18 +212,21 @@ pub fn decide_compression(len: usize, compression: ws_v1::Compression) -> ws_v1: } pub fn brotli_compress(bytes: &[u8], out: &mut impl io::Write) { + let params = brotli_params(); + let reader = &mut &bytes[..]; + brotli::BrotliCompress(reader, out, ¶ms).expect("should be able to BrotliCompress"); +} + +pub(crate) fn brotli_params() -> brotli::enc::BrotliEncoderParams { // We are optimizing for compression speed, // so we choose the lowest (fastest) level of compression. // Experiments on internal workloads have shown compression ratios between 7:1 and 10:1 // for large `SubscriptionUpdate` messages at this level. const COMPRESSION_LEVEL: i32 = 1; - - let params = brotli::enc::BrotliEncoderParams { + brotli::enc::BrotliEncoderParams { quality: COMPRESSION_LEVEL, - ..<_>::default() - }; - let reader = &mut &bytes[..]; - brotli::BrotliCompress(reader, out, ¶ms).expect("should be able to BrotliCompress"); + ..Default::default() + } } pub fn gzip_compress(bytes: &[u8], out: &mut impl io::Write) { 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)); + } + } +}