You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@arrow.apache.org by GitBox <gi...@apache.org> on 2020/11/11 20:26:23 UTC

[GitHub] [arrow] carols10cents commented on a change in pull request #8641: ARROW-8853: [Rust] [Integration Testing] Enable Flight tests

carols10cents commented on a change in pull request #8641:
URL: https://github.com/apache/arrow/pull/8641#discussion_r521618201



##########
File path: rust/integration-testing/src/bin/flight-test-integration-client.rs
##########
@@ -0,0 +1,377 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you 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 arrow_integration_testing::{
+    read_json_file, ArrowFile, AUTH_PASSWORD, AUTH_USERNAME,
+};
+
+use arrow::datatypes::SchemaRef;
+use arrow::record_batch::RecordBatch;
+
+use arrow_flight::flight_service_client::FlightServiceClient;
+use arrow_flight::{
+    flight_descriptor::DescriptorType, BasicAuth, FlightData, HandshakeRequest, Location,
+    Ticket,
+};
+use arrow_flight::{utils::flight_data_to_arrow_batch, FlightDescriptor};
+
+use clap::{App, Arg};
+use futures::{channel::mpsc, sink::SinkExt, StreamExt};
+use prost::Message;
+use tonic::{metadata::MetadataValue, Request, Status};
+
+use std::sync::Arc;
+
+type Error = Box<dyn std::error::Error + Send + Sync + 'static>;
+type Result<T = (), E = Error> = std::result::Result<T, E>;
+
+type Client = FlightServiceClient<tonic::transport::Channel>;
+
+#[tokio::main]
+async fn main() -> Result {
+    let matches = App::new("rust flight-test-integration-client")
+        .arg(Arg::with_name("host").long("host").takes_value(true))
+        .arg(Arg::with_name("port").long("port").takes_value(true))
+        .arg(Arg::with_name("path").long("path").takes_value(true))
+        .arg(
+            Arg::with_name("scenario")
+                .long("scenario")
+                .takes_value(true),
+        )
+        .get_matches();
+
+    let host = matches.value_of("host").expect("Host is required");
+    let port = matches.value_of("port").expect("Port is required");
+
+    match matches.value_of("scenario") {
+        Some("middleware") => middleware_scenario(host, port).await?,
+        Some("auth:basic_proto") => auth_basic_proto_scenario(host, port).await?,
+        Some(scenario_name) => unimplemented!("Scenario not found: {}", scenario_name),
+        None => {
+            let path = matches
+                .value_of("path")
+                .expect("Path is required if scenario is not specified");
+            integration_test_scenario(host, port, path).await?;
+        }
+    }
+
+    Ok(())
+}
+
+async fn middleware_scenario(host: &str, port: &str) -> Result {
+    let url = format!("http://{}:{}", host, port);
+    let conn = tonic::transport::Endpoint::new(url)?.connect().await?;
+    let mut client = FlightServiceClient::with_interceptor(conn, middleware_interceptor);
+
+    let mut descriptor = FlightDescriptor::default();
+    descriptor.set_type(DescriptorType::Cmd);
+    descriptor.cmd = b"".to_vec();
+
+    // This call is expected to fail.
+    let resp = client
+        .get_flight_info(Request::new(descriptor.clone()))
+        .await;
+    match resp {
+        Ok(_) => return Err(Box::new(Status::internal("Expected call to fail"))),
+        Err(e) => {
+            let headers = e.metadata();
+            let middleware_header = headers.get("x-middleware");
+            let value = middleware_header.map(|v| v.to_str().unwrap()).unwrap_or("");
+
+            if value != "expected value" {
+                let msg = format!(
+                    "Expected to receive header 'x-middleware: expected value', \
+                    but instead got: '{}'",
+                    value
+                );
+                return Err(Box::new(Status::internal(msg)));
+            }
+
+            eprintln!("Headers received successfully on failing call.");
+        }
+    }
+
+    // This call should succeed
+    descriptor.cmd = b"success".to_vec();
+    let resp = client.get_flight_info(Request::new(descriptor)).await?;
+
+    let headers = resp.metadata();
+    let middleware_header = headers.get("x-middleware");
+    let value = middleware_header.map(|v| v.to_str().unwrap()).unwrap_or("");
+
+    if value != "expected value" {
+        let msg = format!(
+            "Expected to receive header 'x-middleware: expected value', \
+            but instead got: '{}'",
+            value
+        );
+        return Err(Box::new(Status::internal(msg)));
+    }
+
+    eprintln!("Headers received successfully on passing call.");
+
+    Ok(())
+}
+
+fn middleware_interceptor(mut req: Request<()>) -> Result<Request<()>, Status> {
+    let metadata = req.metadata_mut();
+    metadata.insert("x-middleware", "expected value".parse().unwrap());
+    Ok(req)
+}
+
+async fn auth_basic_proto_scenario(host: &str, port: &str) -> Result {
+    let url = format!("http://{}:{}", host, port);
+    let mut client = FlightServiceClient::connect(url).await?;
+
+    let action = arrow_flight::Action::default();
+
+    let resp = client.do_action(Request::new(action.clone())).await;
+    // This client is unauthenticated and should fail.
+    match resp {
+        Err(e) => {
+            if e.code() != tonic::Code::Unauthenticated {
+                return Err(Box::new(Status::internal(format!(
+                    "Expected UNAUTHENTICATED but got {:?}",
+                    e
+                ))));
+            }
+        }
+        Ok(other) => {
+            return Err(Box::new(Status::internal(format!(
+                "Expected UNAUTHENTICATED but got {:?}",
+                other
+            ))));
+        }
+    }
+
+    let token = authenticate(&mut client, AUTH_USERNAME, AUTH_PASSWORD)
+        .await
+        .expect("must respond successfully from handshake");
+
+    let mut request = Request::new(action);
+    let metadata = request.metadata_mut();
+    metadata.insert_bin(
+        "auth-token-bin",
+        MetadataValue::from_bytes(token.as_bytes()),
+    );
+
+    let resp = client.do_action(request).await?;
+    let mut resp = resp.into_inner();
+
+    let r = resp
+        .next()
+        .await
+        .expect("No response received")
+        .expect("Invalid response received");
+
+    let body = String::from_utf8(r.body).unwrap();
+    assert_eq!(body, AUTH_USERNAME);
+
+    Ok(())
+}
+
+// TODO: should this be extended, abstracted, and moved out of test code and into production code?

Review comment:
       The C++ Flight client provides [this `Authenticate` function](https://github.com/apache/arrow/blob/cf243d4bfc496dedb21a9c155eaba10664266923/cpp/src/arrow/flight/client.cc#L977-L994) and the ability to specify a [`ClientAuthHandler`](https://github.com/apache/arrow/blob/dbeab70863c4d0cd3da800f18f7e474da624bb5f/cpp/src/arrow/flight/client_auth.h#L45-L59), but I'm not sure if that's the abstraction desired in Rust 🤷‍♀️ 




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org