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