scopedb_client/statement.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::cmp;
16use std::time::Duration;
17
18use uuid::Uuid;
19
20use crate::Client;
21use crate::Error;
22use crate::ErrorKind;
23use crate::ErrorOperation;
24use crate::ResultSet;
25use crate::StatementStatus;
26use crate::protocol::StatementRequest;
27
28/// A ScopeQL statement builder.
29///
30/// Call [`execute`](Self::execute) to run the statement to completion, or [`submit`](Self::submit)
31/// to obtain a [`StatementHandle`] for progress polling and cancellation.
32#[derive(Debug)]
33pub struct Statement {
34 client: Client,
35 statement: String,
36 statement_id: Uuid,
37 max_elapsed: Option<Duration>,
38 max_estimated: Option<Duration>,
39}
40
41impl Statement {
42 /// Returns the statement ID that will be sent on submission.
43 ///
44 /// A UUIDv7 is generated by default and can be overridden with
45 /// [`with_statement_id`](Self::with_statement_id). Retain this ID before calling
46 /// [`submit`](Self::submit) if the submission future may be dropped before returning.
47 pub fn statement_id(&self) -> Uuid {
48 self.statement_id
49 }
50
51 /// Sets a caller-chosen statement ID for submission.
52 pub fn with_statement_id(mut self, statement_id: Uuid) -> Self {
53 self.statement_id = statement_id;
54 self
55 }
56
57 /// Sets the maximum total elapsed time on the server, including queueing.
58 pub fn with_max_elapsed(mut self, duration: Duration) -> Self {
59 self.max_elapsed = Some(duration);
60 self
61 }
62
63 /// Rejects the statement if its estimated execution time exceeds `duration`.
64 pub fn with_max_estimated(mut self, duration: Duration) -> Self {
65 self.max_estimated = Some(duration);
66 self
67 }
68
69 /// Submits the statement and returns a [`StatementHandle`] with the initial status snapshot.
70 ///
71 /// On failure, [`Error::statement_id`] retains the statement ID so you can
72 /// inspect the execution with [`Client::statement_handle`] instead of
73 /// resubmitting the SQL.
74 pub async fn submit(self) -> Result<StatementHandle, Error> {
75 if self.max_elapsed.is_some_and(|d| d.is_zero())
76 || self.max_estimated.is_some_and(|d| d.is_zero())
77 {
78 return Err(Error::new(
79 ErrorKind::InvalidInput,
80 ErrorOperation::SubmitStatement,
81 "statement duration limits must be positive",
82 )
83 .set_statement_id(self.statement_id));
84 }
85 let Statement {
86 client,
87 statement,
88 statement_id,
89 max_elapsed,
90 max_estimated,
91 } = self;
92
93 let snapshot = client
94 .submit_statement(StatementRequest {
95 statement,
96 statement_id,
97 max_elapsed_seconds: max_elapsed.map(|v| v.as_secs_f64()),
98 max_estimated_seconds: max_estimated.map(|v| v.as_secs_f64()),
99 format: "json",
100 })
101 .await
102 .map_err(|error| error.set_statement_id(statement_id))?;
103
104 Ok(StatementHandle {
105 client,
106 statement_id: snapshot.statement_id(),
107 snapshot: Some(snapshot),
108 })
109 }
110
111 /// Submits the statement and waits for its [`ResultSet`].
112 ///
113 /// Dropping this future stops local polling without cancelling server
114 /// execution; use [`submit`](Self::submit) and [`StatementHandle::cancel`] to cancel
115 /// a running statement. On failure, [`Error::statement_id`] retains the
116 /// statement ID for recovery via [`Client::statement_handle`].
117 pub async fn execute(self) -> Result<ResultSet, Error> {
118 let mut handle = self
119 .submit()
120 .await
121 .map_err(|error| error.with_operation(ErrorOperation::ExecuteStatement))?;
122 handle.wait().await.map_err(|error| {
123 error
124 .with_operation(ErrorOperation::ExecuteStatement)
125 .after_submission()
126 })
127 }
128
129 pub(crate) fn new(client: Client, statement: String) -> Self {
130 Self {
131 client,
132 statement,
133 statement_id: Uuid::now_v7(),
134 max_elapsed: None,
135 max_estimated: None,
136 }
137 }
138}
139
140/// Handle to a submitted statement execution.
141///
142/// | Operation | Method |
143/// | ----------------------------------------------- | ---------------------------- |
144/// | Read the last observed status without a request | [`snapshot`](Self::snapshot) |
145/// | Fetch the current status | [`refresh`](Self::refresh) |
146/// | Wait for results | [`wait`](Self::wait) |
147/// | Request cancellation | [`cancel`](Self::cancel) |
148///
149/// Terminal statuses (`Finished`, `Failed`, `Cancelled`) are cached locally, so
150/// subsequent calls to [`refresh`](Self::refresh), [`wait`](Self::wait), or
151/// [`cancel`](Self::cancel) return without another network request. Dropping a `refresh` or `wait`
152/// future stops local waiting without cancelling execution on the server.
153#[derive(Debug)]
154pub struct StatementHandle {
155 client: Client,
156 statement_id: Uuid,
157 snapshot: Option<StatementStatus>,
158}
159
160impl StatementHandle {
161 /// Returns the statement ID.
162 pub fn statement_id(&self) -> Uuid {
163 self.statement_id
164 }
165
166 /// Returns the most recently observed [`StatementStatus`], if any, without
167 /// making a network request.
168 pub fn snapshot(&self) -> Option<&StatementStatus> {
169 self.snapshot.as_ref()
170 }
171
172 /// Fetches and caches the latest [`StatementStatus`], or returns the cached
173 /// status if already terminal.
174 pub async fn refresh(&mut self) -> Result<&StatementStatus, Error> {
175 if self
176 .snapshot
177 .as_ref()
178 .is_some_and(StatementStatus::is_terminated)
179 {
180 return Ok(self
181 .snapshot
182 .as_ref()
183 .expect("terminal snapshot is present"));
184 }
185
186 self.snapshot = Some(
187 self.client
188 .fetch_statement(self.statement_id)
189 .await
190 .map_err(|error| error.set_statement_id(self.statement_id))?,
191 );
192 Ok(self.snapshot.as_ref().expect("status was just assigned"))
193 }
194
195 /// Polls until the statement reaches a terminal state and returns its [`ResultSet`].
196 ///
197 /// Returns [`ErrorKind::Cancelled`] if the statement was cancelled, or
198 /// normalizes a server execution failure into [`Error`] with
199 /// [`Error::statement_details`]. Retry transient polling errors by calling
200 /// `wait` again on this handle.
201 pub async fn wait(&mut self) -> Result<ResultSet, Error> {
202 let mut delay = Duration::from_millis(5);
203 let max_delay = Duration::from_secs(1);
204
205 loop {
206 self.refresh()
207 .await
208 .map_err(|error| error.with_operation(ErrorOperation::WaitStatement))?;
209
210 if let Some(status) = self.snapshot.as_ref() {
211 match status {
212 StatementStatus::Finished(finished) => return Ok(finished.result_set()),
213 StatementStatus::Failed(failed) => {
214 return Err(Error::new(
215 ErrorKind::from_statement_code(&failed.error.code),
216 ErrorOperation::WaitStatement,
217 failed.error.message.clone(),
218 )
219 .set_statement_id(self.statement_id)
220 .set_statement_details(failed.error.clone()));
221 }
222 StatementStatus::Cancelled(cancelled) => {
223 return Err(Error::new(
224 ErrorKind::Cancelled,
225 ErrorOperation::WaitStatement,
226 format!("statement {} was cancelled", cancelled.statement_id),
227 )
228 .set_statement_id(self.statement_id));
229 }
230 StatementStatus::Pending(..) | StatementStatus::Running(..) => {
231 tokio::time::sleep(delay).await;
232 if delay < max_delay {
233 delay = cmp::min(delay.saturating_mul(2), max_delay);
234 }
235 }
236 }
237 }
238 }
239 }
240
241 /// Requests cancellation and caches the returned [`StatementStatus`].
242 ///
243 /// If the response status is still `Pending` or `Running`, call [`wait`](Self::wait)
244 /// to await termination. If execution finished or failed before cancellation
245 /// took effect, that terminal status is returned and cached.
246 pub async fn cancel(&mut self) -> Result<StatementStatus, Error> {
247 if let Some(status) = self.snapshot.as_ref().filter(|s| s.is_terminated()) {
248 return Ok(status.clone());
249 }
250 let status = self
251 .client
252 .cancel_statement(self.statement_id)
253 .await
254 .map_err(|error| error.set_statement_id(self.statement_id))?;
255 self.snapshot = Some(status.clone());
256 Ok(status)
257 }
258
259 pub(crate) fn new(client: Client, statement_id: Uuid) -> Self {
260 Self {
261 client,
262 statement_id,
263 snapshot: None,
264 }
265 }
266}