clickhouse-native-rs 2.24.1

Asynchronous ClickHouse client for Rust over the native TCP protocol, a maintained continuation of the clickhouse-rs crate.
Documentation
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
/*
 * 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
 */

//! A Data, Totals or Extremes packet read as its bytes arrive. What has come
//! is kept between reads: the frames already decompressed and how far the
//! walk over the block got. The block is parsed once, when it is whole, and
//! every frame is decompressed once (#7).

use std::io::{self, Cursor};

use chrono_tz::Tz;

use crate::{
    binary::ReadEx,
    errors::{Error, Result},
    types::{
        block::{
            compression::{decompress_frame, frame_len, FRAME_HEAD_SIZE},
            Block,
        },
        column::measure::{BlockWalk, Measure},
    },
};

/// The most the frame buffers keep between blocks: frames the server writes
/// (`max_compress_block_size`, 1 MiB by default) fit.
const RETAINED: usize = 4 << 20;

/// The most the block buffer keeps between blocks: blocks of a few hundred
/// thousand rows fit.
const RETAINED_BLOCK: usize = 64 << 20;

/// How many blocks in a row may use less than a quarter of the kept block
/// buffer before it is let go.
const SMALL_BLOCKS: u8 = 16;

/// The packet being read, if one is.
#[derive(Default)]
pub(crate) struct PendingBlock {
    /// Whether a packet is half read: the one at the start of the input
    /// until it is whole.
    active: bool,
    /// Where the block starts in the packet: after its type and table name.
    body: usize,
    /// With compression: the end in the packet of the frames decompressed
    /// so far, and what they hold (its capacity kept between blocks).
    raw_end: usize,
    decoded: Vec<u8>,
    /// How many blocks in a row have used less than a quarter of `decoded`.
    small: u8,
    frame: Vec<u8>,
    scratch: Vec<u8>,
    walk: BlockWalk,
    /// How many decoded bytes a parse of a block the walk does not know
    /// last ran out at: it is tried again only on more of them.
    tried: Option<usize>,
    /// How many decoded bytes the walk last found too few: it is not walked
    /// again before more come.
    short: Option<usize>,
}

fn would_block() -> Error {
    io::Error::new(io::ErrorKind::WouldBlock, "would block").into()
}

impl PendingBlock {
    /// Reads the packet at the start of `input`, which holds what the last
    /// call had and more: the block and the length of the packet, or
    /// `WouldBlock` while it is not all there.
    pub(crate) fn parse(
        &mut self,
        input: &[u8],
        tz: Tz,
        compress: bool,
        revision: u64,
    ) -> Result<(Block, usize)> {
        if !self.active {
            let mut cursor = Cursor::new(input);
            cursor.read_uvarint()?;
            cursor.skip_string()?;
            let body = cursor.position() as usize;
            *self = PendingBlock {
                active: true,
                body,
                raw_end: body,
                decoded: std::mem::take(&mut self.decoded),
                small: self.small,
                frame: std::mem::take(&mut self.frame),
                scratch: std::mem::take(&mut self.scratch),
                walk: BlockWalk::default(),
                tried: None,
                short: None,
            };
        }
        let result = if compress {
            self.parse_compressed(input, tz, revision)
        } else {
            self.parse_plain(input, tz, revision)
        };
        match result {
            Err(e) if e.is_would_block() => Err(e),
            done => {
                self.active = false;
                // After an error the connection is closed: nothing is kept.
                self.finish_block(done.is_ok());
                // The frame buffers serve the next blocks, unless one large
                // frame would keep them large on an idle connection.
                if self.frame.capacity() > RETAINED {
                    self.frame = Vec::new();
                }
                if self.scratch.capacity() > RETAINED {
                    self.scratch = Vec::new();
                }
                done
            }
        }
    }

    /// The decompressed block when it is whole: kept for the next blocks,
    /// cleared, unless it is larger than `RETAINED_BLOCK`, or the blocks
    /// have long used much less of it. A buffer made anew for each block
    /// would grow from nothing, a copy and fresh pages at every doubling:
    /// more than the decompression itself costs.
    fn finish_block(&mut self, kept: bool) {
        let used = self.decoded.len();
        self.decoded.clear();
        let capacity = self.decoded.capacity();
        if !kept || capacity > RETAINED_BLOCK {
            self.decoded = Vec::new();
            self.small = 0;
        } else if used < capacity / 4 {
            self.small += 1;
            if self.small >= SMALL_BLOCKS {
                self.decoded = Vec::new();
                self.small = 0;
            }
        } else {
            self.small = 0;
        }
    }

    /// Lets the buffers larger than the frame buffers keep go, between
    /// packets: for a connection that waits in the pool.
    pub(crate) fn release(&mut self) {
        if !self.active && self.decoded.capacity() > RETAINED {
            self.decoded = Vec::new();
            self.small = 0;
        }
    }

