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
use std::io::{self, Read};

use chrono_tz::Tz;
use log::{trace, warn};

use crate::{
    binary::{protocol, ReadEx},
    client_info,
    errors::{DriverError, Error, Result, ServerError},
    io::transport::TransportInfo,
    types::{block::compressed, Block, Packet, ProfileInfo, Progress, ServerInfo, TableColumns},
};

/// The first byte of an HTTP response ("H"), never a native packet type.
const HTTP_FIRST_BYTE: u64 = 0x48;

/// The internal clickhouse response parser.
pub(crate) struct Parser<'i, T> {
    reader: T,
    info: &'i TransportInfo,
}

/// The parser can be used to parse clickhouse responses into values.  Generally
/// you normally do not use this directly as it's already done for you by
/// the client but in some more complex situations it might be useful to be
/// able to parse the clickhouse responses.
impl<'i, T: Read> Parser<'i, T> {
    /// Creates a new parser that parses the data behind the reader.  More
    /// than one value can be behind the reader in which case the parser can
    /// be invoked multiple times.  In other words: the stream does not have
    /// to be terminated.
    pub(crate) fn new(reader: T, info: &'i TransportInfo) -> Parser<'i, T> {
        Self { reader, info }
    }

    /// Parses a single value out of the stream. If there are multiple
    /// values you can call this multiple times. If the reader is not yet
    /// ready this will block.
    #[cfg(test)]
    pub(crate) fn parse_packet(&mut self, revision: u64) -> Result<Packet<()>> {
        loop {
            if let Some(packet) = self.parse_next(revision)? {
                return Ok(packet);
            }
        }
    }

    /// Parses the next packet, or `None` for a Log or ProfileEvents packet:
    /// read and dropped, as nothing waits for them, so that the caller can let
    /// go of its bytes before the next packet is complete.
    pub(crate) fn parse_next(&mut self, revision: u64) -> Result<Option<Packet<()>>> {
        let packet = self.reader.read_uvarint()?;
        let packet = match packet {
            protocol::SERVER_HELLO => self.parse_server_info()?,
            protocol::SERVER_PONG => self.parse_pong(),
            protocol::SERVER_PROGRESS => self.parse_progress(revision)?,
            protocol::SERVER_PROFILE_INFO => self.parse_profile_info(revision)?,
            protocol::SERVER_TABLE_COLUMNS => self.parse_table_columns(revision)?,
            protocol::SERVER_EXCEPTION => self.parse_exception()?,
            protocol::SERVER_DATA | protocol::SERVER_TOTALS | protocol::SERVER_EXTREMES => {
                self.parse_block(revision)?
            }
            protocol::SERVER_LOG | protocol::SERVER_PROFILE_EVENTS => {
                self.skip_service_block(revision)?;
                return Ok(None);
            }
            // The session time zone, sent with the structure of an `input()`
            // insert; the columns name their own zones.
            protocol::SERVER_TIMEZONE_UPDATE => {
                self.reader.skip_string()?;
                return Ok(None);
            }
            protocol::SERVER_END_OF_STREAM => Packet::Eof(()),
            HTTP_FIRST_BYTE => self.http_reply(packet)?,
            _ => return Err(Error::Driver(DriverError::UnknownPacket { packet })),
        };
        Ok(Some(packet))
    }

    /// No packet type is 0x48; an HTTP server's reply starts with that byte,
    /// the "H" of "HTTP/". Say so instead of reporting an unknown packet.
    fn http_reply(&mut self, packet: u64) -> Result<Packet<()>> {
        // Byte by byte, so that a mismatch is reported at once instead of
        // waiting for bytes that may never come.
        for expected in *b"TTP/" {
            let byte: u8 = self.reader.read_scalar()?;
            if byte != expected {
                return Err(Error::Driver(DriverError::UnknownPacket { packet }));
            }
        }
        Err(Error::Other(
            "the server answered over HTTP: this client speaks the native TCP protocol, \
             so connect to the server's native port (9000 by default, 9440 with TLS), \
             not to its HTTP interface (8123 by default)"
                .into(),
        ))
    }

    fn parse_block(&mut self, revision: u64) -> Result<Packet<()>> {
        match self.info.timezone {
            None => Err(Error::Driver(DriverError::UnexpectedPacket)),
            Some(tz) => {
                self.reader.skip_string()?;
                let block = Block::load(&mut self.reader, tz, self.info.compress, revision)?;
                Ok(Packet::Block(block))
            }
        }
    }

    /// A Log or ProfileEvents block: compressed as data blocks are from 54481.
    fn skip_service_block(&mut self, revision: u64) -> Result<()> {
        let tz = self.info.timezone.unwrap_or(Tz::UTC);
        let compress = self.info.compress
            && revision >= protocol::DBMS_MIN_REVISION_WITH_COMPRESSED_LOGS_PROFILE_EVENTS_COLUMNS;
        self.reader.skip_string()?;
        Block::load(&mut self.reader, tz, compress, revision)?;
        Ok(())
    }

    fn parse_server_info(&mut self) -> Result<Packet<()>> {
        let name = self.reader.read_string()?;
        let major_version = self.reader.read_uvarint()?;
        let minor_version = self.reader.read_uvarint()?;
        let revision = self.reader.read_uvarint()?;
        // The server writes the fields of the revision the client announced.
        let fields = client_info::negotiated(revision);

        // The version of the parallel replicas protocol, not used by clients.
        if fields >= protocol::DBMS_MIN_REVISION_WITH_VERSIONED_PARALLEL_REPLICAS_PROTOCOL {
            self.reader.read_uvarint()?;
        }

        let timezone = if fields >= protocol::DBMS_MIN_REVISION_WITH_SERVER_TIMEZONE {
            match self.reader.read_string()?.parse() {
                Ok(tz) => tz,
                Err(err) => return Err(io::Error::other(err).into()),
            }
        } else {
            Tz::UTC
        };

        let display_name = if fields >= protocol::DBMS_MIN_REVISION_WITH_SERVER_DISPLAY_NAME {
            self.reader.read_string()?
        } else {
            "".into()
        };

        let patch_version = if fields >= protocol::DBMS_MIN_REVISION_WITH_VERSION_PATCH {
            self.reader.read_uvarint()?
        } else {
            0
        };

        // What the server sends and takes: chunked, notchunked, or either
        // with "_optional".
        let (chunked_send, chunked_recv) =
            if fields >= protocol::DBMS_MIN_PROTOCOL_VERSION_WITH_CHUNKED_PACKETS {
                (self.reader.read_string()?, self.reader.read_string()?)
            } else {
                ("notchunked".into(), "notchunked".into())
            };

        // Password complexity rules (pattern, message), for clients that set
        // passwords; not used here.
        if fields >= protocol::DBMS_MIN_PROTOCOL_VERSION_WITH_PASSWORD_COMPLEXITY_RULES {
            for _ in 0..self.reader.read_uvarint()? {
                self.reader.skip_string()?;
                self.reader.skip_string()?;
            }
        }

        // The nonce of the interserver secret, not used by clients.
        if fields >= protocol::DBMS_MIN_REVISION_WITH_INTERSERVER_SECRET_V2 {
            let _nonce: u64 = self.reader.read_scalar()?;
        }

        // Settings of the user's profile for clients that apply them, as
        // (name, flags, value) until an empty name; not applied here.
        if fields >= protocol::DBMS_MIN_REVISION_WITH_SERVER_SETTINGS {
            while !self.reader.read_string()?.is_empty() {
                self.reader.read_uvarint()?;
                self.reader.skip_string()?;
            }
        }

        // Versions of the query plan serialization and of the cluster
        // functions protocol, for servers reading from each other.
        if fields >= protocol::DBMS_MIN_REVISION_WITH_QUERY_PLAN_SERIALIZATION {
            self.reader.read_uvarint()?;
        }
        if fields >= protocol::DBMS_MIN_REVISION_WITH_VERSIONED_CLUSTER_FUNCTION_PROTOCOL {
            self.reader.read_uvarint()?;
        }

        let server_info = ServerInfo {
            name,
            major_version,
            minor_version,
            revision,
            timezone,
            display_name,
            patch_version,
            chunked_send,
            chunked_recv,
        };

        trace!("[hello]        <- {:?}", server_info);
        Ok(Packet::Hello((), server_info))
    }

    fn parse_progress(&mut self, revision: u64) -> Result<Packet<()>> {
        let rows = self.reader.read_uvarint()?;
        let bytes = self.reader.read_uvarint()?;

        let total_rows = if revision >= protocol::DBMS_MIN_REVISION_WITH_TOTAL_ROWS_IN_PROGRESS {
            self.reader.read_uvarint()?
        } else {
            0
        };

        let total_bytes =
            if revision >= protocol::DBMS_MIN_PROTOCOL_VERSION_WITH_TOTAL_BYTES_IN_PROGRESS {
                self.reader.read_uvarint()?
            } else {
                0
            };

        let (written_rows, written_bytes) =
            if revision >= protocol::DBMS_MIN_REVISION_WITH_CLIENT_WRITE_INFO {
                (self.reader.read_uvarint()?, self.reader.read_uvarint()?)
            } else {
                (0, 0)
            };

        let elapsed_ns =
            if revision >= protocol::DBMS_MIN_PROTOCOL_VERSION_WITH_SERVER_QUERY_TIME_IN_PROGRESS {
                self.reader.read_uvarint()?
            } else {
                0
            };

        let progress = Progress {
            rows,
            bytes,
            total_rows,
            total_bytes,
            written_rows,
            written_bytes,
            elapsed_ns,
        };

        trace!(
            "[process] <- Progress: rows={}, bytes={}, total rows={}, written_rows={}, write_bytes={}",
            progress.rows,
            progress.bytes,
            progress.total_rows,
            progress.written_rows,
            progress.written_bytes,
        );

        Ok(Packet::Progress(progress))
    }

    fn parse_profile_info(&mut self, revision: u64) -> Result<Packet<()>> {
        let mut info = ProfileInfo {
            rows: self.reader.read_uvarint()?,
            blocks: self.reader.read_uvarint()?,
            bytes: self.reader.read_uvarint()?,
            applied_limit: self.reader.read_scalar()?,
            rows_before_limit: self.reader.read_uvarint()?,
            calculated_rows_before_limit: self.reader.read_scalar()?,
            applied_aggregation: false,
            rows_before_aggregation: 0,
        };
        if revision >= protocol::DBMS_MIN_REVISION_WITH_ROWS_BEFORE_AGGREGATION {
            info.applied_aggregation = self.reader.read_scalar()?;
            info.rows_before_aggregation = self.reader.read_uvarint()?;
        }
        let info = Packet::ProfileInfo(info);

        trace!("profile_info: {:?}", info);
        Ok(info)
    }

    /// The table's name and columns, in a compressed frame of their own from
    /// 54481 when the connection compresses.
    fn parse_table_columns(&mut self, revision: u64) -> Result<Packet<()>> {
        let compressed = self.info.compress
            && revision >= protocol::DBMS_MIN_REVISION_WITH_COMPRESSED_LOGS_PROFILE_EVENTS_COLUMNS;
        let (table_name, columns) = if compressed {
            let mut reader = compressed::make(&mut self.reader);
            (reader.read_string()?, reader.read_string()?)
        } else {
            (self.reader.read_string()?, self.reader.read_string()?)
        };
        let table_columns = Packet::TableColumns(TableColumns {
            table_name,
            columns,
        });

        trace!("table_columns: {:?}", table_columns);
        Ok(table_columns)
    }

    fn parse_exception(&mut self) -> Result<Packet<()>> {
        let exception = ServerError {
            code: self.reader.read_scalar()?,
            name: self.reader.read_string()?,
            message: self.reader.read_string()?,
            stack_trace: self.reader.read_string()?,
        };

        warn!("server exception: {:?}", exception);
        Ok(Packet::Exception(exception))
    }

    fn parse_pong(&self) -> Packet<()> {
        trace!("[process]      <- pong");
        Packet::Pong(())
    }
}

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

