scopedb-client 0.5.0

The official Rust client for ScopeDB
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
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
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
// Copyright 2024 ScopeDB, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::fmt;
use std::time::Duration;

use fastrace_reqwest::traceparent_headers;
use reqwest::IntoUrl;
use reqwest::Method;
use reqwest::StatusCode;
use reqwest::Url;
use reqwest::header::AUTHORIZATION;
use reqwest::header::CONTENT_ENCODING;
use reqwest::header::CONTENT_TYPE;
use reqwest::header::HeaderValue;
use serde::Serialize;
use uuid::Uuid;

use crate::AppendErrorDetails;
use crate::AppendOutcome;
use crate::AppendRowsResult;
use crate::Catalog;
use crate::Error;
use crate::ErrorKind;
use crate::ErrorOperation;
use crate::ResultSet;
use crate::Statement;
use crate::StatementHandle;
use crate::StatementStatus;
use crate::Table;
use crate::protocol::StatementRequest;
use crate::protocol::apply_response_metadata;
use crate::protocol::decode_append_error;
use crate::protocol::decode_statement_response;

const JSON_CONTENT_ENCODING: &str = "zstd";
const UNCOMPRESSED_CONTENT_LENGTH: &str = "X-ScopeDB-Uncompressed-Content-Length";
const ZSTD_COMPRESSION_LEVEL: i32 = 3;
pub const MAX_APPEND_BODY_BYTES: usize = 8 * 1024 * 1024;
pub const MAX_APPEND_ROWS: usize = 200_000;
const DEFAULT_WRITE_TIMEOUT: Duration = Duration::from_secs(30);

/// An async client for queries, table writes, and catalog operations.
///
/// Start with [`builder`](Self::builder) to configure your endpoint and API key.
/// Clones share the underlying HTTP connection pool.
#[derive(Debug, Clone)]
pub struct Client {
    endpoint: Url,
    client: reqwest::Client,
    authorization: Option<HeaderValue>,
    write_timeout: Duration,
}

/// Builder for a [`Client`] with an optional API key, write timeout, and custom HTTP client.
pub struct ClientBuilder {
    endpoint: String,
    client: Option<reqwest::Client>,
    api_key: Option<String>,
    write_timeout: Duration,
}

impl fmt::Debug for ClientBuilder {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ClientBuilder")
            .field("endpoint", &self.endpoint)
            .field("client", &self.client)
            .field("has_api_key", &self.api_key.is_some())
            .field("write_timeout", &self.write_timeout)
            .finish()
    }
}

impl ClientBuilder {
    /// Sets the Bearer API key attached to each request.
    ///
    /// Overrides any default `Authorization` header on a custom HTTP client.
    pub fn api_key(mut self, api_key: impl Into<String>) -> Self {
        self.api_key = Some(api_key.into());
        self
    }

    /// Sets a custom HTTP client for TLS, proxy, and connection-pool settings.
    ///
    /// Construct the client with [`reqwest`](crate::reqwest) and disable redirects and
    /// transport retries so writes are not replayed at the HTTP layer:
    ///
    /// ```
    /// use scopedb_client::reqwest;
    ///
    /// let http_client = reqwest::Client::builder()
    ///     .redirect(reqwest::redirect::Policy::none())
    ///     .retry(reqwest::retry::never())
    ///     .build()?;
    /// # Ok::<(), reqwest::Error>(())
    /// ```
    pub fn http_client(mut self, client: reqwest::Client) -> Self {
        self.client = Some(client);
        self
    }

