-
Notifications
You must be signed in to change notification settings - Fork 105
Callback-based gRPC client with C interface #963
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
Merged
Merged
Changes from 7 commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
d252337
Callback-based gRPC client with C interface
cretz 461f3b5
Disable type complexity check
cretz 76381a7
More lint fixes
cretz 929a727
Minor PR updates
cretz 8e8007d
Do not keep lifetimes on gRPC request and minor fix to drop if spawn_…
cretz 94a627e
Merge branch 'master' into interceptable-client
cretz b06e3db
Merge branch 'master' into interceptable-client
cretz 82ae77e
Add callback user data and some doc updates
cretz 71c02a3
Merge branch 'master' into interceptable-client
cretz 6cdfab0
Merge remote-tracking branch 'remotes/origin/master' into interceptab…
cretz d72f72a
Merge branch 'interceptable-client' of https://github.com/temporalio/…
cretz 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 hidden or 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,123 @@ | ||
| //! This module implements support for callback-based gRPC service that has a callback invoked for | ||
| //! every gRPC call instead of directly using the network. | ||
|
|
||
| use anyhow::anyhow; | ||
| use bytes::{BufMut, BytesMut}; | ||
| use futures_util::future::BoxFuture; | ||
| use futures_util::stream; | ||
| use http::{HeaderMap, Request, Response}; | ||
| use http_body_util::{BodyExt, StreamBody, combinators::BoxBody}; | ||
| use hyper::body::{Bytes, Frame}; | ||
| use std::{ | ||
| sync::Arc, | ||
| task::{Context, Poll}, | ||
| }; | ||
| use tonic::{Status, metadata::GRPC_CONTENT_TYPE}; | ||
| use tower::Service; | ||
|
|
||
| /// gRPC request for use by a callback. | ||
| pub struct GrpcRequest { | ||
| /// Fully qualified gRPC service name. | ||
| pub service: String, | ||
| /// RPC name. | ||
| pub rpc: String, | ||
| /// Request headers. | ||
| pub headers: HeaderMap, | ||
| /// Protobuf bytes of the request. | ||
| pub proto: Bytes, | ||
| } | ||
|
|
||
| /// Successful gRPC response returned by a callback. | ||
| pub struct GrpcSuccessResponse { | ||
| /// Response headers. | ||
| pub headers: HeaderMap, | ||
|
|
||
| /// Response proto bytes. | ||
| pub proto: Vec<u8>, | ||
| } | ||
|
|
||
| /// gRPC service that invokes the given callback on each call. | ||
| #[derive(Clone)] | ||
| pub struct CallbackBasedGrpcService { | ||
| /// Callback to invoke on each RPC call. | ||
| #[allow(clippy::type_complexity)] // Signature is not that complex | ||
| pub callback: Arc< | ||
| dyn Fn(GrpcRequest) -> BoxFuture<'static, Result<GrpcSuccessResponse, Status>> | ||
| + Send | ||
| + Sync, | ||
| >, | ||
| } | ||
|
|
||
| impl Service<Request<tonic::body::Body>> for CallbackBasedGrpcService { | ||
| type Response = http::Response<tonic::body::Body>; | ||
| type Error = anyhow::Error; | ||
| type Future = BoxFuture<'static, Result<Self::Response, Self::Error>>; | ||
|
|
||
| fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { | ||
| Poll::Ready(Ok(())) | ||
| } | ||
|
|
||
| fn call(&mut self, req: Request<tonic::body::Body>) -> Self::Future { | ||
| let callback = self.callback.clone(); | ||
|
|
||
| Box::pin(async move { | ||
| // Build req | ||
| let (parts, body) = req.into_parts(); | ||
| let mut path_parts = parts.uri.path().trim_start_matches('/').split('/'); | ||
| let req_body = body.collect().await.map_err(|e| anyhow!(e))?.to_bytes(); | ||
| // Body is flag saying whether compressed (we do not support that), then 32-bit length, | ||
| // then the actual proto. | ||
| if req_body.len() < 5 { | ||
| return Err(anyhow!("Too few request bytes: {}", req_body.len())); | ||
| } else if req_body[0] != 0 { | ||
| return Err(anyhow!("Compression not supported")); | ||
| } | ||
| let req_proto_len = | ||
| u32::from_be_bytes([req_body[1], req_body[2], req_body[3], req_body[4]]) as usize; | ||
| if req_body.len() < 5 + req_proto_len { | ||
| return Err(anyhow!( | ||
| "Expected request body length at least {}, got {}", | ||
| 5 + req_proto_len, | ||
| req_body.len() | ||
| )); | ||
| } | ||
| let req = GrpcRequest { | ||
| service: path_parts.next().unwrap_or_default().to_owned(), | ||
| rpc: path_parts.next().unwrap_or_default().to_owned(), | ||
| headers: parts.headers, | ||
| proto: req_body.slice(5..5 + req_proto_len), | ||
| }; | ||
|
|
||
| // Invoke and handle response | ||
| match (callback)(req).await { | ||
| Ok(success) => { | ||
| // Create body bytes which requires a flag saying whether compressed, then | ||
| // message len, then actual message. So we create a Bytes for those 5 prepend | ||
| // parts, then stream it alongside the user-provided Vec. This allows us to | ||
| // avoid copying the vec | ||
| let mut body_prepend = BytesMut::with_capacity(5); | ||
| body_prepend.put_u8(0); // 0 means no compression | ||
| body_prepend.put_u32(success.proto.len() as u32); | ||
| let stream = stream::iter(vec![ | ||
| Ok::<_, Status>(Frame::data(Bytes::from(body_prepend))), | ||
| Ok::<_, Status>(Frame::data(Bytes::from(success.proto))), | ||
| ]); | ||
| let stream_body = StreamBody::new(stream); | ||
| let full_body = BoxBody::new(stream_body).boxed(); | ||
|
|
||
| // Build response appending headers | ||
| let mut resp_builder = Response::builder() | ||
| .status(200) | ||
| .header(http::header::CONTENT_TYPE, GRPC_CONTENT_TYPE); | ||
| for (key, value) in success.headers.iter() { | ||
| resp_builder = resp_builder.header(key, value); | ||
| } | ||
| Ok(resp_builder | ||
| .body(tonic::body::Body::new(full_body)) | ||
| .map_err(|e| anyhow!(e))?) | ||
| } | ||
| Err(status) => Ok(status.into_http()), | ||
| } | ||
| }) | ||
| } | ||
| } |
This file contains hidden or 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 hidden or 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 hidden or 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
Oops, something went wrong.
Oops, something went wrong.
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.
I do not believe changing this will cause any issues or serious performance concerns, but would like to have it double checked