    use super::*;
    use crate::types::Compression;

    fn parse(bytes: &[u8]) -> Result<Packet<()>> {
        let info = TransportInfo {
            timezone: None,
            revision: 0,
            compress: false,
        };
        Parser::new(Cursor::new(bytes), &info).parse_packet(0)
    }

    #[test]
    fn test_http_reply_is_reported_as_http() {
        let reply = b"HTTP/1.0 400 Bad Request\r\nContent-Type: text/html\r\n\r\n";
        let message = parse(reply).unwrap_err().to_string();
        assert!(message.contains("answered over HTTP"), "{message}");
        assert!(message.contains("native port"), "{message}");
    }

    #[test]
    fn test_other_0x48_is_still_an_unknown_packet() {
        let message = parse(b"Hello").unwrap_err().to_string();
        assert!(message.contains("Unknown packet 0x48"), "{message}");
    }

    #[test]
    fn test_short_http_reply_waits_for_more_bytes() {
        assert!(parse(b"HT").unwrap_err().is_would_block());
    }

    /// A ProfileEvents or Log packet: uvarint type, empty name, a block.
    fn service_packet(kind: u64, compression: Compression, revision: u64) -> Vec<u8> {
        use crate::binary::Encoder;

        let block = Block::new()
            .column("name", vec!["SelectedRows"])
            .column("value", vec![7_i64]);
        let mut encoder = Encoder::new();
        encoder.uvarint(kind);
        encoder.string("");
        block.write_at(&mut encoder, compression, revision).unwrap();
        encoder.get_buffer()
    }