    /// Sets the per-attempt timeout for table appends and catalog mutations,
    /// including reading the response body.
    ///
    /// Defaults to 30 seconds and must be finite and positive.
    /// [`AppendWriterBuilder::attempt_timeout`](crate::AppendWriterBuilder::attempt_timeout) and
    /// [`AppendStreamBuilder::attempt_timeout`](crate::AppendStreamBuilder::attempt_timeout)
    /// override this default. Timeouts configured on a custom HTTP client also apply.
    ///
    /// A timed-out write has an ambiguous outcome and is not replayed
    /// automatically. Append timeouts populate [`Error::write_details`], and
    /// catalog mutation timeouts set [`Error::catalog_outcome`] to
    /// [`CatalogMutationOutcome::Unknown`](crate::CatalogMutationOutcome::Unknown).
    pub fn write_timeout(mut self, timeout: Duration) -> Self {
        self.write_timeout = timeout;
        self
    }

    /// Validates configuration and builds the [`Client`].
    pub fn build(self) -> Result<Client, Error> {
        if self.write_timeout.is_zero() {
            return Err(Error::new(
                ErrorKind::InvalidInput,
                ErrorOperation::BuildClient,
                "write_timeout must be greater than zero",
            ));
        }
        if tokio::time::Instant::now()
            .checked_add(self.write_timeout)
            .is_none()
        {
            return Err(Error::new(
                ErrorKind::InvalidInput,
                ErrorOperation::BuildClient,
                "write_timeout is too large",
            ));
        }
        let http_client = match self.client {
            Some(client) => client,
            None => reqwest::Client::builder()
                .redirect(reqwest::redirect::Policy::none())
                .retry(reqwest::retry::never())
                .build()
                .map_err(|err| {
                    Error::new(
                        ErrorKind::InvalidInput,
                        ErrorOperation::BuildClient,
                        "failed to build HTTP client",
                    )
                    .set_source(err)
                })?,
        };
        let mut client = Client::new(self.endpoint, http_client)?;
        client.write_timeout = self.write_timeout;
        if let Some(api_key) = self.api_key {
            if api_key.is_empty() {
                return Err(Error::new(
                    ErrorKind::InvalidInput,
                    ErrorOperation::BuildClient,
                    "api_key must not be empty",
                ));
            }
            let mut authorization =
                HeaderValue::from_str(&format!("Bearer {api_key}")).map_err(|err| {
                    Error::new(
                        ErrorKind::InvalidInput,
                        ErrorOperation::BuildClient,
                        "api_key is not a valid HTTP credential",
                    )
                    .set_source(err)
                })?;
            authorization.set_sensitive(true);
            client.authorization = Some(authorization);
        }
        Ok(client)
    }
}

impl Client {
    /// Returns a builder for `endpoint`.
    pub fn builder(endpoint: impl ToString) -> ClientBuilder {
        ClientBuilder {
            endpoint: endpoint.to_string(),
            client: None,
            api_key: None,
            write_timeout: DEFAULT_WRITE_TIMEOUT,
        }
    }

    /// Creates a client from an HTTP(S) endpoint URL and a
    /// [`reqwest::Client`](crate::reqwest::Client).
    ///
    /// Configure `client` as shown in [`ClientBuilder::http_client`]. The write
    /// timeout defaults to 30 seconds; use [`builder`](Self::builder) to customize it or
    /// attach an API key.
    pub fn new<E: IntoUrl>(endpoint: E, client: reqwest::Client) -> Result<Self, Error> {
        match endpoint.into_url() {
            Ok(mut endpoint) => {
                if !matches!(endpoint.scheme(), "http" | "https")
                    || endpoint.host_str().is_none()
                    || !endpoint.username().is_empty()
                    || endpoint.password().is_some()
                    || endpoint.query().is_some()
                    || endpoint.fragment().is_some()
                {
                    return Err(Error::new(
                        ErrorKind::InvalidInput,
                        ErrorOperation::BuildClient,
                        "endpoint must be an HTTP(S) URL without credentials, query, or fragment",
                    ));
                }
                if !endpoint.path().ends_with('/') {
                    let path = format!("{}/", endpoint.path());
                    endpoint.set_path(&path);
                }
                Ok(Self {
                    endpoint,
                    client,
                    authorization: None,
                    write_timeout: DEFAULT_WRITE_TIMEOUT,
                })
            }
            Err(err) => Err(Error::new(
                ErrorKind::InvalidInput,
                ErrorOperation::BuildClient,
                "failed to parse endpoint".to_string(),
            )
            .set_source(err)),
        }
    }

