Skip to main content

scopedb_client/
client.rs

1// Copyright 2024 ScopeDB, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::fmt;
16use std::time::Duration;
17
18use fastrace_reqwest::traceparent_headers;
19use reqwest::IntoUrl;
20use reqwest::Method;
21use reqwest::StatusCode;
22use reqwest::Url;
23use reqwest::header::AUTHORIZATION;
24use reqwest::header::CONTENT_ENCODING;
25use reqwest::header::CONTENT_TYPE;
26use reqwest::header::HeaderValue;
27use serde::Serialize;
28use uuid::Uuid;
29
30use crate::AppendErrorDetails;
31use crate::AppendOutcome;
32use crate::AppendRowsResult;
33use crate::Catalog;
34use crate::Error;
35use crate::ErrorKind;
36use crate::ErrorOperation;
37use crate::ResultSet;
38use crate::Statement;
39use crate::StatementHandle;
40use crate::StatementStatus;
41use crate::Table;
42use crate::protocol::StatementRequest;
43use crate::protocol::apply_response_metadata;
44use crate::protocol::decode_append_error;
45use crate::protocol::decode_statement_response;
46
47const JSON_CONTENT_ENCODING: &str = "zstd";
48const UNCOMPRESSED_CONTENT_LENGTH: &str = "X-ScopeDB-Uncompressed-Content-Length";
49const ZSTD_COMPRESSION_LEVEL: i32 = 3;
50pub const MAX_APPEND_BODY_BYTES: usize = 8 * 1024 * 1024;
51pub const MAX_APPEND_ROWS: usize = 200_000;
52const DEFAULT_WRITE_TIMEOUT: Duration = Duration::from_secs(30);
53
54/// An async client for queries, table writes, and catalog operations.
55///
56/// Start with [`builder`](Self::builder) to configure your endpoint and API key.
57/// Clones share the underlying HTTP connection pool.
58#[derive(Debug, Clone)]
59pub struct Client {
60    endpoint: Url,
61    client: reqwest::Client,
62    authorization: Option<HeaderValue>,
63    write_timeout: Duration,
64}
65
66/// Builder for a [`Client`] with an optional API key, write timeout, and custom HTTP client.
67pub struct ClientBuilder {
68    endpoint: String,
69    client: Option<reqwest::Client>,
70    api_key: Option<String>,
71    write_timeout: Duration,
72}
73
74impl fmt::Debug for ClientBuilder {
75    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
76        f.debug_struct("ClientBuilder")
77            .field("endpoint", &self.endpoint)
78            .field("client", &self.client)
79            .field("has_api_key", &self.api_key.is_some())
80            .field("write_timeout", &self.write_timeout)
81            .finish()
82    }
83}
84
85impl ClientBuilder {
86    /// Sets the Bearer API key attached to each request.
87    ///
88    /// Overrides any default `Authorization` header on a custom HTTP client.
89    pub fn api_key(mut self, api_key: impl Into<String>) -> Self {
90        self.api_key = Some(api_key.into());
91        self
92    }
93
94    /// Sets a custom HTTP client for TLS, proxy, and connection-pool settings.
95    ///
96    /// Construct the client with [`reqwest`](crate::reqwest) and disable redirects and
97    /// transport retries so writes are not replayed at the HTTP layer:
98    ///
99    /// ```
100    /// use scopedb_client::reqwest;
101    ///
102    /// let http_client = reqwest::Client::builder()
103    ///     .redirect(reqwest::redirect::Policy::none())
104    ///     .retry(reqwest::retry::never())
105    ///     .build()?;
106    /// # Ok::<(), reqwest::Error>(())
107    /// ```
108    pub fn http_client(mut self, client: reqwest::Client) -> Self {
109        self.client = Some(client);
110        self
111    }
112
113    /// Sets the per-attempt timeout for table appends and catalog mutations,
114    /// including reading the response body.
115    ///
116    /// Defaults to 30 seconds and must be finite and positive.
117    /// [`AppendWriterBuilder::attempt_timeout`](crate::AppendWriterBuilder::attempt_timeout) and
118    /// [`AppendStreamBuilder::attempt_timeout`](crate::AppendStreamBuilder::attempt_timeout)
119    /// override this default. Timeouts configured on a custom HTTP client also apply.
120    ///
121    /// A timed-out write has an ambiguous outcome and is not replayed
122    /// automatically. Append timeouts populate [`Error::write_details`], and
123    /// catalog mutation timeouts set [`Error::catalog_outcome`] to
124    /// [`CatalogMutationOutcome::Unknown`](crate::CatalogMutationOutcome::Unknown).
125    pub fn write_timeout(mut self, timeout: Duration) -> Self {
126        self.write_timeout = timeout;
127        self
128    }
129
130    /// Validates configuration and builds the [`Client`].
131    pub fn build(self) -> Result<Client, Error> {
132        if self.write_timeout.is_zero() {
133            return Err(Error::new(
134                ErrorKind::InvalidInput,
135                ErrorOperation::BuildClient,
136                "write_timeout must be greater than zero",
137            ));
138        }
139        if tokio::time::Instant::now()
140            .checked_add(self.write_timeout)
141            .is_none()
142        {
143            return Err(Error::new(
144                ErrorKind::InvalidInput,
145                ErrorOperation::BuildClient,
146                "write_timeout is too large",
147            ));
148        }
149        let http_client = match self.client {
150            Some(client) => client,
151            None => reqwest::Client::builder()
152                .redirect(reqwest::redirect::Policy::none())
153                .retry(reqwest::retry::never())
154                .build()
155                .map_err(|err| {
156                    Error::new(
157                        ErrorKind::InvalidInput,
158                        ErrorOperation::BuildClient,
159                        "failed to build HTTP client",
160                    )
161                    .set_source(err)
162                })?,
163        };
164        let mut client = Client::new(self.endpoint, http_client)?;
165        client.write_timeout = self.write_timeout;
166        if let Some(api_key) = self.api_key {
167            if api_key.is_empty() {
168                return Err(Error::new(
169                    ErrorKind::InvalidInput,
170                    ErrorOperation::BuildClient,
171                    "api_key must not be empty",
172                ));
173            }
174            let mut authorization =
175                HeaderValue::from_str(&format!("Bearer {api_key}")).map_err(|err| {
176                    Error::new(
177                        ErrorKind::InvalidInput,
178                        ErrorOperation::BuildClient,
179                        "api_key is not a valid HTTP credential",
180                    )
181                    .set_source(err)
182                })?;
183            authorization.set_sensitive(true);
184            client.authorization = Some(authorization);
185        }
186        Ok(client)
187    }
188}
189
190impl Client {
191    /// Returns a builder for `endpoint`.
192    pub fn builder(endpoint: impl ToString) -> ClientBuilder {
193        ClientBuilder {
194            endpoint: endpoint.to_string(),
195            client: None,
196            api_key: None,
197            write_timeout: DEFAULT_WRITE_TIMEOUT,
198        }
199    }
200
201    /// Creates a client from an HTTP(S) endpoint URL and a
202    /// [`reqwest::Client`](crate::reqwest::Client).
203    ///
204    /// Configure `client` as shown in [`ClientBuilder::http_client`]. The write
205    /// timeout defaults to 30 seconds; use [`builder`](Self::builder) to customize it or
206    /// attach an API key.
207    pub fn new<E: IntoUrl>(endpoint: E, client: reqwest::Client) -> Result<Self, Error> {
208        match endpoint.into_url() {
209            Ok(mut endpoint) => {
210                if !matches!(endpoint.scheme(), "http" | "https")
211                    || endpoint.host_str().is_none()
212                    || !endpoint.username().is_empty()
213                    || endpoint.password().is_some()
214                    || endpoint.query().is_some()
215                    || endpoint.fragment().is_some()
216                {
217                    return Err(Error::new(
218                        ErrorKind::InvalidInput,
219                        ErrorOperation::BuildClient,
220                        "endpoint must be an HTTP(S) URL without credentials, query, or fragment",
221                    ));
222                }
223                if !endpoint.path().ends_with('/') {
224                    let path = format!("{}/", endpoint.path());
225                    endpoint.set_path(&path);
226                }
227                Ok(Self {
228                    endpoint,
229                    client,
230                    authorization: None,
231                    write_timeout: DEFAULT_WRITE_TIMEOUT,
232                })
233            }
234            Err(err) => Err(Error::new(
235                ErrorKind::InvalidInput,
236                ErrorOperation::BuildClient,
237                "failed to parse endpoint".to_string(),
238            )
239            .set_source(err)),
240        }
241    }
242
243    /// Creates a [`Statement`] builder for `statement`.
244    pub fn statement(&self, statement: impl Into<String>) -> Statement {
245        Statement::new(self.clone(), statement.into())
246    }
247
248    /// Returns a [`StatementHandle`] for an existing `statement_id` without making a request.
249    pub fn statement_handle(&self, statement_id: Uuid) -> StatementHandle {
250        StatementHandle::new(self.clone(), statement_id)
251    }
252
253    /// Selects `table` in the default `scopedb.public` namespace.
254    pub fn table(&self, table: impl Into<String>) -> Table {
255        Table::new(self.clone(), table.into())
256    }
257
258    /// Submits `statement` and waits for its [`ResultSet`].
259    ///
260    /// If waiting fails after submission, pass [`Error::statement_id`] to
261    /// [`statement_handle`](Self::statement_handle) to inspect or resume waiting on the running
262    /// execution rather than resubmitting the query.
263    pub async fn query(&self, statement: impl Into<String>) -> Result<ResultSet, Error> {
264        self.statement(statement).execute().await
265    }
266
267    /// Accesses the declarative [`Catalog`].
268    pub fn catalog(&self) -> Catalog {
269        Catalog::new(self.clone())
270    }
271
272    /// Appends newline-delimited JSON rows to `database.schema.table` in a single request.
273    ///
274    /// See [`Table::append`] for payload limits and recovery semantics.
275    pub async fn append_rows(
276        &self,
277        database: &str,
278        schema: &str,
279        table: &str,
280        ndjson: impl Into<String>,
281    ) -> Result<AppendRowsResult, Error> {
282        self.append_rows_with_timeout(database, schema, table, ndjson.into(), None)
283            .await
284    }
285
286    pub(crate) async fn append_rows_with_timeout(
287        &self,
288        database: &str,
289        schema: &str,
290        table: &str,
291        ndjson: String,
292        timeout: Option<Duration>,
293    ) -> Result<AppendRowsResult, Error> {
294        if ndjson.len() > MAX_APPEND_BODY_BYTES {
295            return Err(append_definite_failure(format!(
296                "append payload requires {} bytes, exceeds the {MAX_APPEND_BODY_BYTES}-byte append limit",
297                ndjson.len()
298            )));
299        }
300        let expected_rows = ndjson
301            .lines()
302            .filter(|line| !line.trim().is_empty())
303            .count();
304        if expected_rows > MAX_APPEND_ROWS {
305            return Err(append_definite_failure(format!(
306                "append payload exceeds the {MAX_APPEND_ROWS}-row limit",
307            )));
308        }
309        let url = self.make_resource_url(&[
310            "catalog",
311            "databases",
312            database,
313            "schemas",
314            schema,
315            "tables",
316            table,
317            "ingest",
318        ])?;
319        let body =
320            zstd::stream::encode_all(ndjson.as_bytes(), ZSTD_COMPRESSION_LEVEL).map_err(|err| {
321                append_definite_failure("failed to compress table append request body")
322                    .set_source(err)
323            })?;
324        let request = self
325            .request(Method::POST, url)
326            .headers(traceparent_headers())
327            .header(reqwest::header::CONTENT_TYPE, "application/x-ndjson")
328            .header(reqwest::header::CONTENT_ENCODING, JSON_CONTENT_ENCODING)
329            .body(body);
330        let mut status = None;
331        let mut headers = reqwest::header::HeaderMap::new();
332        tokio::time::timeout(timeout.unwrap_or(self.write_timeout), async {
333            let response = request.send().await.map_err(|err| {
334                let error = if err.is_timeout() {
335                    append_ambiguous_error(ErrorKind::Timeout, "table append request timed out; write outcome is ambiguous")
336                        .set_write_timeout()
337                } else {
338                    append_ambiguous_error(ErrorKind::Unavailable, "failed to send table append request")
339                };
340                error.set_source(err)
341            })?;
342            let response_status = response.status();
343            status = Some(response_status);
344            headers = response.headers().clone();
345            let payload = response.bytes().await.map_err(|err| {
346                let error = if err.is_timeout() {
347                    append_ambiguous_error(ErrorKind::Timeout, "table append request timed out; write outcome is ambiguous")
348                        .set_write_timeout()
349                } else {
350                    append_ambiguous_error(ErrorKind::Unavailable, "failed to read table append response")
351                };
352                error.set_source(err)
353            })?;
354            let result = decode_append_response(response_status, &headers, &payload)?;
355            if result.num_rows_inserted != expected_rows as i64 {
356                return Err(append_ambiguous_error(ErrorKind::InvalidResponse, format!(
357                    "table append response reported {} inserted rows for a {expected_rows}-row request",
358                    result.num_rows_inserted
359                )));
360            }
361            Ok(result)
362        })
363        .await
364        .unwrap_or_else(|err| {
365            Err(
366                append_ambiguous_error(ErrorKind::Timeout, "table append request timed out; write outcome is ambiguous")
367                    .set_write_timeout()
368                    .set_source(err),
369            )
370        })
371        .map_err(|err| match status {
372            Some(status) if err.http_status().is_none() => {
373                apply_response_metadata(err, status, &headers)
374            }
375            _ => err,
376        })
377    }
378}
379
380impl Client {
381    #[fastrace::trace]
382    pub(crate) async fn submit_statement(
383        &self,
384        request: StatementRequest,
385    ) -> Result<StatementStatus, Error> {
386        let url = self.make_url("v1/statements")?;
387        let response = self
388            .post_json(url, &request)?
389            .headers(traceparent_headers())
390            .send()
391            .await
392            .map_err(|err| {
393                Error::new(
394                    if err.is_timeout() {
395                        ErrorKind::Timeout
396                    } else {
397                        ErrorKind::Unavailable
398                    },
399                    ErrorOperation::SubmitStatement,
400                    "failed to submit statement",
401                )
402                .set_source(err)
403            })?;
404        decode_statement_response(response, ErrorOperation::SubmitStatement).await
405    }
406
407    #[fastrace::trace]
408    pub(crate) async fn fetch_statement(
409        &self,
410        statement_id: Uuid,
411    ) -> Result<StatementStatus, Error> {
412        let path = format!("v1/statements/{statement_id}");
413        let url = self.make_url(&path)?;
414        let response = self
415            .request(Method::GET, url)
416            .headers(traceparent_headers())
417            .query(&[("format", "json")])
418            .send()
419            .await
420            .map_err(|err| {
421                Error::new(
422                    if err.is_timeout() {
423                        ErrorKind::Timeout
424                    } else {
425                        ErrorKind::Unavailable
426                    },
427                    ErrorOperation::RefreshStatement,
428                    format!("failed to fetch statement: {statement_id:?}"),
429                )
430                .set_source(err)
431                .with_transient_failure(true)
432            })?;
433        decode_statement_response(response, ErrorOperation::RefreshStatement).await
434    }
435
436    #[fastrace::trace]
437    pub(crate) async fn cancel_statement(
438        &self,
439        statement_id: Uuid,
440    ) -> Result<StatementStatus, Error> {
441        let path = format!("v1/statements/{statement_id}/cancel");
442        let url = self.make_url(&path)?;
443        let response = self
444            .request(Method::POST, url)
445            .headers(traceparent_headers())
446            .query(&[("format", "json")])
447            .send()
448            .await
449            .map_err(|err| {
450                Error::new(
451                    if err.is_timeout() {
452                        ErrorKind::Timeout
453                    } else {
454                        ErrorKind::Unavailable
455                    },
456                    ErrorOperation::CancelStatement,
457                    format!("failed to cancel statement: {statement_id:?}"),
458                )
459                .set_source(err)
460                .with_transient_failure(true)
461            })?;
462        decode_statement_response(response, ErrorOperation::CancelStatement).await
463    }
464
465    #[track_caller]
466    fn make_url(&self, path: &str) -> Result<Url, Error> {
467        self.endpoint.join(path).map_err(|err| {
468            Error::new(
469                ErrorKind::Internal,
470                ErrorOperation::Append,
471                "failed to construct URL".to_string(),
472            )
473            .set_source(err)
474        })
475    }
476
477    pub(crate) fn make_resource_url(&self, segments: &[&str]) -> Result<Url, Error> {
478        if segments.iter().any(|s| matches!(*s, "" | "." | "..")) {
479            return Err(Error::new(
480                ErrorKind::InvalidInput,
481                ErrorOperation::Append,
482                "resource names must not be empty or dot segments",
483            ));
484        }
485        let mut url = self.make_url("v1/")?;
486        let mut path = url.path_segments_mut().map_err(|_| {
487            Error::new(
488                ErrorKind::Internal,
489                ErrorOperation::Append,
490                "endpoint cannot be used as a base URL",
491            )
492        })?;
493        path.pop_if_empty();
494        path.extend(segments.iter().copied());
495        drop(path);
496        Ok(url)
497    }
498
499    pub(crate) fn write_timeout(&self) -> Duration {
500        self.write_timeout
501    }
502
503    pub(crate) fn request(&self, method: Method, url: Url) -> reqwest::RequestBuilder {
504        let request = self
505            .client
506            .request(method, url)
507            .header("X-ScopeDB-Client", "scopedb-client");
508        if let Some(authorization) = &self.authorization {
509            request.header(AUTHORIZATION, authorization.clone())
510        } else {
511            request
512        }
513    }
514
515    fn post_json<T: Serialize>(
516        &self,
517        url: Url,
518        value: &T,
519    ) -> Result<reqwest::RequestBuilder, Error> {
520        let uncompressed = serde_json::to_vec(value).map_err(|err| {
521            Error::new(
522                ErrorKind::Internal,
523                ErrorOperation::SubmitStatement,
524                "failed to serialize JSON request body",
525            )
526            .set_source(err)
527        })?;
528        let uncompressed_bytes = uncompressed.len();
529        let body = zstd::stream::encode_all(uncompressed.as_slice(), ZSTD_COMPRESSION_LEVEL)
530            .map_err(|err| {
531                Error::new(
532                    ErrorKind::Internal,
533                    ErrorOperation::SubmitStatement,
534                    "failed to compress JSON request body",
535                )
536                .set_source(err)
537            })?;
538
539        Ok(self
540            .request(Method::POST, url)
541            .header(CONTENT_TYPE, "application/json")
542            .header(CONTENT_ENCODING, JSON_CONTENT_ENCODING)
543            .header(UNCOMPRESSED_CONTENT_LENGTH, uncompressed_bytes.to_string())
544            .body(body))
545    }
546}
547
548fn decode_append_response(
549    status: StatusCode,
550    headers: &reqwest::header::HeaderMap,
551    payload: &[u8],
552) -> Result<AppendRowsResult, Error> {
553    if status == StatusCode::OK {
554        return match serde_json::from_slice::<AppendRowsResult>(payload) {
555            Ok(result)
556                if result.status == AppendOutcome::Succeeded && result.num_rows_inserted >= 0 =>
557            {
558                Ok(result)
559            }
560            Ok(_) => Err(apply_response_metadata(
561                append_ambiguous_error(
562                    ErrorKind::InvalidResponse,
563                    "table append response has an invalid body",
564                ),
565                status,
566                headers,
567            )),
568            Err(err) => Err(apply_response_metadata(
569                append_ambiguous_error(
570                    ErrorKind::InvalidResponse,
571                    "failed to decode table append response",
572                )
573                .set_source(err),
574                status,
575                headers,
576            )),
577        };
578    }
579
580    if status.is_success() {
581        return Err(apply_response_metadata(
582            append_ambiguous_error(
583                ErrorKind::InvalidResponse,
584                format!(
585                    "table append returned unexpected success status {}",
586                    status.as_u16()
587                ),
588            ),
589            status,
590            headers,
591        ));
592    }
593
594    Err(decode_append_error(status, headers, payload))
595}
596
597fn append_ambiguous_error(kind: ErrorKind, message: impl Into<String>) -> Error {
598    Error::new(kind, ErrorOperation::Append, message).set_append_details(AppendErrorDetails {
599        status: AppendOutcome::Ambiguous,
600        row_errors: Vec::new(),
601        row_errors_truncated: false,
602    })
603}
604
605fn append_definite_failure(message: impl Into<String>) -> Error {
606    Error::new(ErrorKind::InvalidInput, ErrorOperation::Append, message).set_append_details(
607        AppendErrorDetails {
608            status: AppendOutcome::Failed,
609            row_errors: Vec::new(),
610            row_errors_truncated: false,
611        },
612    )
613}