    #[test]
    fn test_logs_and_profile_events_are_skipped() {
        // With compression on, they are compressed from 54481, plain before.
        for (revision, compression) in [
            (crate::client_info::CLICK_HOUSE_REVISION, Compression::Lz4),
            (54480, Compression::None),
        ] {
            let info = TransportInfo {
                timezone: Some(Tz::UTC),
                revision,
                compress: true,
            };
            let mut bytes = service_packet(protocol::SERVER_PROFILE_EVENTS, compression, revision);
            bytes.extend(service_packet(protocol::SERVER_LOG, compression, revision));
            bytes.push(protocol::SERVER_PONG as u8);
            let packet = Parser::new(Cursor::new(&bytes[..]), &info).parse_packet(revision);
            assert!(
                matches!(packet, Ok(Packet::Pong(()))),
                "{revision}: {packet:?}"
            );
        }

        // A service packet alone waits for the packet after it.
        let info = TransportInfo {
            timezone: Some(Tz::UTC),
            revision: crate::client_info::CLICK_HOUSE_REVISION,
            compress: false,
        };
        let bytes = service_packet(
            protocol::SERVER_PROFILE_EVENTS,
            Compression::None,
            info.revision,
        );
        // It is read whole and dropped, then the next one is not there yet.
        let mut cursor = Cursor::new(&bytes[..]);
        let packet = Parser::new(&mut cursor, &info).parse_next(info.revision);
        assert!(matches!(packet, Ok(None)), "{packet:?}");
        assert_eq!(cursor.position() as usize, bytes.len());
        let packet = Parser::new(Cursor::new(&bytes[..]), &info).parse_packet(info.revision);
        assert!(packet.unwrap_err().is_would_block());
    }