    /// Creates a [`Statement`] builder for `statement`.
    pub fn statement(&self, statement: impl Into<String>) -> Statement {
        Statement::new(self.clone(), statement.into())
    }

    /// Returns a [`StatementHandle`] for an existing `statement_id` without making a request.
    pub fn statement_handle(&self, statement_id: Uuid) -> StatementHandle {
        StatementHandle::new(self.clone(), statement_id)
    }

    /// Selects `table` in the default `scopedb.public` namespace.
    pub fn table(&self, table: impl Into<String>) -> Table {
        Table::new(self.clone(), table.into())
    }

    /// Submits `statement` and waits for its [`ResultSet`].
    ///
    /// If waiting fails after submission, pass [`Error::statement_id`] to
    /// [`statement_handle`](Self::statement_handle) to inspect or resume waiting on the running
    /// execution rather than resubmitting the query.
    pub async fn query(&self, statement: impl Into<String>) -> Result<ResultSet, Error> {
        self.statement(statement).execute().await
    }

    /// Accesses the declarative [`Catalog`].
    pub fn catalog(&self) -> Catalog {
        Catalog::new(self.clone())
    }

    /// Appends newline-delimited JSON rows to `database.schema.table` in a single request.
    ///
    /// See [`Table::append`] for payload limits and recovery semantics.
    pub async fn append_rows(
        &self,
        database: &str,
        schema: &str,
        table: &str,
        ndjson: impl Into<String>,
    ) -> Result<AppendRowsResult, Error> {
        self.append_rows_with_timeout(database, schema, table, ndjson.into(), None)
            .await
    }

    pub(crate) async fn append_rows_with_timeout(
        &self,
        database: &str,
        schema: &str,
        table: &str,
        ndjson: String,
        timeout: Option<Duration>,
    ) -> Result<AppendRowsResult, Error> {
        if ndjson.len() > MAX_APPEND_BODY_BYTES {
            return Err(append_definite_failure(format!(
                "append payload requires {} bytes, exceeds the {MAX_APPEND_BODY_BYTES}-byte append limit",
                ndjson.len()
            )));
        }
        let expected_rows = ndjson
            .lines()
            .filter(|line| !line.trim().is_empty())
            .count();
        if expected_rows > MAX_APPEND_ROWS {
            return Err(append_definite_failure(format!(
                "append payload exceeds the {MAX_APPEND_ROWS}-row limit",
            )));
        }
        let url = self.make_resource_url(&[
            "catalog",
            "databases",
            database,
            "schemas",
            schema,
            "tables",
            table,
            "ingest",
        ])?;
        let body =
            zstd::stream::encode_all(ndjson.as_bytes(), ZSTD_COMPRESSION_LEVEL).map_err(|err| {
                append_definite_failure("failed to compress table append request body")
                    .set_source(err)
            })?;
        let request = self
            .request(Method::POST, url)
            .headers(traceparent_headers())
            .header(reqwest::header::CONTENT_TYPE, "application/x-ndjson")
            .header(reqwest::header::CONTENT_ENCODING, JSON_CONTENT_ENCODING)
            .body(body);
        let mut status = None;
        let mut headers = reqwest::header::HeaderMap::new();
        tokio::time::timeout(timeout.unwrap_or(self.write_timeout), async {
            let response = request.send().await.map_err(|err| {
                let error = if err.is_timeout() {
                    append_ambiguous_error(ErrorKind::Timeout, "table append request timed out; write outcome is ambiguous")
                        .set_write_timeout()
                } else {
                    append_ambiguous_error(ErrorKind::Unavailable, "failed to send table append request")
                };
                error.set_source(err)
            })?;
            let response_status = response.status();
            status = Some(response_status);
            headers = response.headers().clone();
            let payload = response.bytes().await.map_err(|err| {
                let error = if err.is_timeout() {
                    append_ambiguous_error(ErrorKind::Timeout, "table append request timed out; write outcome is ambiguous")
                        .set_write_timeout()
                } else {
                    append_ambiguous_error(ErrorKind::Unavailable, "failed to read table append response")
                };
                error.set_source(err)
            })?;
            let result = decode_append_response(response_status, &headers, &payload)?;
            if result.num_rows_inserted != expected_rows as i64 {
                return Err(append_ambiguous_error(ErrorKind::InvalidResponse, format!(
                    "table append response reported {} inserted rows for a {expected_rows}-row request",
                    result.num_rows_inserted
                )));
            }
            Ok(result)
        })
        .await
        .unwrap_or_else(|err| {
            Err(
                append_ambiguous_error(ErrorKind::Timeout, "table append request timed out; write outcome is ambiguous")
                    .set_write_timeout()
                    .set_source(err),
            )
        })
        .map_err(|err| match status {
            Some(status) if err.http_status().is_none() => {
                apply_response_metadata(err, status, &headers)
            }
            _ => err,
        })
    }
}

