Skip to main content

encore_clickhouse/
client.rs

1//! The HTTP client: one per server, with the user given per request.
2
3use std::pin::Pin;
4use std::sync::Arc;
5use std::time::Duration;
6
7use bytes::{Buf, Bytes, BytesMut};
8use futures_util::{Stream, StreamExt};
9use tokio::sync::{OwnedSemaphorePermit, Semaphore};
10use url::Url;
11
12use crate::Error;
13use crate::error::exception_in;
14use crate::rowbinary::{Reader, Short};
15use crate::types::Type;
16use crate::value::Value;
17
18/// The most requests in flight at once when the config names no limit.
19pub const DEFAULT_MAX_CONNECTIONS: usize = 100;
20
21/// Up to this much of a response is held on the server until the query
22/// ends, so a query that fails early fails with an HTTP status rather than
23/// after rows. Small, so a selective scan's first rows aren't held back for
24/// long; an exception after rows is found by its tag (see [`Rows`]).
25const RESPONSE_BUFFER: &str = "1048576";
26
27/// A user and password.
28#[derive(Clone, Default)]
29pub struct Credentials {
30    pub user: String,
31    pub password: String,
32}
33
34impl std::fmt::Debug for Credentials {
35    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
36        f.debug_struct("Credentials")
37            .field("user", &self.user)
38            .finish_non_exhaustive()
39    }
40}
41
42#[derive(Clone, Debug)]
43pub struct ClientConfig {
44    /// The base URL of the server's HTTP interface, such as
45    /// `http://127.0.0.1:8123`.
46    pub url: String,
47    /// The TLS to reach an `https` server with: how its certificate is
48    /// verified, and the client's own. The caller builds it, as it does its
49    /// other clients'; it should offer `h2` and `http/1.1`. `None` for a
50    /// server over plain HTTP, as a local one is: no `https` server is
51    /// trusted then.
52    pub tls: Option<rustls::ClientConfig>,
53    /// The most requests in flight at once; 0 for the default.
54    pub max_connections: usize,
55    /// The user of requests that name none.
56    pub credentials: Option<Credentials>,
57}
58
59/// A client of one ClickHouse server. Cheap to clone.
60#[derive(Clone)]
61pub struct Client {
62    inner: Arc<Inner>,
63}
64
65struct Inner {
66    http: reqwest::Client,
67    base: Url,
68    credentials: Option<Credentials>,
69    limit: Arc<Semaphore>,
70}
71
72impl std::fmt::Debug for Client {
73    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
74        f.debug_struct("Client")
75            .field("url", &self.inner.base.as_str())
76            .finish_non_exhaustive()
77    }
78}
79
80/// One query: its SQL, parameters and settings.
81#[derive(Clone, Debug, Default)]
82pub struct Request {
83    pub sql: String,
84    /// The database unqualified names resolve in; the user's default when
85    /// unset.
86    pub database: Option<String>,
87    /// `param_<name>` values, as text (see [`Value::to_param_text`]).
88    pub params: Vec<(String, Vec<u8>)>,
89    pub settings: Vec<(String, String)>,
90    pub query_id: Option<String>,
91    /// Overrides the client's user.
92    pub credentials: Option<Credentials>,
93}
94
95impl Request {
96    pub fn new(sql: impl Into<String>) -> Self {
97        Request {
98            sql: sql.into(),
99            ..Default::default()
100        }
101    }
102
103    pub fn database(mut self, db: impl Into<String>) -> Self {
104        self.database = Some(db.into());
105        self
106    }
107
108    /// Binds `{name:Type}` to a value.
109    pub fn param(mut self, name: impl Into<String>, value: &Value) -> Self {
110        self.params.push((name.into(), value.to_param_text()));
111        self
112    }
113
114    pub fn setting(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
115        self.settings.push((name.into(), value.into()));
116        self
117    }
118
119    pub fn query_id(mut self, id: impl Into<String>) -> Self {
120        self.query_id = Some(id.into());
121        self
122    }
123
124    pub fn credentials(mut self, c: Credentials) -> Self {
125        self.credentials = Some(c);
126        self
127    }
128}
129
130/// What the server reports a query did (`X-ClickHouse-Summary`).
131#[derive(Clone, Debug, Default, PartialEq, Eq)]
132pub struct Summary {
133    pub query_id: String,
134    pub read_rows: u64,
135    pub read_bytes: u64,
136    pub written_rows: u64,
137    pub written_bytes: u64,
138    pub result_rows: u64,
139    pub elapsed_ns: u64,
140}
141
142impl Summary {
143    fn from_headers(h: &reqwest::header::HeaderMap) -> Summary {
144        let mut s = Summary {
145            query_id: header(h, "x-clickhouse-query-id").unwrap_or_default(),
146            ..Default::default()
147        };
148        let Some(json) = header(h, "x-clickhouse-summary") else {
149            return s;
150        };
151        let Ok(serde_json::Value::Object(m)) = serde_json::from_str::<serde_json::Value>(&json)
152        else {
153            return s;
154        };
155        let num = |k: &str| -> u64 {
156            match m.get(k) {
157                Some(serde_json::Value::String(v)) => v.parse().unwrap_or(0),
158                Some(serde_json::Value::Number(n)) => n.as_u64().unwrap_or(0),
159                _ => 0,
160            }
161        };
162        s.read_rows = num("read_rows");
163        s.read_bytes = num("read_bytes");
164        s.written_rows = num("written_rows");
165        s.written_bytes = num("written_bytes");
166        s.result_rows = num("result_rows");
167        s.elapsed_ns = num("elapsed_ns");
168        s
169    }
170}
171
172fn header(h: &reqwest::header::HeaderMap, name: &str) -> Option<String> {
173    h.get(name)?.to_str().ok().map(str::to_string)
174}
175
176/// A result column.
177#[derive(Clone, Debug, PartialEq)]
178pub struct Column {
179    pub name: String,
180    /// The type's name as the server gave it.
181    pub type_name: String,
182    pub ty: Type,
183}
184
185/// The TLS of a client given none: it trusts no server, so a call to an
186/// `https` URL fails at its handshake.
187///
188/// reqwest's own TLS is not left to stand in for it. That verifies with the
189/// system's CA certificates, and a client of it does not build on a Linux
190/// machine that has none, whatever its URL.
191fn no_tls() -> rustls::ClientConfig {
192    rustls::ClientConfig::builder_with_provider(Arc::new(
193        rustls::crypto::aws_lc_rs::default_provider(),
194    ))
195    .with_safe_default_protocol_versions()
196    .expect("aws-lc-rs supports rustls's default protocol versions")
197    .with_root_certificates(rustls::RootCertStore::empty())
198    .with_no_client_auth()
199}
200
201impl Client {
202    pub fn new(cfg: ClientConfig) -> Result<Client, Error> {
203        let base = Url::parse(&cfg.url)
204            .map_err(|e| Error::InvalidArgument(format!("ClickHouse URL {:?}: {e}", cfg.url)))?;
205        if !matches!(base.scheme(), "http" | "https") {
206            return Err(Error::InvalidArgument(format!(
207                "ClickHouse URL {:?}: the scheme must be http or https",
208                cfg.url
209            )));
210        }
211        let mut b = reqwest::Client::builder()
212            .connect_timeout(Duration::from_secs(10))
213            // Below ClickHouse's own keep-alive timeout, so a pooled
214            // connection is not reused just as the server closes it.
215            .pool_idle_timeout(Duration::from_secs(2))
216            .tcp_nodelay(true);
217        b = b.tls_backend_preconfigured(cfg.tls.unwrap_or_else(no_tls));
218        let http = b
219            .build()
220            .map_err(|e| Error::InvalidArgument(format!("build the HTTP client: {e}")))?;
221        let max = if cfg.max_connections == 0 {
222            DEFAULT_MAX_CONNECTIONS
223        } else {
224            cfg.max_connections
225        };
226        Ok(Client {
227            inner: Arc::new(Inner {
228                http,
229                base,
230                credentials: cfg.credentials,
231                limit: Arc::new(Semaphore::new(max)),
232            }),
233        })
234    }
235
236    /// The server's base URL.
237    pub fn url(&self) -> &Url {
238        &self.inner.base
239    }
240
241    /// Whether the server answers (`GET /ping`).
242    pub async fn ping(&self) -> Result<(), Error> {
243        let url = self
244            .inner
245            .base
246            .join("ping")
247            .map_err(|e| Error::InvalidArgument(e.to_string()))?;
248        let resp = self.inner.http.get(url).send().await.map_err(transport)?;
249        if resp.status().is_success() {
250            Ok(())
251        } else {
252            Err(Error::Unavailable(format!("ping: {}", resp.status())))
253        }
254    }
255
256    /// Runs a query and streams its rows.
257    pub async fn query(&self, req: Request) -> Result<Rows, Error> {
258        let mut req = req;
259        default_setting(&mut req, "default_format", "RowBinaryWithNamesAndTypes");
260        default_setting(&mut req, "output_format_binary_write_json_as_string", "1");
261        default_setting(&mut req, "http_response_buffer_size", RESPONSE_BUFFER);
262        let body = req.sql.clone().into_bytes();
263        let (resp, permit) = self.send(&req, None, body).await?;
264        let summary = Summary::from_headers(resp.headers());
265        // The marker an exception after streamed rows starts with: without
266        // it, the exception's text could be read as rows.
267        let marker = header(resp.headers(), "x-clickhouse-exception-tag")
268            .map(|tag| format!("__exception__\r\n{tag}").into_bytes());
269        let mut rows = Rows {
270            columns: Arc::from(Vec::new()),
271            stream: Box::pin(resp.bytes_stream()),
272            buf: BytesMut::new(),
273            done: false,
274            summary,
275            marker,
276            scanned: 0,
277            exception: None,
278            max_row_bytes: None,
279            _permit: permit,
280        };
281        rows.read_header().await?;
282        Ok(rows)
283    }
284
285    /// Runs a statement, discarding any result.
286    pub async fn exec(&self, req: Request) -> Result<Summary, Error> {
287        let body = req.sql.clone().into_bytes();
288        let (resp, _permit) = self.send(&req, None, body).await?;
289        let summary = Summary::from_headers(resp.headers());
290        // Read the body to its end: an exception after a streamed start
291        // shows up in it.
292        let body = resp.bytes().await.map_err(transport)?;
293        if let Some(e) = exception_in(tail(&body)) {
294            return Err(e);
295        }
296        Ok(summary)
297    }
298
299    /// Inserts rows into a table as `JSONEachRow`: each row's values are
300    /// for `columns`, in order. A `None` leaves the column out of that row,
301    /// which gives it the column's default; `Some(Value::Null)` is a NULL
302    /// (the default too, for a column that isn't `Nullable`). `req.sql` is
303    /// ignored.
304    pub async fn insert(
305        &self,
306        req: Request,
307        table: &str,
308        columns: &[String],
309        rows: &[Vec<Option<Value>>],
310    ) -> Result<Summary, Error> {
311        if columns.is_empty() {
312            return Err(Error::InvalidArgument(
313                "an insert needs at least one column".into(),
314            ));
315        }
316        let mut sql = format!("INSERT INTO {} (", quote_table(table)?);
317        for (i, c) in columns.iter().enumerate() {
318            if i > 0 {
319                sql.push_str(", ");
320            }
321            sql.push_str(&quote_ident(c));
322        }
323        sql.push_str(") FORMAT JSONEachRow");
324
325        let mut body = String::new();
326        for row in rows {
327            if row.len() != columns.len() {
328                return Err(Error::InvalidArgument(format!(
329                    "a row has {} values for {} columns",
330                    row.len(),
331                    columns.len()
332                )));
333            }
334            body.push('{');
335            let mut first = true;
336            for (c, v) in columns.iter().zip(row) {
337                let Some(v) = v else { continue };
338                if !first {
339                    body.push(',');
340                }
341                first = false;
342                body.push_str(&serde_json::Value::String(c.clone()).to_string());
343                body.push(':');
344                v.write_json(&mut body);
345            }
346            body.push_str("}\n");
347        }
348        let mut req = req;
349        req.sql = sql;
350        default_setting(&mut req, "date_time_input_format", "best_effort");
351        // Tuples are written as arrays, named ones too.
352        default_setting(&mut req, "input_format_json_named_tuples_as_objects", "0");
353        default_setting(&mut req, "input_format_defaults_for_omitted_fields", "1");
354        let (resp, _permit) = self.send(&req, Some(()), body.into_bytes()).await?;
355        let summary = Summary::from_headers(resp.headers());
356        let body = resp.bytes().await.map_err(transport)?;
357        if let Some(e) = exception_in(tail(&body)) {
358            return Err(e);
359        }
360        Ok(summary)
361    }
362
363    /// POSTs a request. With `data`, the SQL goes in the URL and `body` is the
364    /// statement's data; otherwise `body` is the SQL.
365    async fn send(
366        &self,
367        req: &Request,
368        data: Option<()>,
369        body: Vec<u8>,
370    ) -> Result<(reqwest::Response, OwnedSemaphorePermit), Error> {
371        let permit = self
372            .inner
373            .limit
374            .clone()
375            .acquire_owned()
376            .await
377            .map_err(|_| Error::Unavailable("the client is closed".into()))?;
378
379        let mut url = self.inner.base.clone();
380        let mut q = String::new();
381        let mut add = |k: &[u8], v: &[u8]| {
382            if !q.is_empty() {
383                q.push('&');
384            }
385            q.extend(url::form_urlencoded::byte_serialize(k));
386            q.push('=');
387            q.extend(url::form_urlencoded::byte_serialize(v));
388        };
389        if let Some(db) = &req.database {
390            add(b"database", db.as_bytes());
391        }
392        if let Some(id) = &req.query_id {
393            add(b"query_id", id.as_bytes());
394        }
395        if data.is_some() {
396            add(b"query", req.sql.as_bytes());
397        }
398        for (k, v) in &req.settings {
399            add(k.as_bytes(), v.as_bytes());
400        }
401        for (k, v) in &req.params {
402            let key = format!("param_{k}");
403            add(key.as_bytes(), v);
404        }
405        url.set_query(if q.is_empty() { None } else { Some(&q) });
406
407        let mut r = self.inner.http.post(url).body(body);
408        if let Some(c) = req.credentials.as_ref().or(self.inner.credentials.as_ref()) {
409            r = r
410                .header("X-ClickHouse-User", &c.user)
411                .header("X-ClickHouse-Key", &c.password);
412        }
413        let resp = r.send().await.map_err(transport)?;
414        if !resp.status().is_success() {
415            let code =
416                header(resp.headers(), "x-clickhouse-exception-code").and_then(|c| c.parse().ok());
417            let status = resp.status();
418            let text = resp.text().await.unwrap_or_default();
419            if text.trim().is_empty() {
420                return Err(Error::Server {
421                    code: code.unwrap_or_default(),
422                    name: String::new(),
423                    message: format!("ClickHouse answered {status}"),
424                });
425            }
426            return Err(Error::from_exception(&text, code));
427        }
428        Ok((resp, permit))
429    }
430}
431
432/// Sets a setting the request doesn't set itself.
433fn default_setting(req: &mut Request, name: &str, value: &str) {
434    if !req.settings.iter().any(|(k, _)| k == name) {
435        req.settings.push((name.into(), value.into()));
436    }
437}
438
439/// The last few KiB of a body, where an exception after streamed rows is.
440fn tail(b: &[u8]) -> &[u8] {
441    &b[b.len().saturating_sub(64 * 1024)..]
442}
443
444fn transport(e: reqwest::Error) -> Error {
445    if e.is_connect() || e.is_timeout() {
446        Error::Unavailable(error_chain(&e))
447    } else if e.is_body() || e.is_decode() {
448        Error::Decode(error_chain(&e))
449    } else {
450        Error::Unavailable(error_chain(&e))
451    }
452}
453
454fn error_chain(e: &dyn std::error::Error) -> String {
455    let mut s = e.to_string();
456    let mut src = e.source();
457    while let Some(c) = src {
458        s.push_str(": ");
459        s.push_str(&c.to_string());
460        src = c.source();
461    }
462    s
463}
464
465/// Quotes an identifier with backquotes.
466pub fn quote_ident(name: &str) -> String {
467    let mut s = String::with_capacity(name.len() + 2);
468    s.push('`');
469    for c in name.chars() {
470        match c {
471            '`' => s.push_str("\\`"),
472            '\\' => s.push_str("\\\\"),
473            c => s.push(c),
474        }
475    }
476    s.push('`');
477    s
478}
479
480/// Quotes a table name, `db.table` split at its first dot.
481pub fn quote_table(table: &str) -> Result<String, Error> {
482    let parts: Vec<&str> = match table.split_once('.') {
483        Some((db, t)) => vec![db, t],
484        None => vec![table],
485    };
486    if parts.iter().any(|p| p.is_empty()) {
487        return Err(Error::InvalidArgument(format!(
488            "invalid table name {table:?}"
489        )));
490    }
491    Ok(parts
492        .into_iter()
493        .map(quote_ident)
494        .collect::<Vec<_>>()
495        .join("."))
496}
497
498/// A query's rows, decoded as they arrive. Dropping it closes the response,
499/// which stops a read-only query on the server
500/// (`cancel_http_readonly_queries_on_client_close`).
501pub struct Rows {
502    columns: Arc<[Column]>,
503    stream: Pin<Box<dyn Stream<Item = reqwest::Result<Bytes>> + Send>>,
504    buf: BytesMut,
505    done: bool,
506    summary: Summary,
507    /// See [`Client::query`].
508    marker: Option<Vec<u8>>,
509    /// How much of `buf` has been searched for the marker.
510    scanned: usize,
511    /// The exception the stream ended with, after the rows before it.
512    exception: Option<Error>,
513    /// See [`Rows::max_row_bytes`].
514    max_row_bytes: Option<usize>,
515    _permit: OwnedSemaphorePermit,
516}
517
518impl std::fmt::Debug for Rows {
519    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
520        f.debug_struct("Rows")
521            .field("columns", &self.columns)
522            .finish_non_exhaustive()
523    }
524}
525
526impl Rows {
527    pub fn columns(&self) -> &Arc<[Column]> {
528        &self.columns
529    }
530
531    /// What the server reported when the response started: its query id,
532    /// and how much it had read by then.
533    pub fn summary(&self) -> &Summary {
534        &self.summary
535    }
536
537    /// Refuses a row of more than `bytes` as the server encodes it, rather
538    /// than decoding it: [`next`](Self::next) decodes only within the first
539    /// `bytes` of what has arrived, and fails with [`Error::InvalidArgument`]
540    /// once that much has arrived without a whole row in it. What is held is
541    /// at most `bytes` and one read from the connection.
542    pub fn max_row_bytes(&mut self, bytes: usize) {
543        self.max_row_bytes = Some(bytes);
544    }
545
546    async fn fill(&mut self) -> Result<bool, Error> {
547        if self.exception.is_some() {
548            self.done = true;
549            return Ok(false);
550        }
551        match self.stream.next().await {
552            Some(Ok(chunk)) => {
553                self.buf.extend_from_slice(&chunk);
554                self.find_exception();
555                Ok(true)
556            }
557            Some(Err(e)) => {
558                self.done = true;
559                Err(exception_in(&self.buf).unwrap_or_else(|| transport(e)))
560            }
561            None => {
562                self.done = true;
563                Ok(false)
564            }
565        }
566    }
567
568    /// Cuts the buffer at an exception's marker, keeping the exception for
569    /// when the rows before it have been read.
570    fn find_exception(&mut self) {
571        let Some(marker) = &self.marker else { return };
572        let from = self.scanned.saturating_sub(marker.len());
573        let found = self.buf[from..]
574            .windows(marker.len())
575            .position(|w| w == marker.as_slice());
576        match found {
577            Some(at) => {
578                let at = from + at;
579                let text = self.buf.split_off(at);
580                // The block is preceded by a line break.
581                if self.buf.ends_with(b"\r\n") {
582                    self.buf.truncate(self.buf.len() - 2);
583                }
584                self.exception = Some(exception_in(&text).unwrap_or_else(|| {
585                    Error::from_exception(&String::from_utf8_lossy(&text), None)
586                }));
587                self.scanned = self.buf.len();
588            }
589            None => self.scanned = self.buf.len(),
590        }
591    }
592
593    /// Advances past `n` decoded bytes.
594    fn consume(&mut self, n: usize) {
595        self.buf.advance(n);
596        self.scanned = self.scanned.saturating_sub(n);
597    }
598
599    /// The error the stream ended with, with what was left undecoded.
600    fn ended(&mut self, what: &str) -> Error {
601        if let Some(e) = self.exception.take() {
602            return e;
603        }
604        exception_in(&self.buf).unwrap_or_else(|| Error::Decode(what.into()))
605    }
606
607    async fn read_header(&mut self) -> Result<(), Error> {
608        loop {
609            if !self.buf.is_empty() {
610                let mut r = Reader::new(&self.buf);
611                match header_of(&mut r) {
612                    Ok(cols) => {
613                        let used = r.pos;
614                        self.consume(used);
615                        self.columns = Arc::from(cols);
616                        return Ok(());
617                    }
618                    Err(Short::Incomplete) => {}
619                    Err(Short::Invalid(e)) => return Err(exception_in(&self.buf).unwrap_or(e)),
620                }
621            }
622            if self.done {
623                // No header at all: a statement with no result.
624                if self.buf.is_empty() && self.exception.is_none() {
625                    return Ok(());
626                }
627                return Err(self.ended("truncated header"));
628            }
629            self.fill().await?;
630        }
631    }
632
633    /// The next row's values, in column order.
634    pub async fn next(&mut self) -> Result<Option<Vec<Value>>, Error> {
635        loop {
636            if !self.buf.is_empty() {
637                // Only a row within the limit can be decoded: a larger one
638                // reads as incomplete before any of it is copied out.
639                let window = match self.max_row_bytes {
640                    Some(max) => &self.buf[..self.buf.len().min(max)],
641                    None => &self.buf[..],
642                };
643                let mut r = Reader::new(window);
644                let mut row = Vec::with_capacity(self.columns.len());
645                let mut short = None;
646                for c in self.columns.iter() {
647                    match r.value(&c.ty) {
648                        Ok(v) => row.push(v),
649                        Err(e) => {
650                            short = Some(e);
651                            break;
652                        }
653                    }
654                }
655                match short {
656                    None => {
657                        let used = r.pos;
658                        self.consume(used);
659                        return Ok(Some(row));
660                    }
661                    Some(Short::Incomplete) => {
662                        // Incomplete with a full window: the row doesn't fit.
663                        if let Some(max) = self.max_row_bytes
664                            && self.buf.len() >= max
665                        {
666                            return Err(Error::InvalidArgument(format!(
667                                "a row of the result is larger than {max} bytes"
668                            )));
669                        }
670                    }
671                    Some(Short::Invalid(e)) => {
672                        return Err(self.exception.take().unwrap_or(e));
673                    }
674                }
675            }
676            if self.done {
677                if self.buf.is_empty() && self.exception.is_none() {
678                    return Ok(None);
679                }
680                return Err(self.ended("truncated row"));
681            }
682            self.fill().await?;
683        }
684    }
685
686    /// Every remaining row.
687    pub async fn collect(mut self) -> Result<Vec<Vec<Value>>, Error> {
688        let mut out = Vec::new();
689        while let Some(r) = self.next().await? {
690            out.push(r);
691        }
692        Ok(out)
693    }
694}
695
696fn header_of(r: &mut Reader<'_>) -> Result<Vec<Column>, Short> {
697    let n = r.varint()?;
698    if n > 100_000 {
699        return Err(Short::Invalid(Error::Decode(format!(
700            "implausible column count {n}"
701        ))));
702    }
703    let mut names = Vec::with_capacity(n as usize);
704    for _ in 0..n {
705        names.push(r.string()?);
706    }
707    let mut cols = Vec::with_capacity(n as usize);
708    for name in names {
709        let type_name = r.string()?;
710        let ty = Type::parse(&type_name)?;
711        cols.push(Column {
712            name,
713            type_name,
714            ty,
715        });
716    }
717    Ok(cols)
718}