Skip to main content

scopedb_client/
protocol.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::str::FromStr;
17use std::time::Duration;
18use std::time::SystemTime;
19
20use reqwest::StatusCode;
21use reqwest::header::HeaderMap;
22use serde::Deserialize;
23use serde::Serialize;
24use uuid::Uuid;
25
26use crate::Error;
27use crate::ErrorKind;
28use crate::ErrorOperation;
29use crate::ResultSet;
30
31/// Outcome certainty of a table append request.
32#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
33#[serde(rename_all = "snake_case")]
34pub enum AppendOutcome {
35    /// The entire request succeeded; all rows committed.
36    #[serde(rename = "committed")]
37    Succeeded,
38    /// No rows from the attempt took effect, and none can take effect later.
39    #[serde(rename = "rejected")]
40    Failed,
41    /// The attempt may have taken effect or may still take effect later.
42    #[serde(rename = "unknown")]
43    Ambiguous,
44}
45
46impl fmt::Display for AppendOutcome {
47    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
48        match self {
49            Self::Succeeded => f.write_str("succeeded"),
50            Self::Failed => f.write_str("failed"),
51            Self::Ambiguous => f.write_str("ambiguous"),
52        }
53    }
54}
55
56/// Result of a committed table append request.
57#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
58pub struct AppendRowsResult {
59    /// Confirmed commit outcome: [`AppendOutcome::Succeeded`].
60    #[serde(default = "succeeded_append_outcome")]
61    pub status: AppendOutcome,
62    pub num_rows_inserted: i64,
63}
64
65fn succeeded_append_outcome() -> AppendOutcome {
66    AppendOutcome::Succeeded
67}
68
69/// Row-level validation diagnostic for a failed append request.
70#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
71pub struct AppendRowError {
72    pub row_index: u64,
73    pub column: String,
74    pub message: String,
75}
76
77/// SDK outcome certainty and available row diagnostics for a table append request.
78///
79/// On [`Error::append_details`], `status` is [`AppendOutcome::Ambiguous`] if any
80/// attempt had an ambiguous outcome. A definite failure establishes that no rows
81/// took effect or can take effect later. Row diagnostics, when available, describe
82/// the last failed response and do not determine the outcome.
83#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
84pub struct AppendErrorDetails {
85    pub status: AppendOutcome,
86    /// Optional row diagnostics; an empty list does not imply that every row is valid.
87    #[serde(default)]
88    pub row_errors: Vec<AppendRowError>,
89    #[serde(default)]
90    pub row_errors_truncated: bool,
91}
92
93/// Decodes outcome certainty separately from the diagnostic error category.
94pub fn decode_append_error(status: StatusCode, headers: &HeaderMap, payload: &[u8]) -> Error {
95    #[derive(Deserialize)]
96    struct ErrorBody {
97        code: String,
98        message: String,
99        details: Option<serde_json::Value>,
100        retryable: Option<bool>,
101    }
102
103    let decoded = serde_json::from_slice::<serde_json::Value>(payload).and_then(|envelope| {
104        let modern = envelope.get("error").is_some();
105        let body = envelope.get("error").unwrap_or(&envelope).clone();
106        let request_id = envelope
107            .get("request_id")
108            .and_then(serde_json::Value::as_str)
109            .map(str::to_owned);
110        serde_json::from_value::<ErrorBody>(body).map(|body| (body, modern, request_id))
111    });
112    let ambiguous = AppendErrorDetails {
113        status: AppendOutcome::Ambiguous,
114        row_errors: Vec::new(),
115        row_errors_truncated: false,
116    };
117    let (body, modern, request_id) = match decoded {
118        Ok(decoded) => decoded,
119        Err(source) => {
120            return apply_response_metadata(
121                Error::new(
122                    ErrorKind::InvalidResponse,
123                    ErrorOperation::Append,
124                    "failed to decode table append error response",
125                )
126                .set_source(source)
127                .set_append_details(ambiguous),
128                status,
129                headers,
130            );
131        }
132    };
133    let valid = (status.is_client_error() || status.is_server_error())
134        && (!modern || valid_http_error_code(&body.code, status));
135    let mut details = if modern {
136        ambiguous
137    } else {
138        body.details
139            .as_ref()
140            .and_then(|value| serde_json::from_value::<AppendErrorDetails>(value.clone()).ok())
141            .unwrap_or(ambiguous)
142    };
143    // Explicit rejection details never override a 5xx ambiguous outcome.
144    details.status =
145        if valid && status.is_client_error() && (modern || details.status == AppendOutcome::Failed)
146        {
147            AppendOutcome::Failed
148        } else {
149            AppendOutcome::Ambiguous
150        };
151    let kind = if valid {
152        ErrorKind::from_http(status)
153    } else {
154        ErrorKind::InvalidResponse
155    };
156    let mut error = apply_response_metadata(
157        Error::new(kind, ErrorOperation::Append, body.message)
158            .set_api_error(Some(body.code), body.details)
159            .set_server_retryable(body.retryable)
160            .with_transient_failure(
161                valid
162                    && body.retryable != Some(false)
163                    && (status == StatusCode::TOO_MANY_REQUESTS || status.is_server_error()),
164            )
165            .set_append_details(details),
166        status,
167        headers,
168    );
169    if !valid {
170        error = error.with_context("response", "inconsistent HTTP status and error code");
171    }
172    if let Some(request_id) = request_id {
173        error = error.set_request_id(request_id);
174    }
175    error
176}
177
178fn valid_http_error_code(code: &str, status: StatusCode) -> bool {
179    let expected = match code {
180        "bad_request" => 400,
181        "not_found" => 404,
182        "method_not_allowed" => 405,
183        "request_timeout" => 408,
184        "conflict" => 409,
185        "precondition_failed" => 412,
186        "too_many_requests" => 429,
187        "internal_server_error" => 500,
188        "service_unavailable" => 503,
189        "statement_timeout" | "invalid_request" | "unauthorized" | "payload_too_large"
190        | "timeout" | "unavailable" | "internal_error" => return false,
191        _ => return true,
192    };
193    status.as_u16() == expected
194}
195
196pub async fn decode_statement_response(
197    r: reqwest::Response,
198    operation: ErrorOperation,
199) -> Result<StatementStatus, Error> {
200    let code = r.status();
201    let headers = r.headers().clone();
202    let payload = r.bytes().await.map_err(|err| {
203        let error = Error::new(
204            if err.is_timeout() {
205                ErrorKind::Timeout
206            } else {
207                ErrorKind::Unavailable
208            },
209            operation,
210            "failed to read response body",
211        )
212        .set_source(err);
213        let error = error.with_transient_failure(operation != ErrorOperation::SubmitStatement);
214        apply_response_metadata(error, code, &headers)
215    })?;
216    if code.is_success() {
217        let result = serde_json::from_slice(&payload).map_err(|err| {
218            apply_response_metadata(
219                Error::new(
220                    ErrorKind::InvalidResponse,
221                    operation,
222                    "failed to decode response body",
223                )
224                .set_source(err),
225                code,
226                &headers,
227            )
228        })?;
229        return Ok(result);
230    }
231
232    Err(decode_http_error(code, &headers, &payload, operation))
233}
234
235pub fn decode_http_error(
236    status: StatusCode,
237    headers: &HeaderMap,
238    payload: &[u8],
239    operation: ErrorOperation,
240) -> Error {
241    let parsed = parse_error_payload(payload).unwrap_or_else(|| ParsedErrorPayload {
242        code: None,
243        details: None,
244        message: String::from_utf8_lossy(payload).into_owned(),
245        request_id: None,
246        retryable: None,
247    });
248    let mut error = apply_response_metadata(
249        Error::new(ErrorKind::from_http(status), operation, parsed.message)
250            .set_server_retryable(parsed.retryable)
251            .set_api_error(parsed.code, parsed.details),
252        status,
253        headers,
254    );
255    if let Some(request_id) = parsed.request_id {
256        error = error.set_request_id(request_id);
257    }
258    let retryable = parsed.retryable.unwrap_or_else(|| {
259        matches!(
260            status,
261            StatusCode::REQUEST_TIMEOUT | StatusCode::TOO_MANY_REQUESTS
262        ) || status.is_server_error()
263    });
264    error.with_transient_failure(retryable)
265}
266
267#[derive(Debug)]
268struct ParsedErrorPayload {
269    code: Option<String>,
270    details: Option<serde_json::Value>,
271    message: String,
272    request_id: Option<String>,
273    retryable: Option<bool>,
274}
275
276fn parse_error_payload(payload: &[u8]) -> Option<ParsedErrorPayload> {
277    let payload = serde_json::from_slice::<serde_json::Value>(payload).ok()?;
278    let object = payload.as_object()?;
279    if let Some(message) = object.get("message").and_then(serde_json::Value::as_str) {
280        return Some(ParsedErrorPayload {
281            code: object
282                .get("code")
283                .and_then(serde_json::Value::as_str)
284                .map(str::to_string),
285            details: object.get("details").cloned(),
286            message: message.to_string(),
287            request_id: object
288                .get("request_id")
289                .and_then(serde_json::Value::as_str)
290                .map(str::to_string),
291            retryable: object.get("retryable").and_then(serde_json::Value::as_bool),
292        });
293    }
294
295    let nested = object.get("error")?.as_object()?;
296    Some(ParsedErrorPayload {
297        code: nested
298            .get("code")
299            .and_then(serde_json::Value::as_str)
300            .map(str::to_string),
301        details: nested.get("details").cloned(),
302        message: nested.get("message")?.as_str()?.to_string(),
303        request_id: object
304            .get("request_id")
305            .and_then(serde_json::Value::as_str)
306            .map(str::to_string),
307        retryable: nested.get("retryable").and_then(serde_json::Value::as_bool),
308    })
309}
310
311pub fn apply_response_metadata(mut error: Error, status: StatusCode, headers: &HeaderMap) -> Error {
312    error = error.set_http_status(status);
313    if let Some(request_id) = header_string(headers, "x-request-id") {
314        error = error.set_request_id(request_id);
315    }
316    if let Some(retry_after) = parse_retry_after(headers, SystemTime::now()) {
317        error = error.set_retry_after(retry_after);
318    }
319    error
320}
321
322fn header_string(headers: &HeaderMap, name: &'static str) -> Option<String> {
323    headers
324        .get(name)
325        .and_then(|value| value.to_str().ok())
326        .map(str::to_string)
327}
328
329fn parse_retry_after(headers: &HeaderMap, now: SystemTime) -> Option<Duration> {
330    let value = headers.get(reqwest::header::RETRY_AFTER)?.to_str().ok()?;
331    if let Ok(seconds) = value.parse::<u64>() {
332        return Some(Duration::from_secs(seconds));
333    }
334    let at = httpdate::parse_http_date(value).ok()?;
335    Some(at.duration_since(now).unwrap_or(Duration::ZERO))
336}
337
338#[derive(Debug, Serialize)]
339pub struct StatementRequest {
340    pub statement: String,
341    pub statement_id: Uuid,
342    #[serde(default)]
343    #[serde(skip_serializing_if = "Option::is_none")]
344    pub max_elapsed_seconds: Option<f64>,
345    #[serde(default, skip_serializing_if = "Option::is_none")]
346    pub max_estimated_seconds: Option<f64>,
347    pub format: &'static str,
348}
349
350/// Execution status snapshot of a submitted statement.
351#[derive(Debug, Clone, Serialize, Deserialize)]
352#[serde(tag = "status")]
353pub enum StatementStatus {
354    #[serde(rename = "pending")]
355    Pending(StatementStatusPending),
356    #[serde(rename = "running")]
357    Running(StatementStatusRunning),
358    #[serde(rename = "finished")]
359    Finished(StatementStatusFinished),
360    #[serde(rename = "failed")]
361    Failed(StatementStatusFailed),
362    #[serde(rename = "cancelled")]
363    Cancelled(StatementStatusCancelled),
364}
365
366/// Status of a statement queued for execution.
367#[non_exhaustive]
368#[derive(Debug, Clone, Serialize, Deserialize)]
369pub struct StatementStatusPending {
370    pub statement_id: Uuid,
371    pub created_at: jiff::Timestamp,
372    pub progress: StatementEstimatedProgress,
373}
374
375/// Status of an actively executing statement.
376#[non_exhaustive]
377#[derive(Debug, Clone, Serialize, Deserialize)]
378pub struct StatementStatusRunning {
379    pub statement_id: Uuid,
380    pub created_at: jiff::Timestamp,
381    pub progress: StatementEstimatedProgress,
382}
383
384/// Status of a statement that completed successfully.
385#[non_exhaustive]
386#[derive(Debug, Clone, Serialize, Deserialize)]
387pub struct StatementStatusFinished {
388    pub statement_id: Uuid,
389    pub created_at: jiff::Timestamp,
390    pub progress: StatementEstimatedProgress,
391
392    result_set: StatementResultSet,
393}
394
395impl StatementStatusFinished {
396    /// Returns the decoded [`ResultSet`].
397    pub fn result_set(&self) -> ResultSet {
398        ResultSet::from_statement_result_set(self.result_set.clone())
399    }
400}
401
402/// Status of a statement that terminated with an execution error.
403#[non_exhaustive]
404#[derive(Debug, Clone, Serialize, Deserialize)]
405pub struct StatementStatusFailed {
406    pub statement_id: Uuid,
407    pub created_at: jiff::Timestamp,
408    pub progress: StatementEstimatedProgress,
409    pub error: StatementErrorDetails,
410}
411
412/// Structured server error for a failed statement.
413#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
414pub struct StatementErrorDetails {
415    pub code: String,
416    pub message: String,
417    #[serde(default, skip_serializing_if = "Option::is_none")]
418    pub details: Option<serde_json::Value>,
419}
420
421/// Status of a cancelled statement.
422#[non_exhaustive]
423#[derive(Debug, Clone, Serialize, Deserialize)]
424pub struct StatementStatusCancelled {
425    pub statement_id: Uuid,
426    pub created_at: jiff::Timestamp,
427    pub progress: StatementEstimatedProgress,
428}
429
430impl StatementStatus {
431    pub fn statement_id(&self) -> Uuid {
432        match self {
433            StatementStatus::Pending(s) => s.statement_id,
434            StatementStatus::Running(s) => s.statement_id,
435            StatementStatus::Finished(s) => s.statement_id,
436            StatementStatus::Failed(s) => s.statement_id,
437            StatementStatus::Cancelled(s) => s.statement_id,
438        }
439    }
440
441    pub fn created_at(&self) -> jiff::Timestamp {
442        match self {
443            StatementStatus::Pending(s) => s.created_at,
444            StatementStatus::Running(s) => s.created_at,
445            StatementStatus::Finished(s) => s.created_at,
446            StatementStatus::Failed(s) => s.created_at,
447            StatementStatus::Cancelled(s) => s.created_at,
448        }
449    }
450
451    pub fn progress(&self) -> &StatementEstimatedProgress {
452        match self {
453            StatementStatus::Pending(s) => &s.progress,
454            StatementStatus::Running(s) => &s.progress,
455            StatementStatus::Finished(s) => &s.progress,
456            StatementStatus::Failed(s) => &s.progress,
457            StatementStatus::Cancelled(s) => &s.progress,
458        }
459    }
460
461    pub fn is_finished(&self) -> bool {
462        matches!(self, StatementStatus::Finished(..))
463    }
464
465    pub fn is_terminated(&self) -> bool {
466        matches!(
467            self,
468            StatementStatus::Finished(..)
469                | StatementStatus::Failed(..)
470                | StatementStatus::Cancelled(..)
471        )
472    }
473}
474
475/// Estimated progress and timing metrics for a statement.
476#[derive(Default, Debug, Clone, Serialize, Deserialize)]
477pub struct StatementEstimatedProgress {
478    /// Total progress in percentage: `[0.0, 100.0]`.
479    #[serde(deserialize_with = "deserialize_progress_float")]
480    pub total_percentage: f64,
481    /// Elapsed nanoseconds since submission.
482    pub nanos_from_submitted: i64,
483    /// Elapsed nanoseconds since execution started.
484    pub nanos_from_started: i64,
485    #[serde(flatten)]
486    pub details: StatementProgress,
487}
488
489/// Stage, partition, row, byte, and compute counters for a statement.
490#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
491pub struct StatementProgress {
492    /// Compute consumed by the statement, in seconds.
493    #[serde(deserialize_with = "deserialize_progress_float")]
494    pub compute_seconds: f64,
495    pub total_stages: i64,
496    pub total_partitions: i64,
497    pub total_rows: i64,
498    pub total_compressed_bytes: i64,
499    pub total_uncompressed_bytes: i64,
500    pub scanned_stages: i64,
501    pub scanned_partitions: i64,
502    pub scanned_rows: i64,
503    pub scanned_compressed_bytes: i64,
504    pub scanned_uncompressed_bytes: i64,
505    pub skipped_partitions: i64,
506    pub skipped_rows: i64,
507    pub skipped_compressed_bytes: i64,
508    pub skipped_uncompressed_bytes: i64,
509}
510
511// Internally tagged enums and flattened fields buffer numbers through Serde.
512// Number understands serde_json's arbitrary-precision representation in that buffer.
513fn deserialize_progress_float<'de, D: serde::Deserializer<'de>>(d: D) -> Result<f64, D::Error> {
514    serde_json::Number::deserialize(d)?
515        .as_f64()
516        .ok_or_else(|| serde::de::Error::custom("progress number is outside the f64 range"))
517}
518
519impl StatementProgress {
520    pub fn total_percentage(&self) -> f64 {
521        let scan_progress = if self.total_rows == 0 {
522            0.0
523        } else {
524            (self.scanned_rows + self.skipped_rows) as f64 / self.total_rows as f64 * 100.0
525        };
526
527        let stage_progress = if self.total_stages == 0 {
528            0.0
529        } else {
530            self.scanned_stages as f64 / self.total_stages as f64 * 100.0
531        };
532
533        scan_progress.max(stage_progress)
534    }
535}
536
537#[derive(Debug, Clone, Serialize, Deserialize)]
538pub struct StatementResultSet {
539    pub metadata: ResultSetMetadata,
540    #[serde(flatten)]
541    pub data: ResultSetData,
542}
543
544#[derive(Debug, Clone, Serialize, Deserialize)]
545#[serde(tag = "format")]
546pub enum ResultSetData {
547    #[serde(rename = "json")]
548    Json { rows: Vec<Vec<Option<String>>> },
549}
550
551#[derive(Debug, Clone, Serialize, Deserialize)]
552pub struct ResultSetMetadata {
553    pub fields: Vec<FieldMetadata>,
554    pub num_rows: usize,
555}
556
557#[derive(Debug, Clone, Serialize, Deserialize)]
558pub struct FieldMetadata {
559    pub name: String,
560    pub data_type: DataType,
561}
562
563/// ScopeDB column and result data type.
564#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
565pub enum DataType {
566    #[serde(rename = "int")]
567    Int,
568    #[serde(rename = "uint")]
569    UInt,
570    #[serde(rename = "float")]
571    Float,
572    #[serde(rename = "binary")]
573    Binary,
574    #[serde(rename = "string")]
575    String,
576    #[serde(rename = "boolean")]
577    Boolean,
578    #[serde(rename = "timestamp")]
579    Timestamp,
580    #[serde(rename = "interval")]
581    Interval,
582    #[serde(rename = "array")]
583    Array,
584    #[serde(rename = "object")]
585    Object,
586    #[serde(rename = "any")]
587    Any,
588    #[serde(rename = "null")]
589    Null,
590}
591
592impl FromStr for DataType {
593    type Err = Error;
594
595    fn from_str(s: &str) -> Result<Self, Self::Err> {
596        match s {
597            "int" => Ok(Self::Int),
598            "uint" => Ok(Self::UInt),
599            "float" => Ok(Self::Float),
600            "binary" => Ok(Self::Binary),
601            "string" => Ok(Self::String),
602            "boolean" => Ok(Self::Boolean),
603            "timestamp" => Ok(Self::Timestamp),
604            "interval" => Ok(Self::Interval),
605            "array" => Ok(Self::Array),
606            "object" => Ok(Self::Object),
607            "any" => Ok(Self::Any),
608            "null" => Ok(Self::Null),
609            _ => Err(Error::new(
610                ErrorKind::InvalidInput,
611                ErrorOperation::ParseDataType,
612                format!("unrecognized data type: {s}"),
613            )),
614        }
615    }
616}