impl Client {
    #[fastrace::trace]
    pub(crate) async fn submit_statement(
        &self,
        request: StatementRequest,
    ) -> Result<StatementStatus, Error> {
        let url = self.make_url("v1/statements")?;
        let response = self
            .post_json(url, &request)?
            .headers(traceparent_headers())
            .send()
            .await
            .map_err(|err| {
                Error::new(
                    if err.is_timeout() {
                        ErrorKind::Timeout
                    } else {
                        ErrorKind::Unavailable
                    },
                    ErrorOperation::SubmitStatement,
                    "failed to submit statement",
                )
                .set_source(err)
            })?;
        decode_statement_response(response, ErrorOperation::SubmitStatement).await
    }

    #[fastrace::trace]
    pub(crate) async fn fetch_statement(
        &self,
        statement_id: Uuid,
    ) -> Result<StatementStatus, Error> {
        let path = format!("v1/statements/{statement_id}");
        let url = self.make_url(&path)?;
        let response = self
            .request(Method::GET, url)
            .headers(traceparent_headers())
            .query(&[("format", "json")])
            .send()
            .await
            .map_err(|err| {
                Error::new(
                    if err.is_timeout() {
                        ErrorKind::Timeout
                    } else {
                        ErrorKind::Unavailable
                    },
                    ErrorOperation::RefreshStatement,
                    format!("failed to fetch statement: {statement_id:?}"),
                )
                .set_source(err)
                .with_transient_failure(true)
            })?;
        decode_statement_response(response, ErrorOperation::RefreshStatement).await
    }

    #[fastrace::trace]
    pub(crate) async fn cancel_statement(
        &self,
        statement_id: Uuid,
    ) -> Result<StatementStatus, Error> {
        let path = format!("v1/statements/{statement_id}/cancel");
        let url = self.make_url(&path)?;
        let response = self
            .request(Method::POST, url)
            .headers(traceparent_headers())
            .query(&[("format", "json")])
            .send()
            .await
            .map_err(|err| {
                Error::new(
                    if err.is_timeout() {
                        ErrorKind::Timeout
                    } else {
                        ErrorKind::Unavailable
                    },
                    ErrorOperation::CancelStatement,
                    format!("failed to cancel statement: {statement_id:?}"),
                )
                .set_source(err)
                .with_transient_failure(true)
            })?;
        decode_statement_response(response, ErrorOperation::CancelStatement).await
    }

    #[track_caller]
    fn make_url(&self, path: &str) -> Result<Url, Error> {
        self.endpoint.join(path).map_err(|err| {
            Error::new(
                ErrorKind::Internal,
                ErrorOperation::Append,
                "failed to construct URL".to_string(),
            )
            .set_source(err)
        })
    }

