Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
29 changes: 29 additions & 0 deletions crates/client-api-messages/src/websocket/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand All @@ -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::<Compression>("\"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.
///
Expand Down
1 change: 1 addition & 0 deletions crates/core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 4 additions & 0 deletions crates/core/src/client/messages.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
),
}
}

Expand Down
11 changes: 10 additions & 1 deletion crates/core/src/subscription/websocket_building.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down Expand Up @@ -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");
}
6 changes: 6 additions & 0 deletions sdks/rust/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"

Expand Down
135 changes: 135 additions & 0 deletions sdks/rust/src/compression.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,32 @@ fn gzip_decompress(bytes: &[u8]) -> Result<Vec<u8>, io::Error> {
Ok(decompressed)
}

#[cfg(not(target_arch = "wasm32"))]
fn zstd_decompress(bytes: &[u8]) -> Result<Vec<u8>, 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<Vec<u8>, 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<Vec<u8>, 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<Cow<'_, [u8]>, WsError> {
Expand All @@ -34,6 +60,115 @@ pub(crate) fn decompress_server_message(raw: &[u8]) -> Result<Cow<'_, [u8]>, 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<u8> {
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");
}
}
4 changes: 4 additions & 0 deletions sdks/rust/src/db_connection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
29 changes: 29 additions & 0 deletions sdks/rust/src/websocket.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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"),
Expand Down Expand Up @@ -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));
}
}
}