-
Notifications
You must be signed in to change notification settings - Fork 42
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
fix: Properly exit SimpleExecuteQueryStream on stream end #2243
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,5 +1,6 @@ | ||
pub mod errors; | ||
pub mod handler; | ||
pub mod proxy; | ||
pub mod simple; | ||
|
||
mod session; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,162 @@ | ||
use crate::errors::{Result, RpcsrvError}; | ||
use async_trait::async_trait; | ||
use datafusion::physical_plan::SendableRecordBatchStream; | ||
use datafusion::variable::VarType; | ||
use datafusion_ext::vars::SessionVars; | ||
use futures::{Stream, StreamExt}; | ||
use protogen::{ | ||
gen::rpcsrv::simple, | ||
rpcsrv::types::simple::{ | ||
ExecuteQueryRequest, ExecuteQueryResponse, QueryResultError, QueryResultSuccess, | ||
}, | ||
}; | ||
use sqlexec::{engine::Engine, OperationInfo}; | ||
use std::{ | ||
pin::Pin, | ||
sync::Arc, | ||
task::{Context, Poll}, | ||
}; | ||
use tonic::{Request, Response, Status}; | ||
|
||
/// The "simple query" rpc handler. | ||
/// | ||
/// Note that this doesn't keep state about sessions, and sessions only last the | ||
/// lifetime of a query. | ||
pub struct SimpleHandler { | ||
/// Core db engine for creating sessions. | ||
engine: Arc<Engine>, | ||
} | ||
|
||
impl SimpleHandler { | ||
pub fn new(engine: Arc<Engine>) -> SimpleHandler { | ||
SimpleHandler { engine } | ||
} | ||
} | ||
|
||
#[async_trait] | ||
impl simple::simple_service_server::SimpleService for SimpleHandler { | ||
type ExecuteQueryStream = SimpleExecuteQueryStream; | ||
|
||
async fn execute_query( | ||
&self, | ||
request: Request<simple::ExecuteQueryRequest>, | ||
) -> Result<Response<Self::ExecuteQueryStream>, Status> { | ||
// Note that this creates a local session independent of any "remote" | ||
// sessions. This provides full session capabilities (e.g. parsing sql, | ||
// use the dist exec scheduler). | ||
// | ||
// This may be something we change (into what?) | ||
let request = ExecuteQueryRequest::try_from(request.into_inner())?; | ||
let vars = SessionVars::default().with_database_id(request.database_id, VarType::System); | ||
let mut session = self | ||
.engine | ||
.new_local_session_context(vars, request.config.into()) | ||
.await | ||
.map_err(RpcsrvError::from)?; | ||
|
||
let plan = session | ||
.sql_to_lp(&request.query_text) | ||
.await | ||
.map_err(RpcsrvError::from)?; | ||
let plan = plan.try_into_datafusion_plan().map_err(RpcsrvError::from)?; | ||
let physical = session | ||
.create_physical_plan(plan, &OperationInfo::default()) | ||
.await | ||
.map_err(RpcsrvError::from)?; | ||
let stream = session | ||
.execute_physical(physical) | ||
.await | ||
.map_err(RpcsrvError::from)?; | ||
|
||
Ok(Response::new(SimpleExecuteQueryStream::new(stream))) | ||
} | ||
} | ||
|
||
/// Stream implementation for sending the results of a simple query request. | ||
// TODO: Only supports a single response stream (we can do many). | ||
// TODO: Only provides "success" or "error" info to the client. Doesn't return | ||
// the actual results. | ||
pub struct SimpleExecuteQueryStream { | ||
inner: SendableRecordBatchStream, | ||
done: bool, | ||
} | ||
|
||
impl SimpleExecuteQueryStream { | ||
pub fn new(stream: SendableRecordBatchStream) -> SimpleExecuteQueryStream { | ||
SimpleExecuteQueryStream { | ||
inner: stream, | ||
done: false, | ||
} | ||
} | ||
} | ||
|
||
impl Stream for SimpleExecuteQueryStream { | ||
type Item = Result<simple::ExecuteQueryResponse, Status>; | ||
|
||
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { | ||
if self.done { | ||
return Poll::Ready(None); | ||
} | ||
|
||
loop { | ||
match self.inner.poll_next_unpin(cx) { | ||
// Drop the result, we're not sending it back to the client. | ||
// And continue to the next loop iteration. | ||
Poll::Ready(Some(Ok(_))) => (), | ||
|
||
// Stream completed without error, return success to the client. | ||
Poll::Ready(None) => { | ||
self.done = true; // Make sure we properly signal stream end on next poll. | ||
return Poll::Ready(Some(Ok(ExecuteQueryResponse::SuccessResult( | ||
QueryResultSuccess {}, | ||
) | ||
.into()))); | ||
} | ||
|
||
// We got an error, send it back to the client. | ||
Poll::Ready(Some(Err(e))) => { | ||
return Poll::Ready(Some(Ok(ExecuteQueryResponse::ErrorResult( | ||
QueryResultError { msg: e.to_string() }, | ||
) | ||
.into()))) | ||
} | ||
|
||
Poll::Pending => return Poll::Pending, | ||
} | ||
} | ||
} | ||
} | ||
|
||
#[cfg(test)] | ||
mod tests { | ||
use super::*; | ||
use datafusion::{ | ||
arrow::{datatypes::Schema, record_batch::RecordBatch}, | ||
physical_plan::stream::RecordBatchStreamAdapter, | ||
}; | ||
use futures::stream::{self, StreamExt}; | ||
|
||
#[tokio::test] | ||
async fn simple_stream_exits() { | ||
// https://github.com/GlareDB/glaredb/issues/2242 | ||
|
||
let inner = Box::pin(RecordBatchStreamAdapter::new( | ||
Arc::new(Schema::empty()), | ||
stream::iter([ | ||
Ok(RecordBatch::new_empty(Arc::new(Schema::empty()))), | ||
Ok(RecordBatch::new_empty(Arc::new(Schema::empty()))), | ||
]), | ||
)); | ||
|
||
let stream = SimpleExecuteQueryStream::new(inner); | ||
let output = stream | ||
.map(|result| result.unwrap()) | ||
.collect::<Vec<_>>() | ||
.await; | ||
|
||
let expected: &[simple::ExecuteQueryResponse] = | ||
&[ExecuteQueryResponse::SuccessResult(QueryResultSuccess {}).into()]; | ||
|
||
assert_eq!(output, expected) | ||
} | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is the fix. Adds a bool so that next poll of this stream (no the inner stream) we exit.