    fn parse_plain(&mut self, input: &[u8], tz: Tz, revision: u64) -> Result<(Block, usize)> {
        let body = &input[self.body..];
        let measure = self.walk.walk(body, revision);
        if measure == Measure::Incomplete {
            return Err(would_block());
        }
        let (block, len) = load(body, tz, revision)?;
        check(&measure, len);
        Ok((block, self.body + len))
    }

    fn parse_compressed(&mut self, input: &[u8], tz: Tz, revision: u64) -> Result<(Block, usize)> {
        loop {
            let measure = if self.short == Some(self.decoded.len()) {
                Measure::Incomplete
            } else {
                self.walk.walk(&self.decoded, revision)
            };
            if measure == Measure::Incomplete {
                self.short = Some(self.decoded.len());
            }
            let attempt = match measure {
                Measure::Complete(_) => true,
                Measure::Unknown => self.tried != Some(self.decoded.len()),
                Measure::Incomplete => false,
            };
            if attempt {
                match load(&self.decoded, tz, revision) {
                    Ok((block, len)) => {
                        check(&measure, len);
                        return Ok((block, self.raw_end));
                    }
                    // A column the walk does not know may want more.
                    Err(e) if e.is_would_block() && measure == Measure::Unknown => {
                        self.tried = Some(self.decoded.len());
                    }
                    Err(e) => return Err(e),
                }
            }
            if !self.decompress_next(input)? {
                return Err(would_block());
            }
        }
    }

    /// Decompresses the next frame of the block once it is all there; the
    /// block wants more bytes, so the next bytes are a frame of it.
    fn decompress_next(&mut self, input: &[u8]) -> Result<bool> {
        let raw = &input[self.raw_end..];
        let Some(head) = raw.first_chunk::<FRAME_HEAD_SIZE>() else {
            return Ok(false);
        };
        // A header the frame reader rejects is an error now, not a wait.
        if raw.len() < frame_len(head)? {
            return Ok(false);
        }
        let mut cursor = Cursor::new(raw);
        decompress_frame(&mut cursor, &mut self.scratch, &mut self.frame)?;
        self.raw_end += cursor.position() as usize;
        self.decoded.extend_from_slice(&self.frame);
        Ok(true)
    }
}

/// The block at the start of `bytes` and its length.
fn load(bytes: &[u8], tz: Tz, revision: u64) -> Result<(Block, usize)> {
    let mut cursor = Cursor::new(bytes);
    let block = Block::raw_load(&mut cursor, tz, revision)?;
    Ok((block, cursor.position() as usize))
}