    #[test]
    fn test_hello_fields_follow_the_announced_revision() {
        // A newer server writes the fields of the revision the client
        // announced: name, version, revision, time zone, display name, patch,
        // chunked framing, password rules, nonce, settings and versions for
        // servers.
        use crate::binary::Encoder;

        let mut encoder = Encoder::new();
        encoder.uvarint(protocol::SERVER_HELLO);
        encoder.string("ClickHouse");
        encoder.uvarint(26);
        encoder.uvarint(11);
        encoder.uvarint(54498);
        encoder.uvarint(4); // parallel replicas protocol
        encoder.string("Europe/Berlin");
        encoder.string("ram9");
        encoder.uvarint(3);
        encoder.string("notchunked_optional");
        encoder.string("chunked_optional");
        encoder.uvarint(1);
        encoder.string("^.{12,}$");
        encoder.string("at least 12 characters");
        encoder.write(0x0123_4567_89ab_cdef_u64);
        // A server setting, then the end of them.
        encoder.string("max_threads");
        encoder.uvarint(0);
        encoder.string("8");
        encoder.string("");
        encoder.uvarint(21); // query plan serialization
        encoder.uvarint(3); // cluster function protocol
        encoder.uvarint(protocol::SERVER_PONG);
        let bytes = encoder.get_buffer();
        let mut cursor = Cursor::new(&bytes[..]);
        let info = TransportInfo {
            timezone: None,
            revision: 0,
            compress: false,
        };
        let hello = Parser::new(&mut cursor, &info).parse_packet(0).unwrap();
        let Packet::Hello((), server) = hello else {
            panic!("{hello:?}");
        };
        assert_eq!((server.revision, server.patch_version), (54498, 3));
        assert_eq!(server.display_name, "ram9");
        assert_eq!(server.chunked_recv, "chunked_optional");
        let next = Parser::new(&mut cursor, &info).parse_packet(0);
        assert!(matches!(next, Ok(Packet::Pong(()))), "{next:?}");
    }

    #[test]
    fn test_short_mismatch_is_reported_without_waiting() {
        let message = parse(b"Hx").unwrap_err().to_string();
        assert!(message.contains("Unknown packet 0x48"), "{message}");
    }
}