1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
/*
 * clickhouse-native-rs — Asynchronous ClickHouse client for Rust over the native TCP protocol
 * Copyright (c) 2026 Alexander Panasenko
 *
 * Contact: alex@prod.codes
 * Author: https://prod.codes/about/
 * Project: https://github.com/alex09x/clickhouse-native-rs
 * SPDX-License-Identifier: MIT
 */

//! Compressed frames of the native protocol.
//!
//! ```text
//! checksum  16 bytes  CityHash128 of the rest of the frame, low half first
//! method     1 byte   0x02 none, 0x82 LZ4, 0x90 ZSTD
//! size       u32 LE   size of the frame after the checksum, this header included
//! original   u32 LE   size of the payload once decompressed
//! payload
//! ```
//!
//! The format and the limits follow `src/Compression/CompressionInfo.h` in
//! ClickHouse. Like ClickHouse, the client cuts the data it sends into frames
//! of at most 1 MiB before compression; a block may span several frames.

use std::{
    cell::RefCell,
    fmt,
    os::raw::{c_char, c_int},
    str::FromStr,
};

use byteorder::{ByteOrder, LittleEndian};
use clickhouse_rs_cityhash_sys::{city_hash_128, UInt128};
use lz4::liblz4::{LZ4_compressBound, LZ4_compress_default, LZ4_decompress_safe};
use zstd::bulk::{Compressor, Decompressor};

use crate::{
    binary::ReadEx,
    errors::{Error, Result},
};

const CHECKSUM_SIZE: usize = 16;
const HEADER_SIZE: usize = 9;

/// The largest frame accepted, header included (`DBMS_MAX_COMPRESSED_SIZE`).
const MAX_COMPRESSED_SIZE: usize = 0x2000_0000;
/// The largest decompressed frame accepted (`DBMS_MAX_DECOMPRESSED_SIZE`).
const MAX_DECOMPRESSED_SIZE: usize = 0x1000_0000;
/// Uncompressed bytes per frame the client sends (ClickHouse's default
/// `max_compress_block_size`).
const MAX_FRAME_INPUT: usize = 1 << 20;
/// The ZSTD level used when the connection settings do not name one: the
/// default of `network_zstd_compression_level` since ClickHouse 26.9 (it was 1
/// before).
pub(crate) const DEFAULT_ZSTD_LEVEL: i32 = 3;
/// How much the buffer for compressed bytes grows per read.
const READ_STEP: usize = 1 << 16;

const METHOD_NONE: u8 = 0x02;
const METHOD_LZ4: u8 = 0x82;
const METHOD_ZSTD: u8 = 0x90;

/// Compression of the data the client sends.
///
/// `None` turns compression off in both directions. With `Lz4` or `Zstd` the
/// choice applies to what the client writes: the server compresses its replies
/// with the method of its `network_compression_method` setting, and the client
/// reads LZ4, ZSTD and uncompressed frames alike.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum Compression {
    /// No compression, in either direction.
    #[default]
    None,
    /// LZ4.
    Lz4,
    /// ZSTD, at the level of the `network_zstd_compression_level` setting of
    /// the connection, or 3 (ClickHouse's default since 26.9) when it is not set.
    Zstd,
}

impl Compression {
    pub(crate) fn is_enabled(self) -> bool {
        self != Compression::None
    }
}

impl FromStr for Compression {
    type Err = Error;

    fn from_str(source: &str) -> Result<Self> {
        match source.to_ascii_lowercase().as_str() {
            "none" => Ok(Compression::None),
            "lz4" => Ok(Compression::Lz4),
            "zstd" => Ok(Compression::Zstd),
            _ => Err(Error::from(format!(
                "unknown compression method `{source}`"
            ))),
        }
    }
}

impl fmt::Display for Compression {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str(match self {
            Compression::None => "none",
            Compression::Lz4 => "lz4",
            Compression::Zstd => "zstd",
        })
    }
}