/// In the tests, a walk that said whole agrees with the parser.
fn check(measure: &Measure, len: usize) {
    if let Measure::Complete(walked) = measure {
        debug_assert_eq!(*walked, len, "the walk and the parser disagree");
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::{
        binary::Encoder,
        types::{Compression, Simple},
    };

    /// A Data packet of `block` at `revision`, then a Pong.
    fn packet(block: &Block<Simple>, compression: Compression, revision: u64) -> Vec<u8> {
        let mut encoder = Encoder::new();
        encoder.uvarint(1);
        encoder.string("");
        block.write_at(&mut encoder, compression, revision).unwrap();
        encoder.write(4_u8);
        encoder.get_buffer()
    }

    #[test]
    fn test_a_packet_read_byte_by_byte() {
        let strings: Vec<String> = (0..70_000).map(|i| format!("value {i}")).collect();
        let numbers: Vec<u64> = (0..70_000).collect();
        let block = Block::<Simple>::new()
            .column("s", strings)
            .column("n", numbers)
            .column("o", vec![Some(1_u8); 70_000]);
        for compression in [Compression::None, Compression::Lz4, Compression::Zstd] {
            for revision in [54491, 54492] {
                let bytes = packet(&block, compression, revision);
                let end = bytes.len() - 1;
                let mut pending = PendingBlock::default();
                // Every byte short of the whole packet waits: in steps, so
                // that a frame comes whole between some of them.
                let mut len = 0;
                while len < end {
                    let err = pending
                        .parse(&bytes[..len], Tz::UTC, compression.is_enabled(), revision)
                        .expect_err("a packet not all there");
                    assert!(
                        err.is_would_block(),
                        "{compression} {revision} {len}: {err}"
                    );
                    len += 4099;
                }
                let (read, packet_len) = pending
                    .parse(&bytes, Tz::UTC, compression.is_enabled(), revision)
                    .unwrap();
                assert_eq!(read, block, "{compression} {revision}");
                assert_eq!(packet_len, end, "{compression} {revision}");
                assert!(!pending.active);
                // At once, too.
                let (read, _) = PendingBlock::default()
                    .parse(&bytes, Tz::UTC, compression.is_enabled(), revision)
                    .unwrap();
                assert_eq!(read, block);
            }
        }
    }

    #[test]
    fn test_a_bad_frame_header_is_an_error_at_once() {
        // A Data packet whose first frame has a method no reader knows and
        // no payload yet.
        let mut bytes = vec![1, 0];
        bytes.extend_from_slice(&[0; 16]);
        bytes.push(0x77);
        bytes.extend_from_slice(&1000_u32.to_le_bytes());
        bytes.extend_from_slice(&991_u32.to_le_bytes());
        let err = PendingBlock::default()
            .parse(&bytes, Tz::UTC, true, 54492)
            .expect_err("an unknown method");
        assert!(
            err.to_string().contains("unsupported compression method"),
            "{err}"
        );
    }

    #[test]
    fn test_a_replicated_index_past_its_rows_is_an_error_at_once() {
        // A block of one replicated String column of two rows, index 3 of 2
        // distinct rows, and the distinct rows not sent.
        let mut body = Encoder::new();
        body.write_bytes(&[1, 0, 2, 0xff, 0xff, 0xff, 0xff, 0]);
        body.uvarint(1);
        body.uvarint(2);
        body.string("c");
        body.string("String");
        body.write_bytes(&[1, 4]);
        body.uvarint(2);
        body.write_bytes(&[1, 0, 3]);
        body.uvarint(2);
        let body = body.get_buffer();
        for compression in [Compression::None, Compression::Lz4] {
            let mut bytes = vec![1, 0];
            if compression.is_enabled() {
                crate::types::block::compression::compress(compression, 3, &body, &mut bytes)
                    .unwrap();
            } else {
                bytes.extend_from_slice(&body);
            }
            let err = PendingBlock::default()
                .parse(&bytes, Tz::UTC, compression.is_enabled(), 54492)
                .expect_err("an index past the distinct rows");
            assert!(
                err.to_string().contains("points to row 3"),
                "{compression}: {err}"
            );
        }
    }

    #[test]
    fn test_the_block_buffer_serves_the_next_block() {
        // A large block, then a smaller one of other columns read in parts on
        // the same reader: the buffer is the one the first block grew.
        let first = Block::<Simple>::new().column("n", (0..600_000_u64).collect::<Vec<_>>());
        let second = Block::<Simple>::new().column(
            "s",
            (0..50_000).map(|i| format!("s{i}")).collect::<Vec<_>>(),
        );
        let mut pending = PendingBlock::default();
        let bytes = packet(&first, Compression::Lz4, 54492);
        let (read, _) = pending.parse(&bytes, Tz::UTC, true, 54492).unwrap();
        assert_eq!(read, first);
        let capacity = pending.decoded.capacity();
        let buffer = pending.decoded.as_ptr();
        assert!(capacity >= 4_800_000, "{capacity}");

        let bytes = packet(&second, Compression::Lz4, 54492);
        let end = bytes.len() - 1;
        let half = bytes.len() / 2;
        assert!(pending.parse(&bytes[..half], Tz::UTC, true, 54492).is_err());
        let (read, len) = pending.parse(&bytes, Tz::UTC, true, 54492).unwrap();
        assert_eq!((read, len), (second, end));
        assert_eq!(pending.decoded.capacity(), capacity);
        assert_eq!(pending.decoded.as_ptr(), buffer);

        // Back in the pool, the connection keeps a small buffer only.
        pending.release();
        assert_eq!(pending.decoded.capacity(), 0);
    }

    #[test]
    fn test_the_block_buffer_is_kept_within_bounds() {
        let mut pending = PendingBlock::default();
        pending.decoded.resize(1 << 20, 0);
        pending.finish_block(true);
        assert!(pending.decoded.is_empty() && pending.decoded.capacity() >= 1 << 20);
        // Blocks that use little of it, many in a row, let it go.
        for block in 1..=SMALL_BLOCKS {
            pending.decoded.resize(16, 0);
            pending.finish_block(true);
            assert_eq!(pending.decoded.capacity() == 0, block == SMALL_BLOCKS);
        }
        // So does one too large, and any after an error.
        pending.decoded = Vec::with_capacity(RETAINED_BLOCK + 1);
        pending.finish_block(true);
        assert_eq!(pending.decoded.capacity(), 0);
        pending.decoded.resize(16, 0);
        pending.finish_block(false);
        assert_eq!(pending.decoded.capacity(), 0);
    }

    #[test]
    fn test_corrupt_frame_is_an_error() {
        let block = Block::<Simple>::new().column("n", vec![1_u32, 2, 3]);
        let mut bytes = packet(&block, Compression::Lz4, 54492);
        // The first byte of the checksum, after the packet type and name.
        bytes[2] ^= 0xff;
        let err = PendingBlock::default()
            .parse(&bytes, Tz::UTC, true, 54492)
            .expect_err("a corrupt frame");
        assert!(!err.is_would_block(), "{err}");
    }
}