    pub(crate) fn make_resource_url(&self, segments: &[&str]) -> Result<Url, Error> {
        if segments.iter().any(|s| matches!(*s, "" | "." | "..")) {
            return Err(Error::new(
                ErrorKind::InvalidInput,
                ErrorOperation::Append,
                "resource names must not be empty or dot segments",
            ));
        }
        let mut url = self.make_url("v1/")?;
        let mut path = url.path_segments_mut().map_err(|_| {
            Error::new(
                ErrorKind::Internal,
                ErrorOperation::Append,
                "endpoint cannot be used as a base URL",
            )
        })?;
        path.pop_if_empty();
        path.extend(segments.iter().copied());
        drop(path);
        Ok(url)
    }

    pub(crate) fn write_timeout(&self) -> Duration {
        self.write_timeout
    }

    pub(crate) fn request(&self, method: Method, url: Url) -> reqwest::RequestBuilder {
        let request = self
            .client
            .request(method, url)
            .header("X-ScopeDB-Client", "scopedb-client");
        if let Some(authorization) = &self.authorization {
            request.header(AUTHORIZATION, authorization.clone())
        } else {
            request
        }
    }

    fn post_json<T: Serialize>(
        &self,
        url: Url,
        value: &T,
    ) -> Result<reqwest::RequestBuilder, Error> {
        let uncompressed = serde_json::to_vec(value).map_err(|err| {
            Error::new(
                ErrorKind::Internal,
                ErrorOperation::SubmitStatement,
                "failed to serialize JSON request body",
            )
            .set_source(err)
        })?;
        let uncompressed_bytes = uncompressed.len();
        let body = zstd::stream::encode_all(uncompressed.as_slice(), ZSTD_COMPRESSION_LEVEL)
            .map_err(|err| {
                Error::new(
                    ErrorKind::Internal,
                    ErrorOperation::SubmitStatement,
                    "failed to compress JSON request body",
                )
                .set_source(err)
            })?;

        Ok(self
            .request(Method::POST, url)
            .header(CONTENT_TYPE, "application/json")
            .header(CONTENT_ENCODING, JSON_CONTENT_ENCODING)
            .header(UNCOMPRESSED_CONTENT_LENGTH, uncompressed_bytes.to_string())
            .body(body))
    }
}

fn decode_append_response(
    status: StatusCode,
    headers: &reqwest::header::HeaderMap,
    payload: &[u8],
) -> Result<AppendRowsResult, Error> {
    if status == StatusCode::OK {
        return match serde_json::from_slice::<AppendRowsResult>(payload) {
            Ok(result)
                if result.status == AppendOutcome::Succeeded && result.num_rows_inserted >= 0 =>
            {
                Ok(result)
            }
            Ok(_) => Err(apply_response_metadata(
                append_ambiguous_error(
                    ErrorKind::InvalidResponse,
                    "table append response has an invalid body",
                ),
                status,
                headers,
            )),
            Err(err) => Err(apply_response_metadata(
                append_ambiguous_error(
                    ErrorKind::InvalidResponse,
                    "failed to decode table append response",
                )
                .set_source(err),
                status,
                headers,
            )),
        };
    }

    if status.is_success() {
        return Err(apply_response_metadata(
            append_ambiguous_error(
                ErrorKind::InvalidResponse,
                format!(
                    "table append returned unexpected success status {}",
                    status.as_u16()
                ),
            ),
            status,
            headers,
        ));
    }

    Err(decode_append_error(status, headers, payload))
}

fn append_ambiguous_error(kind: ErrorKind, message: impl Into<String>) -> Error {
    Error::new(kind, ErrorOperation::Append, message).set_append_details(AppendErrorDetails {
        status: AppendOutcome::Ambiguous,
        row_errors: Vec::new(),
        row_errors_truncated: false,
    })
}

fn append_definite_failure(message: impl Into<String>) -> Error {
    Error::new(ErrorKind::InvalidInput, ErrorOperation::Append, message).set_append_details(
        AppendErrorDetails {
            status: AppendOutcome::Failed,
            row_errors: Vec::new(),
            row_errors_truncated: false,
        },
    )
}