thread_local! {
    static ZSTD_COMPRESSOR: RefCell<Option<(i32, Compressor<'static>)>> = const { RefCell::new(None) };
    static ZSTD_DECOMPRESSOR: RefCell<Option<Decompressor<'static>>> = const { RefCell::new(None) };
}

/// Appends `data` to `out` as one or more compressed frames; `zstd_level`
/// applies to `Compression::Zstd`.
pub(crate) fn compress(
    method: Compression,
    zstd_level: i32,
    data: &[u8],
    out: &mut Vec<u8>,
) -> Result<()> {
    let mut rest = data;
    loop {
        let (chunk, tail) = rest.split_at(rest.len().min(MAX_FRAME_INPUT));
        write_frame(method, zstd_level, chunk, out)?;
        rest = tail;
        if rest.is_empty() {
            return Ok(());
        }
    }
}

fn write_frame(
    method: Compression,
    zstd_level: i32,
    chunk: &[u8],
    out: &mut Vec<u8>,
) -> Result<()> {
    let start = out.len();
    let header_start = start + CHECKSUM_SIZE;
    let payload_start = header_start + HEADER_SIZE;

    let (method_byte, bound) = match method {
        Compression::None => (METHOD_NONE, chunk.len()),
        Compression::Lz4 => (METHOD_LZ4, lz4_bound(chunk.len())),
        Compression::Zstd => (METHOD_ZSTD, zstd::zstd_safe::compress_bound(chunk.len())),
    };
    out.resize(payload_start + bound, 0);

    let payload = &mut out[payload_start..];
    let written = match method {
        Compression::None => {
            payload.copy_from_slice(chunk);
            chunk.len()
        }
        Compression::Lz4 => lz4_compress(chunk, payload)?,
        Compression::Zstd => zstd_compress(chunk, payload, zstd_level)?,
    };
    out.truncate(payload_start + written);

    let header = &mut out[header_start..payload_start];
    header[0] = method_byte;
    LittleEndian::write_u32(&mut header[1..5], (HEADER_SIZE + written) as u32);
    LittleEndian::write_u32(&mut header[5..9], chunk.len() as u32);

    let hash = city_hash_128(&out[header_start..]);
    LittleEndian::write_u64(&mut out[start..start + 8], hash.lo);
    LittleEndian::write_u64(&mut out[start + 8..header_start], hash.hi);
    Ok(())
}

/// Reads one frame and replaces the contents of `out` with its decompressed
/// payload. `scratch` holds the compressed bytes and is reused between calls.
pub(crate) fn decompress_frame<R>(
    reader: &mut R,
    scratch: &mut Vec<u8>,
    out: &mut Vec<u8>,
) -> Result<()>
where
    R: ReadEx,
{
    let mut checksum = [0_u8; CHECKSUM_SIZE];
    reader.read_bytes(&mut checksum)?;
    let expected = UInt128 {
        lo: LittleEndian::read_u64(&checksum[..8]),
        hi: LittleEndian::read_u64(&checksum[8..]),
    };

    let mut header = [0_u8; HEADER_SIZE];
    reader.read_bytes(&mut header)?;
    let (method, size, original) = check_header(&header)?;

    // Grow the buffer as the bytes arrive rather than trusting the declared
    // size up front: a short read is retried from the start of the packet.
    scratch.clear();
    scratch.extend_from_slice(&header);
    while scratch.len() < size {
        let filled = scratch.len();
        let step = (size - filled).min(READ_STEP);
        scratch.resize(filled + step, 0);
        reader.read_bytes(&mut scratch[filled..])?;
    }

    if city_hash_128(&scratch[..]) != expected {
        return Err("data was corrupted".into());
    }

    let payload = &scratch[HEADER_SIZE..];
    out.clear();
    let produced = match method {
        METHOD_LZ4 => lz4_decompress(payload, original, out)?,
        METHOD_ZSTD => zstd_decompress(payload, original, out)?,
        _ => {
            out.extend_from_slice(payload);
            payload.len()
        }
    };

    if produced != original {
        return Err(Error::from(format!(
            "frame decompressed to {produced} bytes, its header says {original}"
        )));
    }
    Ok(())
}

/// The checksum and header that start a frame.
pub(crate) const FRAME_HEAD_SIZE: usize = CHECKSUM_SIZE + HEADER_SIZE;

/// The length of the frame that `head` starts, checksum and header
/// included, once its header passes the checks `decompress_frame` makes.
pub(crate) fn frame_len(head: &[u8; FRAME_HEAD_SIZE]) -> Result<usize> {
    let header: &[u8; HEADER_SIZE] = head[CHECKSUM_SIZE..].try_into().unwrap();
    let (_, size, _) = check_header(header)?;
    Ok(CHECKSUM_SIZE + size)
}

/// The method, the compressed size (header included) and the decompressed
/// size of a frame, checked against the limits and the methods known.
fn check_header(header: &[u8; HEADER_SIZE]) -> Result<(u8, usize, usize)> {
    let method = header[0];
    let size = LittleEndian::read_u32(&header[1..5]) as usize;
    let original = LittleEndian::read_u32(&header[5..9]) as usize;

    if size < HEADER_SIZE {
        return Err(Error::from(format!(
            "compressed frame size {size} is smaller than its {HEADER_SIZE}-byte header"
        )));
    }
    if size > MAX_COMPRESSED_SIZE {
        return Err(Error::from(format!(
            "compressed frame of {size} bytes exceeds the {MAX_COMPRESSED_SIZE}-byte limit"
        )));
    }
    if original > MAX_DECOMPRESSED_SIZE {
        return Err(Error::from(format!(
            "decompressed frame of {original} bytes exceeds the {MAX_DECOMPRESSED_SIZE}-byte limit"
        )));
    }
    match method {
        METHOD_LZ4 | METHOD_ZSTD => {}
        METHOD_NONE if size - HEADER_SIZE == original => {}
        METHOD_NONE => {
            return Err(Error::from(format!(
                "uncompressed frame holds {} bytes, its header says {original}",
                size - HEADER_SIZE
            )))
        }
        _ => {
            return Err(Error::from(format!(
                "unsupported compression method 0x{method:02x}"
            )))
        }
    }
    Ok((method, size, original))
}

fn lz4_bound(len: usize) -> usize {
    // `len` is at most MAX_FRAME_INPUT, far below LZ4's input limit.
    unsafe { LZ4_compressBound(len as c_int) as usize }
}

fn lz4_compress(src: &[u8], dst: &mut [u8]) -> Result<usize> {
    let written = unsafe {
        LZ4_compress_default(
            src.as_ptr() as *const c_char,
            dst.as_mut_ptr() as *mut c_char,
            src.len() as c_int,
            dst.len() as c_int,
        )
    };
    if written <= 0 {
        return Err("LZ4 compression failed".into());
    }
    Ok(written as usize)
}

fn lz4_decompress(src: &[u8], original: usize, out: &mut Vec<u8>) -> Result<usize> {
    out.reserve(original);
    // Safety: the frame limits keep `src.len()` and `original` far below
    // `c_int::MAX`; `out` is empty with room for `original` bytes, and LZ4
    // writes at most that many.
    let produced = unsafe {
        LZ4_decompress_safe(
            src.as_ptr() as *const c_char,
            out.as_mut_ptr() as *mut c_char,
            src.len() as c_int,
            original as c_int,
        )
    };
    if produced < 0 {
        return Err("can't decompress LZ4 data".into());
    }
    // LZ4 has written `produced` bytes, no more than the capacity reserved above.
    unsafe { out.set_len(produced as usize) };
    Ok(produced as usize)
}

fn zstd_compress(src: &[u8], dst: &mut [u8], level: i32) -> Result<usize> {
    ZSTD_COMPRESSOR.with(|cell| {
        let mut cell = cell.borrow_mut();
        match cell.as_mut() {
            None => *cell = Some((level, Compressor::new(level)?)),
            Some((current, compressor)) if *current != level => {
                compressor.set_compression_level(level)?;
                *current = level;
            }
            Some(_) => {}
        }
        let (_, compressor) = cell.as_mut().expect("created above");
        Ok(compressor.compress_to_buffer(src, dst)?)
    })
}

fn zstd_decompress(src: &[u8], original: usize, out: &mut Vec<u8>) -> Result<usize> {
    // Check the size the ZSTD frame header declares before allocating for it.
    match zstd::zstd_safe::get_frame_content_size(src) {
        Ok(Some(size)) if size != original as u64 => {
            return Err(Error::from(format!(
                "ZSTD frame holds {size} bytes, its block header says {original}"
            )))
        }
        Ok(_) => {}
        Err(_) => return Err("the payload is not a ZSTD frame".into()),
    }

    // A slice of exactly `original` bytes makes the decoder stop at the
    // declared size instead of filling whatever capacity `out` has.
    out.resize(original, 0);
    let produced = ZSTD_DECOMPRESSOR.with(|cell| {
        let mut cell = cell.borrow_mut();
        if cell.is_none() {
            *cell = Some(Decompressor::new()?);
        }
        let decompressor = cell.as_mut().expect("created above");
        decompressor
            .decompress_to_buffer(src, &mut out[..])
            .map_err(|err| Error::from(format!("can't decompress ZSTD data: {err}")))
    })?;
    out.truncate(produced);
    Ok(produced)
}

#[cfg(test)]
mod test {
    use std::io::Cursor;

    use super::*;

    fn sample(len: usize) -> Vec<u8> {
        (0..len)
            .map(|i| (i % 251) as u8 ^ (i / 4096) as u8)
            .collect()
    }

    fn read_all(mut bytes: &[u8]) -> Vec<u8> {
        let mut scratch = Vec::new();
        let mut frame = Vec::new();
        let mut result = Vec::new();
        while !bytes.is_empty() {
            let mut cursor = Cursor::new(bytes);
            decompress_frame(&mut cursor, &mut scratch, &mut frame).unwrap();
            result.extend_from_slice(&frame);
            bytes = &bytes[cursor.position() as usize..];
        }
        result
    }

    #[test]
    fn test_round_trip_every_method() {
        for method in [Compression::None, Compression::Lz4, Compression::Zstd] {
            for len in [0, 1, 1000, MAX_FRAME_INPUT, 3 * MAX_FRAME_INPUT + 17] {
                let data = sample(len);
                let mut out = Vec::new();
                compress(method, DEFAULT_ZSTD_LEVEL, &data, &mut out).unwrap();
                assert_eq!(read_all(&out), data, "{method} with {len} bytes");
            }
        }
    }

    #[test]
    fn test_frames_are_split_at_one_mebibyte() {
        let data = sample(2 * MAX_FRAME_INPUT + 1);
        let mut out = Vec::new();
        compress(Compression::Zstd, DEFAULT_ZSTD_LEVEL, &data, &mut out).unwrap();

        let mut originals = Vec::new();
        let mut rest = &out[..];
        while !rest.is_empty() {
            let header = &rest[CHECKSUM_SIZE..CHECKSUM_SIZE + HEADER_SIZE];
            assert_eq!(header[0], METHOD_ZSTD);
            originals.push(LittleEndian::read_u32(&header[5..9]) as usize);
            let size = LittleEndian::read_u32(&header[1..5]) as usize;
            rest = &rest[CHECKSUM_SIZE + size..];
        }
        assert_eq!(originals, vec![MAX_FRAME_INPUT, MAX_FRAME_INPUT, 1]);
    }

    fn frame(method: Compression, data: &[u8]) -> Vec<u8> {
        let mut out = Vec::new();
        compress(method, DEFAULT_ZSTD_LEVEL, data, &mut out).unwrap();
        out
    }

    fn read_error(bytes: &[u8]) -> String {
        let mut cursor = Cursor::new(bytes);
        decompress_frame(&mut cursor, &mut Vec::new(), &mut Vec::new())
            .unwrap_err()
            .to_string()
    }

    fn rehash(bytes: &mut [u8]) {
        let hash = city_hash_128(&bytes[CHECKSUM_SIZE..]);
        LittleEndian::write_u64(&mut bytes[..8], hash.lo);
        LittleEndian::write_u64(&mut bytes[8..CHECKSUM_SIZE], hash.hi);
    }

    #[test]
    fn test_corrupted_payload_is_rejected() {
        let mut bytes = frame(Compression::Zstd, &sample(500));
        let last = bytes.len() - 1;
        bytes[last] ^= 0xff;
        assert!(read_error(&bytes).contains("corrupted"));
    }

    #[test]
    fn test_unknown_method_is_an_error() {
        let mut bytes = frame(Compression::None, b"abc");
        bytes[CHECKSUM_SIZE] = 0x9f;
        rehash(&mut bytes);
        assert!(read_error(&bytes).contains("unsupported compression method 0x9f"));
    }

    #[test]
    fn test_size_smaller_than_header_is_an_error() {
        let mut bytes = frame(Compression::None, b"");
        LittleEndian::write_u32(&mut bytes[CHECKSUM_SIZE + 1..CHECKSUM_SIZE + 5], 3);
        assert!(read_error(&bytes).contains("smaller than its 9-byte header"));
    }

    #[test]
    fn test_huge_declared_size_is_refused_before_allocating() {
        let mut bytes = frame(Compression::Lz4, b"abc");
        LittleEndian::write_u32(&mut bytes[CHECKSUM_SIZE + 5..CHECKSUM_SIZE + 9], u32::MAX);
        assert!(read_error(&bytes).contains("exceeds"));
    }

    #[test]
    fn test_wrong_declared_size_is_an_error() {
        let mut bytes = frame(Compression::Zstd, &sample(100));
        LittleEndian::write_u32(&mut bytes[CHECKSUM_SIZE + 5..CHECKSUM_SIZE + 9], 99);
        rehash(&mut bytes);
        assert!(!read_error(&bytes).is_empty());
    }

    #[test]
    fn test_uncompressed_frame_with_wrong_size_is_an_error() {
        let mut bytes = frame(Compression::None, b"abcd");
        LittleEndian::write_u32(&mut bytes[CHECKSUM_SIZE + 5..CHECKSUM_SIZE + 9], 5);
        assert!(read_error(&bytes).contains("its header says 5"));
    }

    #[test]
    fn test_incomplete_frame_allocates_only_what_arrived() {
        let mut bytes = frame(Compression::Lz4, &sample(1000));
        let declared = MAX_COMPRESSED_SIZE as u32 - 1;
        LittleEndian::write_u32(&mut bytes[CHECKSUM_SIZE + 1..CHECKSUM_SIZE + 5], declared);

        let mut scratch = Vec::new();
        let mut cursor = Cursor::new(&bytes[..]);
        decompress_frame(&mut cursor, &mut scratch, &mut Vec::new()).unwrap_err();
        assert!(scratch.len() <= HEADER_SIZE + 2 * READ_STEP);
    }

    #[test]
    fn test_zstd_frame_size_mismatch_is_refused_before_decoding() {
        let mut bytes = frame(Compression::Zstd, &sample(100));
        LittleEndian::write_u32(
            &mut bytes[CHECKSUM_SIZE + 5..CHECKSUM_SIZE + 9],
            200_000_000,
        );
        rehash(&mut bytes);
        assert!(read_error(&bytes).contains("ZSTD frame holds 100 bytes"));
    }

    #[test]
    fn test_compressor_follows_the_requested_level() {
        let data: Vec<u8> = (0..200_000_u32)
            .flat_map(|i| (i.wrapping_mul(2_654_435_761) % 1000).to_le_bytes())
            .collect();
        let reference = |level| zstd::bulk::compress(&data, level).unwrap();
        assert_ne!(
            reference(1),
            reference(9),
            "the input must tell the levels apart"
        );

        let mut payload = vec![0_u8; zstd::zstd_safe::compress_bound(data.len())];
        for level in [1, 9, 1] {
            let written = zstd_compress(&data, &mut payload, level).unwrap();
            assert_eq!(payload[..written], reference(level)[..], "level {level}");
        }
    }

    #[test]
    fn test_parse_method() {
        assert_eq!("none".parse::<Compression>().unwrap(), Compression::None);
        assert_eq!("lz4".parse::<Compression>().unwrap(), Compression::Lz4);
        assert_eq!("ZSTD".parse::<Compression>().unwrap(), Compression::Zstd);
        "brotli".parse::<Compression>().unwrap_err();
    }
}