Skip to main content

djs_gateway/
compression.rs

1//! Transport compression.
2
3use std::io;
4
5/// Transport compression applied by Discord to everything it sends on the connection.
6///
7/// See [transport compression](https://docs.discord.com/developers/events/gateway#transport-compression).
8///
9/// discord.js counterpart: `CompressionMethod` (`@discordjs/ws`).
10#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
11#[non_exhaustive]
12pub enum Compression {
13    /// No compression: payloads arrive as WebSocket text messages. The default when no
14    /// compression feature is enabled.
15    #[cfg_attr(not(any(feature = "zstd-stream", feature = "zlib-stream")), default)]
16    None,
17    /// `zstd-stream`: one zstd decompression context for the whole connection (the default
18    /// with the `zstd-stream` feature).
19    ///
20    /// Typically reduces gateway bandwidth by 80–90 %.
21    #[cfg(feature = "zstd-stream")]
22    #[cfg_attr(feature = "zstd-stream", default)]
23    ZstdStream,
24    /// `zlib-stream`: one zlib inflate context for the whole connection, decoded with the
25    /// pure-Rust `zlib-rs` (the default with the `zlib-stream` feature alone).
26    ///
27    /// Compresses less than zstd and decodes more slowly — in the stress tests, with Discord's
28    /// parameters, 29× instead of 39× on small events and 10–30 % fewer events per second —
29    /// but needs no C compiler and holds less memory per shard (~50 KiB instead of ~150 KiB).
30    ///
31    /// discord.js counterpart: `CompressionMethod.ZlibNative` / `ZlibSync`.
32    #[cfg(feature = "zlib-stream")]
33    #[cfg_attr(all(feature = "zlib-stream", not(feature = "zstd-stream")), default)]
34    ZlibStream,
35}
36
37impl Compression {
38    /// The value of the `compress` gateway query parameter, if any.
39    pub(crate) const fn query_value(self) -> Option<&'static str> {
40        match self {
41            Self::None => None,
42            #[cfg(feature = "zstd-stream")]
43            Self::ZstdStream => Some("zstd-stream"),
44            #[cfg(feature = "zlib-stream")]
45            Self::ZlibStream => Some("zlib-stream"),
46        }
47    }
48}
49
50/// Per-connection decompression state.
51pub(crate) enum Decompressor {
52    #[cfg(feature = "zstd-stream")]
53    Zstd(zstd_stream::ZstdDecompressor),
54    #[cfg(feature = "zlib-stream")]
55    Zlib(zlib_stream::ZlibDecompressor),
56}
57
58impl Decompressor {
59    /// Creates the decompressor for a new connection, or `None` without compression.
60    #[cfg_attr(
61        not(feature = "zstd-stream"),
62        expect(
63            clippy::unnecessary_wraps,
64            reason = "fallible with compression features"
65        )
66    )]
67    pub(crate) fn new(compression: Compression) -> io::Result<Option<Self>> {
68        match compression {
69            Compression::None => Ok(None),
70            #[cfg(feature = "zstd-stream")]
71            Compression::ZstdStream => Ok(Some(Self::Zstd(zstd_stream::ZstdDecompressor::new()?))),
72            #[cfg(feature = "zlib-stream")]
73            Compression::ZlibStream => Ok(Some(Self::Zlib(zlib_stream::ZlibDecompressor::new()))),
74        }
75    }
76
77    /// Decompresses one WebSocket message. Returns the complete gateway payload, or `None` if
78    /// the message is only the first part of one (possible with `zlib-stream`).
79    #[cfg_attr(
80        not(any(feature = "zstd-stream", feature = "zlib-stream")),
81        allow(unused_variables)
82    )]
83    pub(crate) fn decompress(&mut self, input: &[u8]) -> io::Result<Option<&[u8]>> {
84        match *self {
85            #[cfg(feature = "zstd-stream")]
86            Self::Zstd(ref mut zstd) => zstd.decompress(input).map(Some),
87            #[cfg(feature = "zlib-stream")]
88            Self::Zlib(ref mut zlib) => zlib.decompress(input),
89        }
90    }
91}
92
93#[cfg(feature = "zstd-stream")]
94mod zstd_stream {
95    use std::io;
96
97    use zstd::stream::raw::{Decoder, InBuffer, Operation, OutBuffer};
98
99    /// Minimum free space ensured in the output buffer before each decompression step.
100    const CHUNK: usize = 32 * 1024;
101    /// Buffers larger than this are shrunk back after the payload has been handed out, so one
102    /// huge `GUILD_CREATE` does not pin megabytes of memory forever.
103    const MAX_RETAINED: usize = 1024 * 1024;
104
105    pub(crate) struct ZstdDecompressor {
106        decoder: Decoder<'static>,
107        buffer: Vec<u8>,
108    }
109
110    impl ZstdDecompressor {
111        pub(crate) fn new() -> io::Result<Self> {
112            Ok(Self {
113                decoder: Decoder::new()?,
114                buffer: Vec::with_capacity(CHUNK),
115            })
116        }
117
118        /// Each WebSocket message holds exactly one gateway payload but does not end a zstd
119        /// frame, so the decoder is driven until the input is consumed and no output remains.
120        pub(crate) fn decompress(&mut self, input: &[u8]) -> io::Result<&[u8]> {
121            if self.buffer.capacity() > MAX_RETAINED {
122                self.buffer = Vec::with_capacity(CHUNK);
123            }
124            self.buffer.clear();
125
126            let mut input = InBuffer::around(input);
127            loop {
128                if self.buffer.capacity() - self.buffer.len() < CHUNK {
129                    self.buffer.reserve(CHUNK);
130                }
131                let position = self.buffer.len();
132                let mut output = OutBuffer::around_pos(&mut self.buffer, position);
133                self.decoder.run(&mut input, &mut output)?;
134                let output_full = output.pos() == output.capacity();
135                if input.pos() == input.src.len() && !output_full {
136                    break;
137                }
138            }
139            Ok(&self.buffer)
140        }
141    }
142
143    #[cfg(test)]
144    mod tests {
145        use zstd::stream::raw::Encoder;
146
147        use super::*;
148
149        /// Compresses messages the way Discord does: one long-lived stream, flushed (but not
150        /// finished) after every message.
151        struct StreamCompressor(Encoder<'static>);
152
153        impl StreamCompressor {
154            fn compress(&mut self, data: &[u8]) -> Vec<u8> {
155                let mut out = Vec::with_capacity(data.len() + 64);
156                let mut input = InBuffer::around(data);
157                loop {
158                    out.reserve(1024);
159                    let position = out.len();
160                    let mut output = OutBuffer::around_pos(&mut out, position);
161                    self.0.run(&mut input, &mut output).unwrap();
162                    if input.pos() == input.src.len() {
163                        break;
164                    }
165                }
166                loop {
167                    out.reserve(1024);
168                    let position = out.len();
169                    let mut output = OutBuffer::around_pos(&mut out, position);
170                    if self.0.flush(&mut output).unwrap() == 0 {
171                        break;
172                    }
173                }
174                out
175            }
176        }
177
178        #[test]
179        fn stream_of_messages() {
180            let mut compressor = StreamCompressor(Encoder::new(3).unwrap());
181            let mut decompressor = ZstdDecompressor::new().unwrap();
182            for i in 0..50 {
183                let payload = format!(
184                    r#"{{"op":0,"s":{i},"t":"X","d":{{"n":"{}"}}}}"#,
185                    "y".repeat(i * 37)
186                );
187                let compressed = compressor.compress(payload.as_bytes());
188                assert_eq!(
189                    decompressor.decompress(&compressed).unwrap(),
190                    payload.as_bytes()
191                );
192            }
193        }
194
195        #[test]
196        fn large_payload_spans_many_chunks() {
197            let mut compressor = StreamCompressor(Encoder::new(3).unwrap());
198            let mut decompressor = ZstdDecompressor::new().unwrap();
199            let payload: Vec<u8> = (0..2_000_000_u32).map(|i| (i % 251) as u8).collect();
200            let compressed = compressor.compress(&payload);
201            assert_eq!(decompressor.decompress(&compressed).unwrap(), &payload[..]);
202            // The oversized buffer is released on the next message.
203            let small = compressor.compress(b"{}");
204            assert_eq!(decompressor.decompress(&small).unwrap(), b"{}");
205            assert!(decompressor.buffer.capacity() <= MAX_RETAINED);
206        }
207
208        #[test]
209        fn garbage_is_an_error() {
210            let mut decompressor = ZstdDecompressor::new().unwrap();
211            assert!(decompressor.decompress(b"definitely not zstd").is_err());
212        }
213    }
214}
215
216#[cfg(feature = "zlib-stream")]
217mod zlib_stream {
218    use core::mem;
219    use std::io;
220
221    use flate2::{Decompress, FlushDecompress, Status};
222
223    /// Every complete payload ends with the empty stored block of a `Z_SYNC_FLUSH`.
224    const SYNC_FLUSH_SUFFIX: [u8; 4] = [0x00, 0x00, 0xff, 0xff];
225    /// Minimum free space ensured in the output buffer before each inflate step.
226    const CHUNK: usize = 32 * 1024;
227    /// Buffers larger than this are shrunk back after use, so one huge `GUILD_CREATE` does not
228    /// pin megabytes of memory forever.
229    const MAX_RETAINED: usize = 1024 * 1024;
230
231    pub(crate) struct ZlibDecompressor {
232        inflate: Decompress,
233        /// The compressed start of a payload split over several WebSocket messages.
234        pending: Vec<u8>,
235        buffer: Vec<u8>,
236    }
237
238    impl ZlibDecompressor {
239        pub(crate) fn new() -> Self {
240            Self {
241                // Discord's stream starts with a zlib header.
242                inflate: Decompress::new(true),
243                pending: Vec::new(),
244                buffer: Vec::with_capacity(CHUNK),
245            }
246        }
247
248        /// Messages are buffered until one ends with the sync-flush suffix; the collected
249        /// bytes then inflate to exactly one gateway payload. In practice Discord sends one
250        /// payload per message, which is inflated straight from the message without copying.
251        pub(crate) fn decompress(&mut self, input: &[u8]) -> io::Result<Option<&[u8]>> {
252            let complete = input.ends_with(&SYNC_FLUSH_SUFFIX);
253            if self.pending.is_empty() && complete {
254                self.inflate_payload(input)?;
255                return Ok(Some(&self.buffer));
256            }
257            self.pending.extend_from_slice(input);
258            if !complete {
259                return Ok(None);
260            }
261            let mut pending = mem::take(&mut self.pending);
262            let result = self.inflate_payload(&pending);
263            pending.clear();
264            if pending.capacity() <= MAX_RETAINED {
265                self.pending = pending;
266            }
267            result?;
268            Ok(Some(&self.buffer))
269        }
270
271        fn inflate_payload(&mut self, input: &[u8]) -> io::Result<()> {
272            if self.buffer.capacity() > MAX_RETAINED {
273                self.buffer = Vec::with_capacity(CHUNK);
274            }
275            self.buffer.clear();
276
277            let mut consumed = 0;
278            loop {
279                if self.buffer.capacity() - self.buffer.len() < CHUNK {
280                    self.buffer.reserve(CHUNK);
281                }
282                let (in_before, out_before) = (self.inflate.total_in(), self.buffer.len());
283                let status = self
284                    .inflate
285                    .decompress_vec(&input[consumed..], &mut self.buffer, FlushDecompress::Sync)
286                    .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?;
287                // At most `input.len()`, so it fits.
288                consumed += usize::try_from(self.inflate.total_in() - in_before)
289                    .map_err(|_| io::Error::from(io::ErrorKind::InvalidData))?;
290                let output_full = self.buffer.len() == self.buffer.capacity();
291                if consumed == input.len() && !output_full {
292                    return Ok(());
293                }
294                let progressed =
295                    self.inflate.total_in() != in_before || self.buffer.len() != out_before;
296                if status == Status::StreamEnd || !progressed {
297                    // Discord never ends the stream; trailing bytes mean a corrupt payload.
298                    return Err(io::Error::new(
299                        io::ErrorKind::InvalidData,
300                        "zlib-stream payload did not inflate completely",
301                    ));
302                }
303            }
304        }
305    }
306
307    #[cfg(test)]
308    mod tests {
309        use flate2::{Compress, Compression, FlushCompress};
310
311        use super::*;
312
313        /// Compresses messages the way Discord does: one long-lived zlib stream, sync-flushed
314        /// after every payload.
315        struct StreamCompressor(Compress);
316
317        impl StreamCompressor {
318            fn new() -> Self {
319                Self(Compress::new(Compression::default(), true))
320            }
321
322            fn compress(&mut self, data: &[u8]) -> Vec<u8> {
323                let mut out = Vec::with_capacity(data.len() / 2 + 64);
324                let start = self.0.total_in();
325                loop {
326                    out.reserve(1024);
327                    let read = usize::try_from(self.0.total_in() - start).unwrap();
328                    self.0
329                        .compress_vec(&data[read..], &mut out, FlushCompress::Sync)
330                        .unwrap();
331                    let read = usize::try_from(self.0.total_in() - start).unwrap();
332                    if read == data.len() && out.len() < out.capacity() {
333                        break;
334                    }
335                }
336                assert!(out.ends_with(&SYNC_FLUSH_SUFFIX));
337                out
338            }
339        }
340
341        fn payload(i: usize) -> String {
342            format!(
343                r#"{{"op":0,"s":{i},"t":"X","d":{{"n":"{}"}}}}"#,
344                "y".repeat(i * 37)
345            )
346        }
347
348        #[test]
349        fn stream_of_messages() {
350            let mut compressor = StreamCompressor::new();
351            let mut decompressor = ZlibDecompressor::new();
352            for i in 0..50 {
353                let payload = payload(i);
354                let compressed = compressor.compress(payload.as_bytes());
355                assert_eq!(
356                    decompressor.decompress(&compressed).unwrap(),
357                    Some(payload.as_bytes())
358                );
359            }
360        }
361
362        #[test]
363        fn payload_split_over_messages() {
364            let mut compressor = StreamCompressor::new();
365            let mut decompressor = ZlibDecompressor::new();
366            for i in 0..20 {
367                let payload = payload(i * 3);
368                let compressed = compressor.compress(payload.as_bytes());
369                let (head, tail) = compressed.split_at(compressed.len() / 2);
370                assert_eq!(decompressor.decompress(head).unwrap(), None);
371                assert_eq!(
372                    decompressor.decompress(tail).unwrap(),
373                    Some(payload.as_bytes())
374                );
375            }
376            assert_eq!(decompressor.pending, [] as [u8; 0]);
377        }
378
379        #[test]
380        fn large_payload_spans_many_chunks() {
381            let mut compressor = StreamCompressor::new();
382            let mut decompressor = ZlibDecompressor::new();
383            let payload: Vec<u8> = (0..2_000_000_u32).map(|i| (i % 251) as u8).collect();
384            let compressed = compressor.compress(&payload);
385            assert_eq!(
386                decompressor.decompress(&compressed).unwrap(),
387                Some(&payload[..])
388            );
389            // The oversized buffer is released on the next message.
390            let small = compressor.compress(b"{}");
391            assert_eq!(decompressor.decompress(&small).unwrap(), Some(&b"{}"[..]));
392            assert!(decompressor.buffer.capacity() <= MAX_RETAINED);
393        }
394
395        #[test]
396        fn garbage_is_an_error() {
397            let mut decompressor = ZlibDecompressor::new();
398            let mut garbage = b"definitely not zlib".to_vec();
399            garbage.extend_from_slice(&SYNC_FLUSH_SUFFIX);
400            assert!(decompressor.decompress(&garbage).is_err());
401        }
402    }
403}