scopedb-client 0.5.0

The official Rust client for ScopeDB
Documentation
// 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::cmp;
use std::time::Duration;

use uuid::Uuid;

use crate::Client;
use crate::Error;
use crate::ErrorKind;
use crate::ErrorOperation;
use crate::ResultSet;
use crate::StatementStatus;
use crate::protocol::StatementRequest;

/// A ScopeQL statement builder.
///
/// Call [`execute`](Self::execute) to run the statement to completion, or [`submit`](Self::submit)
/// to obtain a [`StatementHandle`] for progress polling and cancellation.
#[derive(Debug)]
pub struct Statement {
    client: Client,
    statement: String,
    statement_id: Uuid,
    max_elapsed: Option<Duration>,
    max_estimated: Option<Duration>,
}

impl Statement {
    /// Returns the statement ID that will be sent on submission.
    ///
    /// A UUIDv7 is generated by default and can be overridden with
    /// [`with_statement_id`](Self::with_statement_id). Retain this ID before calling
    /// [`submit`](Self::submit) if the submission future may be dropped before returning.
    pub fn statement_id(&self) -> Uuid {
        self.statement_id
    }

    /// Sets a caller-chosen statement ID for submission.
    pub fn with_statement_id(mut self, statement_id: Uuid) -> Self {
        self.statement_id = statement_id;
        self
    }

    /// Sets the maximum total elapsed time on the server, including queueing.
    pub fn with_max_elapsed(mut self, duration: Duration) -> Self {
        self.max_elapsed = Some(duration);
        self
    }

    /// Rejects the statement if its estimated execution time exceeds `duration`.
    pub fn with_max_estimated(mut self, duration: Duration) -> Self {
        self.max_estimated = Some(duration);
        self
    }

    /// Submits the statement and returns a [`StatementHandle`] with the initial status snapshot.
    ///
    /// On failure, [`Error::statement_id`] retains the statement ID so you can
    /// inspect the execution with [`Client::statement_handle`] instead of
    /// resubmitting the SQL.
    pub async fn submit(self) -> Result<StatementHandle, Error> {
        if self.max_elapsed.is_some_and(|d| d.is_zero())
            || self.max_estimated.is_some_and(|d| d.is_zero())
        {
            return Err(Error::new(
                ErrorKind::InvalidInput,
                ErrorOperation::SubmitStatement,
                "statement duration limits must be positive",
            )
            .set_statement_id(self.statement_id));
        }
        let Statement {
            client,
            statement,
            statement_id,
            max_elapsed,
            max_estimated,
        } = self;

        let snapshot = client
            .submit_statement(StatementRequest {
                statement,
                statement_id,
                max_elapsed_seconds: max_elapsed.map(|v| v.as_secs_f64()),
                max_estimated_seconds: max_estimated.map(|v| v.as_secs_f64()),
                format: "json",
            })
            .await
            .map_err(|error| error.set_statement_id(statement_id))?;

        Ok(StatementHandle {
            client,
            statement_id: snapshot.statement_id(),
            snapshot: Some(snapshot),
        })
    }

    /// Submits the statement and waits for its [`ResultSet`].
    ///
    /// Dropping this future stops local polling without cancelling server
    /// execution; use [`submit`](Self::submit) and [`StatementHandle::cancel`] to cancel
    /// a running statement. On failure, [`Error::statement_id`] retains the
    /// statement ID for recovery via [`Client::statement_handle`].
    pub async fn execute(self) -> Result<ResultSet, Error> {
        let mut handle = self
            .submit()
            .await
            .map_err(|error| error.with_operation(ErrorOperation::ExecuteStatement))?;
        handle.wait().await.map_err(|error| {
            error
                .with_operation(ErrorOperation::ExecuteStatement)
                .after_submission()
        })
    }

    pub(crate) fn new(client: Client, statement: String) -> Self {
        Self {
            client,
            statement,
            statement_id: Uuid::now_v7(),
            max_elapsed: None,
            max_estimated: None,
        }
    }
}

/// Handle to a submitted statement execution.
///
/// | Operation                                       | Method                       |
/// | ----------------------------------------------- | ---------------------------- |
/// | Read the last observed status without a request | [`snapshot`](Self::snapshot) |
/// | Fetch the current status                        | [`refresh`](Self::refresh)   |
/// | Wait for results                                | [`wait`](Self::wait)         |
/// | Request cancellation                            | [`cancel`](Self::cancel)     |
///
/// Terminal statuses (`Finished`, `Failed`, `Cancelled`) are cached locally, so
/// subsequent calls to [`refresh`](Self::refresh), [`wait`](Self::wait), or
/// [`cancel`](Self::cancel) return without another network request. Dropping a `refresh` or `wait`
/// future stops local waiting without cancelling execution on the server.
#[derive(Debug)]
pub struct StatementHandle {
    client: Client,
    statement_id: Uuid,
    snapshot: Option<StatementStatus>,
}

impl StatementHandle {
    /// Returns the statement ID.
    pub fn statement_id(&self) -> Uuid {
        self.statement_id
    }

    /// Returns the most recently observed [`StatementStatus`], if any, without
    /// making a network request.
    pub fn snapshot(&self) -> Option<&StatementStatus> {
        self.snapshot.as_ref()
    }

    /// Fetches and caches the latest [`StatementStatus`], or returns the cached
    /// status if already terminal.
    pub async fn refresh(&mut self) -> Result<&StatementStatus, Error> {
        if self
            .snapshot
            .as_ref()
            .is_some_and(StatementStatus::is_terminated)
        {
            return Ok(self
                .snapshot
                .as_ref()
                .expect("terminal snapshot is present"));
        }

        self.snapshot = Some(
            self.client
                .fetch_statement(self.statement_id)
                .await
                .map_err(|error| error.set_statement_id(self.statement_id))?,
        );
        Ok(self.snapshot.as_ref().expect("status was just assigned"))
    }

    /// Polls until the statement reaches a terminal state and returns its [`ResultSet`].
    ///
    /// Returns [`ErrorKind::Cancelled`] if the statement was cancelled, or
    /// normalizes a server execution failure into [`Error`] with
    /// [`Error::statement_details`]. Retry transient polling errors by calling
    /// `wait` again on this handle.
    pub async fn wait(&mut self) -> Result<ResultSet, Error> {
        let mut delay = Duration::from_millis(5);
        let max_delay = Duration::from_secs(1);

        loop {
            self.refresh()
                .await
                .map_err(|error| error.with_operation(ErrorOperation::WaitStatement))?;

            if let Some(status) = self.snapshot.as_ref() {
                match status {
                    StatementStatus::Finished(finished) => return Ok(finished.result_set()),
                    StatementStatus::Failed(failed) => {
                        return Err(Error::new(
                            ErrorKind::from_statement_code(&failed.error.code),
                            ErrorOperation::WaitStatement,
                            failed.error.message.clone(),
                        )
                        .set_statement_id(self.statement_id)
                        .set_statement_details(failed.error.clone()));
                    }
                    StatementStatus::Cancelled(cancelled) => {
                        return Err(Error::new(
                            ErrorKind::Cancelled,
                            ErrorOperation::WaitStatement,
                            format!("statement {} was cancelled", cancelled.statement_id),
                        )
                        .set_statement_id(self.statement_id));
                    }
                    StatementStatus::Pending(..) | StatementStatus::Running(..) => {
                        tokio::time::sleep(delay).await;
                        if delay < max_delay {
                            delay = cmp::min(delay.saturating_mul(2), max_delay);
                        }
                    }
                }
            }
        }
    }

    /// Requests cancellation and caches the returned [`StatementStatus`].
    ///
    /// If the response status is still `Pending` or `Running`, call [`wait`](Self::wait)
    /// to await termination. If execution finished or failed before cancellation
    /// took effect, that terminal status is returned and cached.
    pub async fn cancel(&mut self) -> Result<StatementStatus, Error> {
        if let Some(status) = self.snapshot.as_ref().filter(|s| s.is_terminated()) {
            return Ok(status.clone());
        }
        let status = self
            .client
            .cancel_statement(self.statement_id)
            .await
            .map_err(|error| error.set_statement_id(self.statement_id))?;
        self.snapshot = Some(status.clone());
        Ok(status)
    }

    pub(crate) fn new(client: Client, statement_id: Uuid) -> Self {
        Self {
            client,
            statement_id,
            snapshot: None,
        }
    }
}