This is an automated email from the ASF dual-hosted git repository.

raulcd pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/arrow.git


The following commit(s) were added to refs/heads/main by this push:
     new 373d64c02cb GH-50282: [C++][FlightRPC] Refactor gRPC server and 
transport classes (#50407)
373d64c02cb is described below

commit 373d64c02cb23663b63c5853099fca43a46c39fc
Author: Alexis Placet <[email protected]>
AuthorDate: Wed Oct 21 12:21:59 2026 +0200

    GH-50282: [C++][FlightRPC] Refactor gRPC server and transport classes 
(#50407)
    
    # Rationale for this change
    
    The goal of the pullrequest is to refactor the FligtRPC code to prepare the 
async implementation.
    
    # What changes are included in this PR
    
    - extracts `server.cc/transport_server.cc` internals into 
`transport_server_internal.{h,cc}` and the gRPC-specific call context, 
auth/middleware helper, and endpoint/builder setup into 
`transport/grpc/grpc_server_internal.{h,cc}`, templated on the gRPC context 
type so `ServerContext` and `CallbackServerContext` can share one 
implementation.
     - Moves signal-driven shutdown into `internal::ServerSignalState`, fixing 
teardown ordering so handlers are restored even when `Serve()` fails early, a 
SIGPIPE race when waking the signal thread, and shutdown of an uninitialized 
server clearing another serving instance's signal target. (Github Copilot issue 
report)
     - Adds public `Location::uri()` and `Location::port()`, and includes` 
arrow/util/uri.h` from types.h so the `Result<util::Uri>` return type is 
instantiable by consumers of the installed header. (Github Copilot issue report 
in the PR)
     - `Wait()` on an uninitialized server now returns `Status::Invalid` 
instead of dereferencing null. No other public behavior change. 
`ServerTransport`, `TransportMessageReader`/`Writer`, `WriteDataStream` and 
friends stay internal. (Github Copilot issue report in the PR)
     - Drops the unused gRPC FlightData message registry.
    
    # Are these changes tested?
    - Full CI tests
    - Adds tests covering signal handling and server middleware headers that 
depend on handler state.
    
    # Are there any user-facing changes?
    - New API: `Location::uri()` → `Result<util::Uri>`, `Location::port()` → 
`int` (-1 when absent)
    - Compilation fix: `types.h` now includes `arrow/util/uri.h`. Before, 
`Result<util::Uri>` was uninstantiable for anyone including only the installed 
header.
    - Behavior: `Wait()` on an uninitialized server returns `Status::Invalid` 
(was a null deref). `Serve()` restores prior signal handlers on failure. 
`Shutdown()` on an uninitialized server no longer disables signal shutdown for 
another serving instance, signal thread wake no longer risks SIGPIPE-killing 
the process. (Github Copilot issue report in the PR)
    
    # Was AI used for this PR?
    In accordance to the [AI generation 
guidelines](https://arrow.apache.org/docs/dev/developers/overview.html#ai-generated-code),
 please disclose below whether and how AI was used in this PR.
    
    PR code and description written by:
    - [x] Human
    - [x] AI
    Reviewed before submission by:
    - [x] Human
    - [x] AI
    - [] Not reviewed
    
    * GitHub Issue: #50282
    
    Lead-authored-by: Alexis Placet <[email protected]>
    Co-authored-by: Alexis Placet <[email protected]>
    Co-authored-by: Alexis Placet <[email protected]>
    Signed-off-by: Raúl Cumplido <[email protected]>
---
 cpp/src/arrow/flight/CMakeLists.txt                |   2 +
 cpp/src/arrow/flight/flight_internals_test.cc      |  61 ++++
 cpp/src/arrow/flight/flight_test.cc                | 102 +++++++
 cpp/src/arrow/flight/meson.build                   |   2 +
 cpp/src/arrow/flight/server.cc                     | 164 +++-------
 cpp/src/arrow/flight/server.h                      |   5 +-
 cpp/src/arrow/flight/server_tracing_middleware.cc  |   2 +-
 cpp/src/arrow/flight/transport/grpc/grpc_server.cc | 238 ++-------------
 .../flight/transport/grpc/grpc_server_internal.cc  |  75 +++++
 .../flight/transport/grpc/grpc_server_internal.h   | 206 +++++++++++++
 cpp/src/arrow/flight/transport_server.cc           | 290 +-----------------
 cpp/src/arrow/flight/transport_server_internal.cc  | 332 +++++++++++++++++++++
 cpp/src/arrow/flight/transport_server_internal.h   | 305 +++++++++++++++++++
 cpp/src/arrow/flight/types.cc                      |  12 +
 cpp/src/arrow/flight/types.h                       |  15 +-
 15 files changed, 1178 insertions(+), 633 deletions(-)

diff --git a/cpp/src/arrow/flight/CMakeLists.txt 
b/cpp/src/arrow/flight/CMakeLists.txt
index 91afab15702..09eda0e2444 100644
--- a/cpp/src/arrow/flight/CMakeLists.txt
+++ b/cpp/src/arrow/flight/CMakeLists.txt
@@ -186,9 +186,11 @@ set(ARROW_FLIGHT_SRCS
     server_tracing_middleware.cc
     transport.cc
     transport_server.cc
+    transport_server_internal.cc
     # Bundle the gRPC impl with libarrow_flight
     transport/grpc/grpc_client.cc
     transport/grpc/grpc_server.cc
+    transport/grpc/grpc_server_internal.cc
     transport/grpc/serialization_internal.cc
     transport/grpc/protocol_grpc_internal.cc
     transport/grpc/util_internal.cc
diff --git a/cpp/src/arrow/flight/flight_internals_test.cc 
b/cpp/src/arrow/flight/flight_internals_test.cc
index a66ac210b86..5ec9b75dcfd 100644
--- a/cpp/src/arrow/flight/flight_internals_test.cc
+++ b/cpp/src/arrow/flight/flight_internals_test.cc
@@ -18,6 +18,10 @@
 // ----------------------------------------------------------------------
 // Tests for Flight which don't actually spin up a client/server
 
+#include <atomic>
+#include <chrono>
+#include <csignal>
+#include <thread>
 #include <type_traits>
 
 #include <gmock/gmock.h>
@@ -37,6 +41,7 @@
 #include "arrow/record_batch.h"
 #include "arrow/status.h"
 #include "arrow/testing/gtest_util.h"
+#include "arrow/util/io_util.h"
 #include "arrow/util/string.h"
 
 // Include after Flight headers
@@ -861,5 +866,61 @@ TEST(TransportErrorHandling, ReconstructStatus) {
 
 // TODO: test TransportStatusDetail
 
+#if !defined(_WIN32) && defined(ARROW_ENABLE_THREADING)
+
+// Serve() must not leave the process signal handlers overridden when it fails
+TEST(TestServerSignalState, ServeBeforeInitRestoresSignalHandlers) {
+  FlightServerBase server;
+  ASSERT_OK(server.SetShutdownOnSignals({SIGUSR1}));
+  ASSERT_OK_AND_ASSIGN(auto before, 
::arrow::internal::GetSignalHandler(SIGUSR1));
+
+  ASSERT_RAISES(UnknownError, server.Serve());
+
+  ASSERT_OK_AND_ASSIGN(auto after, 
::arrow::internal::GetSignalHandler(SIGUSR1));
+  EXPECT_EQ(before.callback(), after.callback());
+}
+
+// Shutdown() on a server that was never initialized must not clear the
+// process-wide signal target of another, serving instance
+TEST(TestServerSignalState, ShutdownUninitializedKeepsOtherServerSignalable) {
+  FlightServerBase serving_server;
+  ASSERT_OK_AND_ASSIGN(auto location, Location::ForGrpcTcp("localhost", 0));
+  FlightServerOptions options(location);
+  ASSERT_OK(serving_server.Init(options));
+  ASSERT_OK(serving_server.SetShutdownOnSignals({SIGUSR1}));
+
+  std::atomic<bool> returned{false};
+  std::thread serving_thread([&] {
+    auto status = serving_server.Serve();
+    ARROW_UNUSED(status);
+    returned = true;
+  });
+
+  // Wait for Serve() to install the process signal handler.
+  ASSERT_OK_AND_ASSIGN(auto original, 
::arrow::internal::GetSignalHandler(SIGUSR1));
+  for (int i = 0; i < 1000 && !returned.load(); ++i) {
+    ASSERT_OK_AND_ASSIGN(auto current, 
::arrow::internal::GetSignalHandler(SIGUSR1));
+    if (current.callback() != original.callback()) {
+      break;
+    }
+    std::this_thread::sleep_for(std::chrono::milliseconds(1));
+  }
+
+  FlightServerBase uninitialized;
+  ASSERT_RAISES(Invalid, uninitialized.Shutdown());
+
+  ::raise(SIGUSR1);
+  for (int i = 0; i < 500 && !returned.load(); ++i) {
+    std::this_thread::sleep_for(std::chrono::milliseconds(10));
+  }
+  EXPECT_TRUE(returned.load());
+  if (!returned.load()) {
+    ASSERT_OK(serving_server.Shutdown());
+  }
+  serving_thread.join();
+}
+
+#endif
+
 }  // namespace flight
 }  // namespace arrow
diff --git a/cpp/src/arrow/flight/flight_test.cc 
b/cpp/src/arrow/flight/flight_test.cc
index ab74e1fd6b8..1437d3162eb 100644
--- a/cpp/src/arrow/flight/flight_test.cc
+++ b/cpp/src/arrow/flight/flight_test.cc
@@ -587,6 +587,75 @@ class CountingServerMiddlewareFactory : public 
ServerMiddlewareFactory {
   std::atomic<int> failed_;
 };
 
+// A server middleware that only sends a header once the RPC handler has
+// flagged it, to check that headers are gathered after the handler runs.
+class HandlerStateServerMiddleware : public ServerMiddleware {
+ public:
+  void SendingHeaders(AddCallHeaders* outgoing_headers) override {
+    if (handler_ran) {
+      outgoing_headers->AddHeader("x-handler-ran", "true");
+    }
+  }
+  void CallCompleted(const Status& status) override {}
+
+  std::string name() const override { return "HandlerStateServerMiddleware"; }
+
+  bool handler_ran = false;
+};
+
+class HandlerStateServerMiddlewareFactory : public ServerMiddlewareFactory {
+ public:
+  Status StartCall(const CallInfo& info, const ServerCallContext& context,
+                   std::shared_ptr<ServerMiddleware>* middleware) override {
+    *middleware = std::make_shared<HandlerStateServerMiddleware>();
+    return Status::OK();
+  }
+};
+
+class HandlerStateTestServer : public FlightServerBase {
+  Status GetFlightInfo(const ServerCallContext& context, const 
FlightDescriptor& request,
+                       std::unique_ptr<FlightInfo>* info) override {
+    auto middleware = static_cast<HandlerStateServerMiddleware*>(
+        context.GetMiddleware("handler_state"));
+    if (middleware == nullptr) {
+      return Status::Invalid("Could not find middleware");
+    }
+    middleware->handler_ran = true;
+    ARROW_ASSIGN_OR_RAISE(auto flight_info,
+                          FlightInfo::Make(*arrow::schema({}), request, {}, 
-1, -1));
+    *info = std::make_unique<FlightInfo>(std::move(flight_info));
+    return Status::OK();
+  }
+};
+
+// A client middleware that records the values of the x-handler-ran header.
+class HandlerStateClientMiddleware : public ClientMiddleware {
+ public:
+  explicit HandlerStateClientMiddleware(std::vector<std::string>* values)
+      : values_(values) {}
+  void SendingHeaders(AddCallHeaders* outgoing_headers) override {}
+  void ReceivedHeaders(const CallHeaders& incoming_headers) override {
+    auto [begin, end] = incoming_headers.equal_range("x-handler-ran");
+    for (auto it = begin; it != end; ++it) {
+      values_->emplace_back(it->second);
+    }
+  }
+  void CallCompleted(const Status& status) override {}
+
+ private:
+  std::vector<std::string>* values_;
+};
+
+class HandlerStateClientMiddlewareFactory : public ClientMiddlewareFactory {
+ public:
+  void StartCall(const CallInfo& info,
+                 std::unique_ptr<ClientMiddleware>* middleware) override {
+    *middleware = std::make_unique<HandlerStateClientMiddleware>(&values_);
+  }
+
+  std::vector<std::string> values_;
+};
+
 // The current span ID, used to emulate OpenTracing style distributed
 // tracing. Only used for communication between application code and
 // client middleware.
@@ -872,6 +941,34 @@ class TestCountingServerMiddleware : public 
::testing::Test {
   std::unique_ptr<FlightServerBase> server_;
 };
 
+class TestHandlerStateServerMiddleware : public ::testing::Test {
+ public:
+  void SetUp() {
+    client_middleware_ = 
std::make_shared<HandlerStateClientMiddlewareFactory>();
+    ASSERT_OK(MakeServer<HandlerStateTestServer>(
+        &server_, &client_,
+        [](FlightServerOptions* options) {
+          options->middleware.push_back(
+              {"handler_state", 
std::make_shared<HandlerStateServerMiddlewareFactory>()});
+          return Status::OK();
+        },
+        [&](FlightClientOptions* options) {
+          options->middleware.push_back(client_middleware_);
+          return Status::OK();
+        }));
+  }
+
+  void TearDown() {
+    ASSERT_OK(client_->Close());
+    ASSERT_OK(server_->Shutdown());
+  }
+
+ protected:
+  std::shared_ptr<HandlerStateClientMiddlewareFactory> client_middleware_;
+  std::unique_ptr<FlightClient> client_;
+  std::unique_ptr<FlightServerBase> server_;
+};
+
 // Setup for this test is 2 servers
 // 1. Client makes request to server A with a request ID set
 // 2. server A extracts the request ID and makes a request to server B
@@ -1475,6 +1572,11 @@ TEST_F(TestCountingServerMiddleware, Count) {
   ASSERT_EQ(1, request_counter_->failed_);
 }
 
+TEST_F(TestHandlerStateServerMiddleware, GetFlightInfo) {
+  ASSERT_OK(client_->GetFlightInfo(FlightDescriptor::Command("")));
+  ASSERT_THAT(client_middleware_->values_, ::testing::ElementsAre("true"));
+}
+
 TEST_F(TestPropagatingMiddleware, Propagate) {
   Action action;
   std::unique_ptr<Result> result;
diff --git a/cpp/src/arrow/flight/meson.build b/cpp/src/arrow/flight/meson.build
index e66bc904d5f..dcdacc42ffd 100644
--- a/cpp/src/arrow/flight/meson.build
+++ b/cpp/src/arrow/flight/meson.build
@@ -88,8 +88,10 @@ arrow_flight_srcs = [
     'server_tracing_middleware.cc',
     'transport.cc',
     'transport_server.cc',
+    'transport_server_internal.cc',
     'transport/grpc/grpc_client.cc',
     'transport/grpc/grpc_server.cc',
+    'transport/grpc/grpc_server_internal.cc',
     'transport/grpc/serialization_internal.cc',
     'transport/grpc/protocol_grpc_internal.cc',
     'transport/grpc/util_internal.cc',
diff --git a/cpp/src/arrow/flight/server.cc b/cpp/src/arrow/flight/server.cc
index 7807829b3b3..da66d704c56 100644
--- a/cpp/src/arrow/flight/server.cc
+++ b/cpp/src/arrow/flight/server.cc
@@ -23,119 +23,30 @@
 
 #include "arrow/flight/server.h"
 
-#include <atomic>
-#include <cerrno>
 #include <chrono>
-#include <cstdint>
 #include <deque>
 #include <memory>
-#include <string_view>
-#include <thread>
 #include <utility>
 
 #include "arrow/device.h"
 #include "arrow/flight/transport.h"
 #include "arrow/flight/transport/grpc/grpc_server.h"
 #include "arrow/flight/transport_server.h"
+#include "arrow/flight/transport_server_internal.h"
 #include "arrow/flight/types.h"
 #include "arrow/status.h"
 #include "arrow/type.h"
-#include "arrow/util/io_util.h"
-#include "arrow/util/logging.h"
-#include "arrow/util/uri.h"
 
 namespace arrow {
 namespace flight {
 
-namespace {
-#if (ATOMIC_INT_LOCK_FREE != 2 || ATOMIC_POINTER_LOCK_FREE != 2)
-#  error "atomic ints and atomic pointers not always lock-free!"
-#endif
-
-using ::arrow::internal::SelfPipe;
-using ::arrow::internal::SetSignalHandler;
-using ::arrow::internal::SignalHandler;
-
-/// RAII guard that manages a self-pipe and a thread that listens on
-/// the self-pipe, shutting down the server when a signal handler
-/// writes to the pipe.
-class ServerSignalHandler {
- public:
-  ARROW_DISALLOW_COPY_AND_ASSIGN(ServerSignalHandler);
-  ServerSignalHandler() = default;
-
-  /// Create the pipe and handler thread.
-  ///
-  /// \return the fd of the write side of the pipe.
-  template <typename Fn>
-  arrow::Result<std::shared_ptr<SelfPipe>> Init(Fn handler) {
-    ARROW_ASSIGN_OR_RAISE(self_pipe_, SelfPipe::Make(/*signal_safe=*/true));
-    handle_signals_ = std::thread(handler, self_pipe_);
-    return self_pipe_;
-  }
-
-  Status Shutdown() {
-    RETURN_NOT_OK(self_pipe_->Shutdown());
-    handle_signals_.join();
-    return Status::OK();
-  }
-
-  ~ServerSignalHandler() { ARROW_CHECK_OK(Shutdown()); }
-
- private:
-  std::shared_ptr<SelfPipe> self_pipe_;
-  std::thread handle_signals_;
-};
-}  // namespace
-
 /// Server implementation. Manages the lifecycle of the "real" server
 /// (ServerTransport) and contains
 struct FlightServerBase::Impl {
   std::unique_ptr<internal::ServerTransport> transport_;
-
-  // Signal handlers (on Windows) and the shutdown handler (other platforms)
-  // are executed in a separate thread, so getting the current thread instance
-  // wouldn't make sense.  This means only a single instance can receive 
signals.
-  static std::atomic<Impl*> running_instance_;
-  // We'll use the self-pipe trick to notify a thread from the signal
-  // handler. The thread will then shut down the server.
-  std::shared_ptr<SelfPipe> self_pipe_;
-
-  // Signal handling
-  std::vector<int> signals_;
-  std::vector<SignalHandler> old_signal_handlers_;
-  std::atomic<int> got_signal_;
-
-  static void HandleSignal(int signum) {
-    auto instance = running_instance_.load();
-    if (instance != nullptr) {
-      instance->DoHandleSignal(signum);
-    }
-  }
-
-  void DoHandleSignal(int signum) {
-    got_signal_ = signum;
-
-    // Send dummy payload over self-pipe
-    self_pipe_->Send(/*payload=*/0);
-  }
-
-  static void WaitForSignals(std::shared_ptr<SelfPipe> self_pipe) {
-    // Wait for a signal handler to wake up the pipe
-    auto st = self_pipe->Wait().status();
-    // Status::Invalid means the pipe was shutdown without any wakeup
-    if (!st.ok() && !st.IsInvalid()) {
-      ARROW_LOG(FATAL) << "Failed to wait on self-pipe: " << st.ToString();
-    }
-    auto instance = running_instance_.load();
-    if (instance != nullptr) {
-      ARROW_WARN_NOT_OK(instance->transport_->Shutdown(), "Error shutting down 
server");
-    }
-  }
+  internal::ServerSignalState signal_state_;
 };
 
-std::atomic<FlightServerBase::Impl*> FlightServerBase::Impl::running_instance_;
-
 FlightServerOptions::FlightServerOptions(const Location& location_)
     : location(location_),
       auth_handler(nullptr),
@@ -159,66 +70,59 @@ Status FlightServerBase::Init(const FlightServerOptions& 
options) {
   ARROW_ASSIGN_OR_RAISE(impl_->transport_,
                         internal::GetDefaultTransportRegistry()->MakeServer(
                             scheme, this, options.memory_manager));
-  return impl_->transport_->Init(options, *options.location.uri_);
+  ARROW_ASSIGN_OR_RAISE(auto uri, options.location.uri());
+  return impl_->transport_->Init(options, uri);
 }
 
-int FlightServerBase::port() const { return location().uri_->port(); }
+int FlightServerBase::port() const { return location().port(); }
 
 Location FlightServerBase::location() const { return 
impl_->transport_->location(); }
 
 Status FlightServerBase::SetShutdownOnSignals(const std::vector<int> sigs) {
-  impl_->signals_ = sigs;
-  impl_->old_signal_handlers_.clear();
-  return Status::OK();
+  return impl_->signal_state_.SetShutdownOnSignals(sigs);
 }
 
 Status FlightServerBase::Serve() {
+  // Check before entering the signal helper: a failing wait() callback would
+  // otherwise leave the process signal handlers overridden, and clearing the
+  // signal target on the error path would disable signals for another server.
   if (!impl_->transport_) {
     return Status::UnknownError("Server did not start properly");
   }
-  impl_->got_signal_ = 0;
-  impl_->old_signal_handlers_.clear();
-  impl_->running_instance_ = impl_.get();
-
-  ServerSignalHandler signal_handler;
-  ARROW_ASSIGN_OR_RAISE(impl_->self_pipe_, 
signal_handler.Init(&Impl::WaitForSignals));
-  // Override existing signal handlers with our own handler so as to stop the 
server.
-  for (size_t i = 0; i < impl_->signals_.size(); ++i) {
-    int signum = impl_->signals_[i];
-    SignalHandler new_handler(&Impl::HandleSignal), old_handler;
-    ARROW_ASSIGN_OR_RAISE(old_handler, SetSignalHandler(signum, new_handler));
-    impl_->old_signal_handlers_.push_back(std::move(old_handler));
-  }
-
-  RETURN_NOT_OK(impl_->transport_->Wait());
-  impl_->running_instance_ = nullptr;
-
-  // Restore signal handlers
-  for (size_t i = 0; i < impl_->signals_.size(); ++i) {
-    RETURN_NOT_OK(
-        SetSignalHandler(impl_->signals_[i], 
impl_->old_signal_handlers_[i]).status());
-  }
-  return Status::OK();
+  return impl_->signal_state_.Serve(
+      [this]() -> Status { return impl_->transport_->Wait(); },
+      [this](const std::chrono::system_clock::time_point* deadline) -> Status {
+        if (deadline) {
+          return impl_->transport_->Shutdown(*deadline);
+        }
+        return impl_->transport_->Shutdown();
+      },
+      "Error shutting down server");
 }
 
-int FlightServerBase::GotSignal() const { return impl_->got_signal_; }
+int FlightServerBase::GotSignal() const { return 
impl_->signal_state_.GotSignal(); }
 
 Status FlightServerBase::Shutdown(const std::chrono::system_clock::time_point* 
deadline) {
-  auto server = impl_->transport_.get();
-  if (!server) {
+  if (!impl_->transport_) {
     return Status::Invalid("Shutdown() on uninitialized FlightServerBase");
   }
-  impl_->running_instance_ = nullptr;
-  if (deadline) {
-    return impl_->transport_->Shutdown(*deadline);
-  }
-  return impl_->transport_->Shutdown();
+  return impl_->signal_state_.Shutdown(
+      [this](const std::chrono::system_clock::time_point* maybe_deadline) -> 
Status {
+        if (maybe_deadline) {
+          return impl_->transport_->Shutdown(*maybe_deadline);
+        }
+        return impl_->transport_->Shutdown();
+      },
+      deadline);
 }
 
 Status FlightServerBase::Wait() {
-  RETURN_NOT_OK(impl_->transport_->Wait());
-  impl_->running_instance_ = nullptr;
-  return Status::OK();
+  return impl_->signal_state_.Wait([this] {
+    if (!impl_->transport_) {
+      return Status::Invalid("Wait() on uninitialized FlightServerBase");
+    }
+    return impl_->transport_->Wait();
+  });
 }
 
 Status FlightServerBase::ListFlights(const ServerCallContext& context,
diff --git a/cpp/src/arrow/flight/server.h b/cpp/src/arrow/flight/server.h
index 8d73353ab16..c1534e490a0 100644
--- a/cpp/src/arrow/flight/server.h
+++ b/cpp/src/arrow/flight/server.h
@@ -195,9 +195,8 @@ class ARROW_FLIGHT_EXPORT FlightServerBase {
   Status Init(const FlightServerOptions& options);
 
   /// \brief Get the port that the Flight server is listening on.
-  /// This method must only be called after Init().  Will return a
-  /// non-positive value if no port exists (e.g. when listening on a
-  /// domain socket).
+  /// This method must only be called after Init().
+  /// \return The port number. -1 if the port is not available.
   int port() const;
 
   /// \brief Get the address that the Flight server is listening on.
diff --git a/cpp/src/arrow/flight/server_tracing_middleware.cc 
b/cpp/src/arrow/flight/server_tracing_middleware.cc
index a22e1a98ce4..5ce337e3cb4 100644
--- a/cpp/src/arrow/flight/server_tracing_middleware.cc
+++ b/cpp/src/arrow/flight/server_tracing_middleware.cc
@@ -95,7 +95,7 @@ class TracingServerMiddleware::Impl {
       : scope_(std::move(scope)), span_(std::move(span)) {}
   void CallCompleted(const Status& status) {
     if (!status.ok()) {
-      auto grpc_status = transport::grpc::ToGrpcStatus(status, 
/*ctx=*/nullptr);
+      auto grpc_status = transport::grpc::ToGrpcStatus(status);
       span_->SetStatus(otel::trace::StatusCode::kError, status.ToString());
       span_->SetAttribute(SemanticConventions::kRpcGrpcStatusCode,
                           static_cast<int32_t>(grpc_status.error_code()));
diff --git a/cpp/src/arrow/flight/transport/grpc/grpc_server.cc 
b/cpp/src/arrow/flight/transport/grpc/grpc_server.cc
index 03f22f8864d..2a100caeff7 100644
--- a/cpp/src/arrow/flight/transport/grpc/grpc_server.cc
+++ b/cpp/src/arrow/flight/transport/grpc/grpc_server.cc
@@ -34,6 +34,7 @@
 #include "arrow/flight/server.h"
 #include "arrow/flight/server_middleware.h"
 #include "arrow/flight/transport.h"
+#include "arrow/flight/transport/grpc/grpc_server_internal.h"
 #include "arrow/flight/transport/grpc/serialization_internal.h"
 #include "arrow/flight/transport/grpc/util_internal.h"
 #include "arrow/flight/transport_server.h"
@@ -112,78 +113,8 @@ class GrpcServerAuthSender : public ServerAuthSender {
   ::grpc::ServerReaderWriter<pb::HandshakeResponse, pb::HandshakeRequest>* 
stream_;
 };
 
-class GrpcServerCallContext : public ServerCallContext {
- public:
-  explicit GrpcServerCallContext(::grpc::ServerContext* context)
-      : context_(context), peer_(context_->peer()) {
-    for (const auto& entry : context->client_metadata()) {
-      incoming_headers_.insert(
-          {std::string_view(entry.first.data(), entry.first.length()),
-           std::string_view(entry.second.data(), entry.second.length())});
-    }
-  }
-
-  const std::string& peer_identity() const override { return peer_identity_; }
-  const std::string& peer() const override { return peer_; }
-  bool is_cancelled() const override { return context_->IsCancelled(); }
-  const CallHeaders& incoming_headers() const override { return 
incoming_headers_; }
-
-  // Helper method that runs interceptors given the result of an RPC,
-  // then returns the final gRPC status to send to the client
-  ::grpc::Status FinishRequest(const ::grpc::Status& status) {
-    // Don't double-convert status - return the original one here
-    FinishRequest(FromGrpcStatus(status));
-    return status;
-  }
-
-  ::grpc::Status FinishRequest(const arrow::Status& status) {
-    for (const auto& instance : middleware_) {
-      instance->CallCompleted(status);
-    }
-
-    // Set custom headers to map the exact Arrow status for clients
-    // who want it.
-    return ToGrpcStatus(status, context_);
-  }
-
-  void AddHeader(const std::string& key, const std::string& value) const 
override {
-    context_->AddInitialMetadata(key, value);
-  }
-
-  void AddTrailer(const std::string& key, const std::string& value) const 
override {
-    context_->AddTrailingMetadata(key, value);
-  }
-
-  ServerMiddleware* GetMiddleware(const std::string& key) const override {
-    const auto& instance = middleware_map_.find(key);
-    if (instance == middleware_map_.end()) {
-      return nullptr;
-    }
-    return instance->second.get();
-  }
-
- private:
-  friend class GrpcServiceHandler;
-  ServerContext* context_;
-  std::string peer_;
-  std::string peer_identity_;
-  std::vector<std::shared_ptr<ServerMiddleware>> middleware_;
-  std::unordered_map<std::string, std::shared_ptr<ServerMiddleware>> 
middleware_map_;
-  CallHeaders incoming_headers_;
-};
-
-class GrpcAddServerHeaders : public AddCallHeaders {
- public:
-  explicit GrpcAddServerHeaders(::grpc::ServerContext* context) : 
context_(context) {}
-  ~GrpcAddServerHeaders() override = default;
-
-  void AddHeader(const std::string& key, const std::string& value) override {
-    context_->AddInitialMetadata(key, value);
-  }
-
- private:
-  ::grpc::ServerContext* context_;
-};
+using GrpcServerCallContext = 
transport::grpc::GrpcServerCallContext<ServerContext>;
+using GrpcContextHelper = 
transport::grpc::GrpcServerCallContextHelper<ServerContext>;
 
 // A ServerDataStream for streaming data to the client.
 class GetDataStream : public internal::ServerDataStream {
@@ -248,7 +179,7 @@ class GrpcServiceHandler final : public 
FlightService::Service {
       std::vector<std::pair<std::string, 
std::shared_ptr<ServerMiddlewareFactory>>>
           middleware,
       internal::ServerTransport* impl)
-      : auth_handler_(auth_handler), middleware_(middleware), impl_(impl) {}
+      : helper_(std::move(auth_handler), std::move(middleware)), impl_(impl) {}
 
   template <typename UserType, typename Iterator, typename ProtoType>
   ::grpc::Status WriteStream(Iterator* iterator, ServerWriter<ProtoType>* 
writer) {
@@ -290,83 +221,13 @@ class GrpcServiceHandler final : public 
FlightService::Service {
     return ::grpc::Status::OK;
   }
 
-  // Authenticate the client (if applicable) and construct the call context
-  ::grpc::Status CheckAuth(const FlightMethod& method, ServerContext* context,
-                           GrpcServerCallContext& flight_context,
-                           bool skip_headers = false) {
-    if (!auth_handler_) {
-      const auto auth_context = context->auth_context();
-      if (auth_context && auth_context->IsPeerAuthenticated()) {
-        auto peer_identity = auth_context->GetPeerIdentity();
-        flight_context.peer_identity_ =
-            peer_identity.empty()
-                ? ""
-                : std::string(peer_identity.front().begin(), 
peer_identity.front().end());
-      } else {
-        flight_context.peer_identity_ = "";
-      }
-    } else {
-      const auto client_metadata = context->client_metadata();
-      const auto [auth_header, auth_header_end] =
-          client_metadata.equal_range(kGrpcAuthHeader);
-      std::string token;
-      if (auth_header == auth_header_end) {
-        token = "";
-      } else {
-        token = std::string(auth_header->second.data(), 
auth_header->second.length());
-      }
-      GRPC_RETURN_NOT_OK(
-          auth_handler_->IsValid(flight_context, token, 
&flight_context.peer_identity_));
-    }
-
-    return MakeCallContext(method, context, flight_context);
-  }
-
-  // Authenticate the client (if applicable) and construct the call context
-  ::grpc::Status MakeCallContext(const FlightMethod& method, ServerContext* 
context,
-                                 GrpcServerCallContext& flight_context,
-                                 bool skip_headers = false) {
-    // Run server middleware
-    const CallInfo info{method};
-
-    for (const auto& factory : middleware_) {
-      std::shared_ptr<ServerMiddleware> instance;
-      Status result = factory.second->StartCall(info, flight_context, 
&instance);
-      if (!result.ok()) {
-        // Interceptor rejected call, end the request on all existing
-        // interceptors
-        return flight_context.FinishRequest(result);
-      }
-      if (instance != nullptr) {
-        flight_context.middleware_.push_back(instance);
-        flight_context.middleware_map_.insert({factory.first, instance});
-      }
-    }
-
-    // TODO factor this out after fixing all streaming and non-streaming 
handlers
-    if (!skip_headers) {
-      addMiddlewareHeaders(context, flight_context);
-    }
-
-    return ::grpc::Status::OK;
-  }
-
-  void addMiddlewareHeaders(ServerContext* context,
-                            GrpcServerCallContext& flight_context) {
-    GrpcAddServerHeaders outgoing_headers(context);
-    for (const std::shared_ptr<ServerMiddleware>& instance : 
flight_context.middleware_) {
-      instance->SendingHeaders(&outgoing_headers);
-    }
-  }
-
   ::grpc::Status Handshake(
       ServerContext* context,
       ::grpc::ServerReaderWriter<pb::HandshakeResponse, pb::HandshakeRequest>* 
stream) {
     GrpcServerCallContext flight_context(context);
     GRPC_RETURN_NOT_GRPC_OK(
-        MakeCallContext(FlightMethod::Handshake, context, flight_context));
-
-    if (!auth_handler_) {
+        helper_.MakeCallContext(FlightMethod::Handshake, context, 
&flight_context));
+    if (!helper_.auth_handler()) {
       RETURN_WITH_MIDDLEWARE(
           flight_context,
           ::grpc::Status(
@@ -375,7 +236,7 @@ class GrpcServiceHandler final : public 
FlightService::Service {
     }
     GrpcServerAuthSender outgoing{stream};
     GrpcServerAuthReader incoming{stream};
-    RETURN_WITH_MIDDLEWARE(flight_context, auth_handler_->Authenticate(
+    RETURN_WITH_MIDDLEWARE(flight_context, 
helper_.auth_handler()->Authenticate(
                                                flight_context, &outgoing, 
&incoming));
   }
 
@@ -383,8 +244,7 @@ class GrpcServiceHandler final : public 
FlightService::Service {
                              ServerWriter<pb::FlightInfo>* writer) {
     GrpcServerCallContext flight_context(context);
     GRPC_RETURN_NOT_GRPC_OK(
-        CheckAuth(FlightMethod::ListFlights, context, flight_context));
-
+        helper_.CheckAuth(FlightMethod::ListFlights, context, 
&flight_context));
     // Retrieve the listing from the implementation
     std::unique_ptr<FlightListing> listing;
 
@@ -407,7 +267,7 @@ class GrpcServiceHandler final : public 
FlightService::Service {
                                pb::FlightInfo* response) {
     GrpcServerCallContext flight_context(context);
     GRPC_RETURN_NOT_GRPC_OK(
-        CheckAuth(FlightMethod::GetFlightInfo, context, flight_context));
+        helper_.CheckAuth(FlightMethod::GetFlightInfo, context, 
&flight_context));
 
     CHECK_ARG_NOT_NULL(flight_context, request, "FlightDescriptor cannot be 
null");
 
@@ -416,7 +276,7 @@ class GrpcServiceHandler final : public 
FlightService::Service {
 
     std::unique_ptr<FlightInfo> info;
     auto res = impl_->base()->GetFlightInfo(flight_context, descr, &info);
-    addMiddlewareHeaders(context, flight_context);
+    helper_.AddMiddlewareHeaders(context, &flight_context);
     SERVICE_RETURN_NOT_OK(flight_context, res);
 
     if (!info) {
@@ -434,7 +294,7 @@ class GrpcServiceHandler final : public 
FlightService::Service {
                                 pb::PollInfo* response) {
     GrpcServerCallContext flight_context(context);
     GRPC_RETURN_NOT_GRPC_OK(
-        CheckAuth(FlightMethod::PollFlightInfo, context, flight_context));
+        helper_.CheckAuth(FlightMethod::PollFlightInfo, context, 
&flight_context));
 
     CHECK_ARG_NOT_NULL(flight_context, request, "FlightDescriptor cannot be 
null");
 
@@ -458,7 +318,8 @@ class GrpcServiceHandler final : public 
FlightService::Service {
   ::grpc::Status GetSchema(ServerContext* context, const pb::FlightDescriptor* 
request,
                            pb::SchemaResult* response) {
     GrpcServerCallContext flight_context(context);
-    GRPC_RETURN_NOT_GRPC_OK(CheckAuth(FlightMethod::GetSchema, context, 
flight_context));
+    GRPC_RETURN_NOT_GRPC_OK(
+        helper_.CheckAuth(FlightMethod::GetSchema, context, &flight_context));
 
     CHECK_ARG_NOT_NULL(flight_context, request, "FlightDescriptor cannot be 
null");
 
@@ -482,8 +343,8 @@ class GrpcServiceHandler final : public 
FlightService::Service {
   ::grpc::Status DoGet(ServerContext* context, const pb::Ticket* request,
                        ServerWriter<pb::FlightData>* writer) {
     GrpcServerCallContext flight_context(context);
-    GRPC_RETURN_NOT_GRPC_OK(CheckAuth(FlightMethod::DoGet, context, 
flight_context));
-
+    GRPC_RETURN_NOT_GRPC_OK(
+        helper_.CheckAuth(FlightMethod::DoGet, context, &flight_context));
     CHECK_ARG_NOT_NULL(flight_context, request, "ticket cannot be null");
 
     Ticket ticket;
@@ -498,8 +359,8 @@ class GrpcServiceHandler final : public 
FlightService::Service {
       ServerContext* context,
       ::grpc::ServerReaderWriter<pb::PutResult, pb::FlightData>* reader) {
     GrpcServerCallContext flight_context(context);
-    GRPC_RETURN_NOT_GRPC_OK(CheckAuth(FlightMethod::DoPut, context, 
flight_context));
-
+    GRPC_RETURN_NOT_GRPC_OK(
+        helper_.CheckAuth(FlightMethod::DoPut, context, &flight_context));
     PutDataStream stream(reader);
     RETURN_WITH_MIDDLEWARE(flight_context, impl_->DoPut(flight_context, 
&stream));
   }
@@ -508,8 +369,8 @@ class GrpcServiceHandler final : public 
FlightService::Service {
       ServerContext* context,
       ::grpc::ServerReaderWriter<pb::FlightData, pb::FlightData>* stream) {
     GrpcServerCallContext flight_context(context);
-    GRPC_RETURN_NOT_GRPC_OK(CheckAuth(FlightMethod::DoExchange, context, 
flight_context));
-
+    GRPC_RETURN_NOT_GRPC_OK(
+        helper_.CheckAuth(FlightMethod::DoExchange, context, &flight_context));
     ExchangeDataStream data_stream(stream);
     RETURN_WITH_MIDDLEWARE(flight_context,
                            impl_->DoExchange(flight_context, &data_stream));
@@ -519,7 +380,7 @@ class GrpcServiceHandler final : public 
FlightService::Service {
                              ServerWriter<pb::ActionType>* writer) {
     GrpcServerCallContext flight_context(context);
     GRPC_RETURN_NOT_GRPC_OK(
-        CheckAuth(FlightMethod::ListActions, context, flight_context));
+        helper_.CheckAuth(FlightMethod::ListActions, context, 
&flight_context));
     // Retrieve the listing from the implementation
     std::vector<ActionType> types;
     SERVICE_RETURN_NOT_OK(flight_context,
@@ -530,7 +391,8 @@ class GrpcServiceHandler final : public 
FlightService::Service {
   ::grpc::Status DoAction(ServerContext* context, const pb::Action* request,
                           ServerWriter<pb::Result>* writer) {
     GrpcServerCallContext flight_context(context);
-    GRPC_RETURN_NOT_GRPC_OK(CheckAuth(FlightMethod::DoAction, context, 
flight_context));
+    GRPC_RETURN_NOT_GRPC_OK(
+        helper_.CheckAuth(FlightMethod::DoAction, context, &flight_context));
     CHECK_ARG_NOT_NULL(flight_context, request, "Action cannot be null");
     Action action;
     SERVICE_RETURN_NOT_OK(flight_context, internal::FromProto(*request, 
&action));
@@ -561,9 +423,7 @@ class GrpcServiceHandler final : public 
FlightService::Service {
   }
 
  private:
-  std::shared_ptr<ServerAuthHandler> auth_handler_;
-  std::vector<std::pair<std::string, std::shared_ptr<ServerMiddlewareFactory>>>
-      middleware_;
+  GrpcContextHelper helper_;
   internal::ServerTransport* impl_;
 };
 
@@ -583,62 +443,26 @@ class GrpcServerTransport : public 
internal::ServerTransport {
         new GrpcServiceHandler(options.auth_handler, options.middleware, 
this));
 
     ::grpc::ServerBuilder builder;
-    // Allow uploading messages of any length
-    builder.SetMaxReceiveMessageSize(-1);
-
-    const std::string scheme = uri.scheme();
     int port = 0;
-    if (scheme == kSchemeGrpc || scheme == kSchemeGrpcTcp || scheme == 
kSchemeGrpcTls) {
-      std::stringstream address;
-      address << arrow::util::UriEncodeHost(uri.host()) << ':' << 
uri.port_text();
-
-      std::shared_ptr<::grpc::ServerCredentials> creds;
-      if (scheme == kSchemeGrpcTls) {
-        ::grpc::SslServerCredentialsOptions ssl_options;
-        for (const auto& pair : options.tls_certificates) {
-          ssl_options.pem_key_cert_pairs.push_back({pair.pem_key, 
pair.pem_cert});
-        }
-        if (options.verify_client) {
-          ssl_options.client_certificate_request =
-              GRPC_SSL_REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_AND_VERIFY;
-        }
-        if (!options.root_certificates.empty()) {
-          ssl_options.pem_root_certs = options.root_certificates;
-        }
-        creds = ::grpc::SslServerCredentials(ssl_options);
-      } else {
-        creds = ::grpc::InsecureServerCredentials();
-      }
-
-      builder.AddListeningPort(address.str(), creds, &port);
-    } else if (scheme == kSchemeGrpcUnix) {
-      std::stringstream address;
-      address << "unix:" << uri.path();
-      builder.AddListeningPort(address.str(), 
::grpc::InsecureServerCredentials());
-      location_ = options.location;
+    ARROW_ASSIGN_OR_RAISE(auto endpoint, ParseServerEndpoint(options, uri));
+    location_ = endpoint.location;
+    if (uri.scheme() == kSchemeGrpcUnix) {
+      builder.AddListeningPort(endpoint.address, endpoint.credentials);
     } else {
-      return Status::NotImplemented("Scheme is not supported: " + scheme);
+      builder.AddListeningPort(endpoint.address, endpoint.credentials, &port);
     }
 
     builder.RegisterService(grpc_service_.get());
-
-    // Disable SO_REUSEPORT - it makes debugging/testing a pain as
-    // leftover processes can handle requests on accident
-    builder.AddChannelArgument(GRPC_ARG_ALLOW_REUSEPORT, 0);
-
-    if (options.builder_hook) {
-      options.builder_hook(&builder);
-    }
+    ConfigureServerBuilderOptions(options, &builder);
 
     grpc_server_ = builder.BuildAndStart();
     if (!grpc_server_) {
       return Status::UnknownError("Server did not start properly");
     }
-
-    if (scheme == kSchemeGrpcTls) {
+    if (uri.scheme() == kSchemeGrpcTls) {
       ARROW_ASSIGN_OR_RAISE(
           location_, 
Location::ForGrpcTls(arrow::util::UriEncodeHost(uri.host()), port));
-    } else if (scheme == kSchemeGrpc || scheme == kSchemeGrpcTcp) {
+    } else if (uri.scheme() == kSchemeGrpc || uri.scheme() == kSchemeGrpcTcp) {
       ARROW_ASSIGN_OR_RAISE(
           location_, 
Location::ForGrpcTcp(arrow::util::UriEncodeHost(uri.host()), port));
     }
diff --git a/cpp/src/arrow/flight/transport/grpc/grpc_server_internal.cc 
b/cpp/src/arrow/flight/transport/grpc/grpc_server_internal.cc
new file mode 100644
index 00000000000..0c1931ba735
--- /dev/null
+++ b/cpp/src/arrow/flight/transport/grpc/grpc_server_internal.cc
@@ -0,0 +1,75 @@
+// 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.
+
+#include "arrow/flight/transport/grpc/grpc_server_internal.h"
+
+#include <sstream>
+
+namespace arrow::flight::transport::grpc {
+
+arrow::Result<GrpcServerEndpoint> ParseServerEndpoint(const 
FlightServerOptions& options,
+                                                      const arrow::util::Uri& 
uri) {
+  GrpcServerEndpoint endpoint;
+  endpoint.location = options.location;
+  const std::string scheme = uri.scheme();
+  if (scheme == kSchemeGrpc || scheme == kSchemeGrpcTcp || scheme == 
kSchemeGrpcTls) {
+    std::stringstream address;
+    address << arrow::util::UriEncodeHost(uri.host()) << ':' << 
uri.port_text();
+    endpoint.address = address.str();
+
+    if (scheme == kSchemeGrpcTls) {
+      ::grpc::SslServerCredentialsOptions ssl_options;
+      for (const auto& pair : options.tls_certificates) {
+        ssl_options.pem_key_cert_pairs.push_back(
+            {.private_key = pair.pem_key, .cert_chain = pair.pem_cert});
+      }
+      if (options.verify_client) {
+        ssl_options.client_certificate_request =
+            GRPC_SSL_REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_AND_VERIFY;
+      }
+      if (!options.root_certificates.empty()) {
+        ssl_options.pem_root_certs = options.root_certificates;
+      }
+      endpoint.credentials = ::grpc::SslServerCredentials(ssl_options);
+    } else {
+      endpoint.credentials = ::grpc::InsecureServerCredentials();
+    }
+    return endpoint;
+  }
+  if (scheme == kSchemeGrpcUnix) {
+    std::stringstream address;
+    address << "unix:" << uri.path();
+    endpoint.address = address.str();
+    endpoint.credentials = ::grpc::InsecureServerCredentials();
+    return endpoint;
+  }
+  return Status::NotImplemented("Scheme is not supported: " + scheme);
+}
+
+void ConfigureServerBuilderOptions(const FlightServerOptions& options,
+                                   ::grpc::ServerBuilder* builder) {
+  // Allow uploading messages of any length
+  builder->SetMaxReceiveMessageSize(-1);
+  // Disable SO_REUSEPORT - it makes debugging/testing a pain as
+  // leftover processes can handle requests on accident
+  builder->AddChannelArgument(GRPC_ARG_ALLOW_REUSEPORT, 0);
+  if (options.builder_hook) {
+    options.builder_hook(builder);
+  }
+}
+
+}  // namespace arrow::flight::transport::grpc
diff --git a/cpp/src/arrow/flight/transport/grpc/grpc_server_internal.h 
b/cpp/src/arrow/flight/transport/grpc/grpc_server_internal.h
new file mode 100644
index 00000000000..cdafb53a3e1
--- /dev/null
+++ b/cpp/src/arrow/flight/transport/grpc/grpc_server_internal.h
@@ -0,0 +1,206 @@
+// 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.
+
+#pragma once
+
+#include <memory>
+#include <string>
+#include <unordered_map>
+#include <utility>
+#include <vector>
+
+#include <grpcpp/grpcpp.h>
+
+#include "arrow/flight/server.h"
+#include "arrow/flight/server_middleware.h"
+#include "arrow/flight/transport/grpc/util_internal.h"
+#include "arrow/util/uri.h"
+
+namespace arrow::flight::transport::grpc {
+
+using MiddlewareFactoryList =
+    std::vector<std::pair<std::string, 
std::shared_ptr<ServerMiddlewareFactory>>>;
+
+template <typename GrpcContext>
+class GrpcAddServerHeaders : public AddCallHeaders {
+ public:
+  explicit GrpcAddServerHeaders(GrpcContext* context) : context_(context) {}
+  ~GrpcAddServerHeaders() override = default;
+
+  void AddHeader(const std::string& key, const std::string& value) override {
+    context_->AddInitialMetadata(key, value);
+  }
+
+ private:
+  GrpcContext* context_;
+};
+
+template <typename GrpcContext>
+class GrpcServerCallContext : public ServerCallContext {
+ public:
+  explicit GrpcServerCallContext(GrpcContext* context)
+      : context_(context), peer_(context->peer()) {
+    for (const auto& entry : context->client_metadata()) {
+      incoming_headers_.insert(
+          {std::string_view(entry.first.data(), entry.first.length()),
+           std::string_view(entry.second.data(), entry.second.length())});
+    }
+  }
+
+  const std::string& peer_identity() const override { return peer_identity_; }
+  const std::string& peer() const override { return peer_; }
+  bool is_cancelled() const override { return context_->IsCancelled(); }
+  const CallHeaders& incoming_headers() const override { return 
incoming_headers_; }
+
+  // Helper method that runs interceptors given the result of an RPC,
+  // then returns the final gRPC status to send to the client
+  ::grpc::Status FinishRequest(const ::grpc::Status& status) {
+    // Don't double-convert status - return the original one here
+    FinishRequest(FromGrpcStatus(status));
+    return status;
+  }
+
+  ::grpc::Status FinishRequest(const Status& status) {
+    for (const auto& instance : middleware_) {
+      instance->CallCompleted(status);
+    }
+    return ToGrpcStatus(status, context_);
+  }
+
+  void AddHeader(const std::string& key, const std::string& value) const 
override {
+    context_->AddInitialMetadata(key, value);
+  }
+
+  void AddTrailer(const std::string& key, const std::string& value) const 
override {
+    context_->AddTrailingMetadata(key, value);
+  }
+
+  ServerMiddleware* GetMiddleware(const std::string& key) const override {
+    const auto& instance = middleware_map_.find(key);
+    if (instance == middleware_map_.end()) {
+      return nullptr;
+    }
+    return instance->second.get();
+  }
+
+ private:
+  template <typename>
+  friend class GrpcServerCallContextHelper;
+
+  GrpcContext* context_;
+  std::string peer_;
+  std::string peer_identity_;
+  std::vector<std::shared_ptr<ServerMiddleware>> middleware_;
+  std::unordered_map<std::string, std::shared_ptr<ServerMiddleware>> 
middleware_map_;
+  CallHeaders incoming_headers_;
+};
+
+template <typename GrpcContext>
+class GrpcServerCallContextHelper {
+ public:
+  GrpcServerCallContextHelper(std::shared_ptr<ServerAuthHandler> auth_handler,
+                              MiddlewareFactoryList middleware)
+      : auth_handler_(std::move(auth_handler)), 
middleware_(std::move(middleware)) {}
+
+  // Authenticate the client (if applicable) and construct the call context
+  ::grpc::Status MakeCallContext(FlightMethod method, GrpcContext* context,
+                                 GrpcServerCallContext<GrpcContext>* 
flight_context,
+                                 bool skip_headers = false) const {
+    // Run server middleware
+    const CallInfo info{method};
+    for (const auto& factory : middleware_) {
+      std::shared_ptr<ServerMiddleware> instance;
+      Status result = factory.second->StartCall(info, *flight_context, 
&instance);
+      if (!result.ok()) {
+        // Interceptor rejected call, end the request on all existing
+        // interceptors
+        return flight_context->FinishRequest(result);
+      }
+      if (instance != nullptr) {
+        flight_context->middleware_.push_back(instance);
+        flight_context->middleware_map_.insert({factory.first, instance});
+      }
+    }
+    // TODO factor this out after fixing all streaming and non-streaming 
handlers
+    if (!skip_headers) {
+      AddMiddlewareHeaders(context, flight_context);
+    }
+
+    return ::grpc::Status::OK;
+  }
+
+  void AddMiddlewareHeaders(GrpcContext* context,
+                            GrpcServerCallContext<GrpcContext>* 
flight_context) const {
+    GrpcAddServerHeaders<GrpcContext> outgoing_headers(context);
+    for (const auto& instance : flight_context->middleware_) {
+      instance->SendingHeaders(&outgoing_headers);
+    }
+  }
+
+  // Authenticate the client (if applicable) and construct the call context
+  ::grpc::Status CheckAuth(FlightMethod method, GrpcContext* context,
+                           GrpcServerCallContext<GrpcContext>* flight_context) 
const {
+    if (!auth_handler_) {
+      const auto auth_context = context->auth_context();
+      if (auth_context && auth_context->IsPeerAuthenticated()) {
+        auto peer_identity = auth_context->GetPeerIdentity();
+        flight_context->peer_identity_ =
+            peer_identity.empty()
+                ? ""
+                : std::string(peer_identity.front().begin(), 
peer_identity.front().end());
+      } else {
+        flight_context->peer_identity_ = "";
+      }
+    } else {
+      const auto client_metadata = context->client_metadata();
+      const auto [auth_header, auth_header_end] =
+          client_metadata.equal_range(kGrpcAuthHeader);
+      std::string token;
+      if (auth_header != auth_header_end) {
+        token = std::string(auth_header->second.data(), 
auth_header->second.length());
+      }
+      auto auth_status =
+          auth_handler_->IsValid(*flight_context, token, 
&flight_context->peer_identity_);
+      if (!auth_status.ok()) {
+        return flight_context->FinishRequest(auth_status);
+      }
+    }
+    return MakeCallContext(method, context, flight_context);
+  }
+
+  const std::shared_ptr<ServerAuthHandler>& auth_handler() const { return 
auth_handler_; }
+
+ private:
+  std::shared_ptr<ServerAuthHandler> auth_handler_;
+  MiddlewareFactoryList middleware_;
+};
+
+struct GrpcServerEndpoint {
+  std::string address;
+  std::shared_ptr<::grpc::ServerCredentials> credentials;
+  Location location;
+};
+
+ARROW_FLIGHT_EXPORT
+arrow::Result<GrpcServerEndpoint> ParseServerEndpoint(const 
FlightServerOptions& options,
+                                                      const arrow::util::Uri& 
uri);
+
+ARROW_FLIGHT_EXPORT
+void ConfigureServerBuilderOptions(const FlightServerOptions& options,
+                                   ::grpc::ServerBuilder* builder);
+
+}  // namespace arrow::flight::transport::grpc
diff --git a/cpp/src/arrow/flight/transport_server.cc 
b/cpp/src/arrow/flight/transport_server.cc
index 197def7cabd..9830547cfbd 100644
--- a/cpp/src/arrow/flight/transport_server.cc
+++ b/cpp/src/arrow/flight/transport_server.cc
@@ -17,16 +17,8 @@
 
 #include "arrow/flight/transport_server.h"
 
-#include <unordered_map>
-
-#include "arrow/buffer.h"
-#include "arrow/flight/serialization_internal.h"
 #include "arrow/flight/server.h"
-#include "arrow/flight/types.h"
-#include "arrow/ipc/reader.h"
-#include "arrow/result.h"
-#include "arrow/status.h"
-#include "arrow/util/logging_internal.h"
+#include "arrow/flight/transport_server_internal.h"
 
 namespace arrow {
 namespace flight {
@@ -36,289 +28,11 @@ Status ServerDataStream::WritePutMetadata(const Buffer&) {
   return Status::NotImplemented("Writing put metadata for this stream");
 }
 
-namespace {
-class TransportIpcMessageReader : public ipc::MessageReader {
- public:
-  TransportIpcMessageReader(
-      std::shared_ptr<internal::PeekableFlightDataReader> peekable_reader,
-      std::shared_ptr<MemoryManager> memory_manager,
-      std::shared_ptr<Buffer>* app_metadata)
-      : peekable_reader_(peekable_reader),
-        memory_manager_(std::move(memory_manager)),
-        app_metadata_(app_metadata) {}
-
-  ::arrow::Result<std::unique_ptr<ipc::Message>> ReadNextMessage() override {
-    if (stream_finished_) return nullptr;
-    internal::FlightData* data;
-    peekable_reader_->Next(&data);
-    if (!data) {
-      stream_finished_ = true;
-      return nullptr;
-    }
-    if (data->body) {
-      ARROW_ASSIGN_OR_RAISE(data->body, Buffer::ViewOrCopy(data->body, 
memory_manager_));
-    }
-    *app_metadata_ = std::move(data->app_metadata);
-    return data->OpenMessage();
-  }
-
- protected:
-  std::shared_ptr<internal::PeekableFlightDataReader> peekable_reader_;
-  std::shared_ptr<MemoryManager> memory_manager_;
-  // A reference to TransportDataStream.app_metadata_. That class
-  // can't access the app metadata because when it Peek()s the stream,
-  // it may be looking at a dictionary batch, not the record
-  // batch. Updating it here ensures the reader is always updated with
-  // the last metadata message read.
-  std::shared_ptr<Buffer>* app_metadata_;
-  bool stream_finished_ = false;
-};
-
-/// \brief Adapt TransportDataStream to the FlightMessageReader
-///   interface for DoPut.
-class TransportMessageReader final : public FlightMessageReader {
- public:
-  TransportMessageReader(ServerDataStream* stream,
-                         std::shared_ptr<MemoryManager> memory_manager)
-      : peekable_reader_(new internal::PeekableFlightDataReader(stream)),
-        memory_manager_(std::move(memory_manager)) {}
-
-  Status Init() {
-    // Peek the first message to get the descriptor.
-    internal::FlightData* data;
-    peekable_reader_->Peek(&data);
-    if (!data) {
-      return Status::IOError("Stream finished before first message sent");
-    }
-    if (!data->descriptor) {
-      return Status::IOError("Descriptor missing on first message");
-    }
-    descriptor_ = *data->descriptor;
-    // If there's a schema (=DoPut), also Open().
-    if (data->metadata) {
-      return EnsureDataStarted();
-    }
-    peekable_reader_->Next(&data);
-    return Status::OK();
-  }
-
-  const FlightDescriptor& descriptor() const override { return descriptor_; }
-
-  arrow::Result<std::shared_ptr<Schema>> GetSchema() override {
-    RETURN_NOT_OK(EnsureDataStarted());
-    return batch_reader_->schema();
-  }
-
-  arrow::Result<FlightStreamChunk> Next() override {
-    FlightStreamChunk out;
-    internal::FlightData* data = nullptr;
-    peekable_reader_->Peek(&data);
-    if (!data) {
-      out.app_metadata = nullptr;
-      out.data = nullptr;
-      return out;
-    }
-
-    if (!data->metadata) {
-      // Metadata-only (data->metadata is the IPC header)
-      out.app_metadata = data->app_metadata;
-      out.data = nullptr;
-      peekable_reader_->Next(&data);
-      return out;
-    }
-
-    if (!batch_reader_) {
-      RETURN_NOT_OK(EnsureDataStarted());
-      // re-peek here since EnsureDataStarted() advances the stream
-      return Next();
-    }
-    RETURN_NOT_OK(batch_reader_->ReadNext(&out.data));
-    out.app_metadata = std::move(app_metadata_);
-    return out;
-  }
-
-  ipc::ReadStats stats() const override {
-    if (batch_reader_ == nullptr) {
-      return ipc::ReadStats{};
-    }
-    return batch_reader_->stats();
-  }
-
- private:
-  /// Ensure we are set up to read data.
-  Status EnsureDataStarted() {
-    if (!batch_reader_) {
-      // peek() until we find the first data message; discard metadata
-      if (!peekable_reader_->SkipToData()) {
-        return Status::IOError("Client never sent a data message");
-      }
-      auto message_reader =
-          std::unique_ptr<ipc::MessageReader>(new TransportIpcMessageReader(
-              peekable_reader_, memory_manager_, &app_metadata_));
-      ARROW_ASSIGN_OR_RAISE(
-          batch_reader_, 
ipc::RecordBatchStreamReader::Open(std::move(message_reader)));
-    }
-    return Status::OK();
-  }
-
-  FlightDescriptor descriptor_;
-  std::shared_ptr<internal::PeekableFlightDataReader> peekable_reader_;
-  std::shared_ptr<MemoryManager> memory_manager_;
-  std::shared_ptr<ipc::RecordBatchStreamReader> batch_reader_;
-  std::shared_ptr<Buffer> app_metadata_;
-};
-
-/// \brief An IpcPayloadWriter for ServerDataStream.
-///
-/// To support app_metadata and reuse the existing IPC infrastructure,
-/// this takes a pointer to a buffer to be combined with the IPC
-/// payload when writing a Flight payload.
-class TransportMessagePayloadWriter : public ipc::internal::IpcPayloadWriter {
- public:
-  TransportMessagePayloadWriter(ServerDataStream* stream,
-                                std::shared_ptr<Buffer>* app_metadata)
-      : stream_(stream), app_metadata_(app_metadata) {}
-
-  Status Start() override { return Status::OK(); }
-  Status WritePayload(const ipc::IpcPayload& ipc_payload) override {
-    FlightPayload payload;
-    payload.ipc_message = ipc_payload;
-
-    if (ipc_payload.type == ipc::MessageType::RECORD_BATCH && *app_metadata_) {
-      payload.app_metadata = std::move(*app_metadata_);
-    }
-    ARROW_ASSIGN_OR_RAISE(auto success, stream_->WriteData(payload));
-    if (!success) {
-      return MakeFlightError(
-          FlightStatusCode::Internal,
-          "Could not write record batch to stream (client disconnect?)");
-    }
-    return arrow::Status::OK();
-  }
-  Status Close() override {
-    // Closing is handled one layer up in TransportMessageWriter::Close
-    return Status::OK();
-  }
-
- private:
-  ServerDataStream* stream_;
-  std::shared_ptr<Buffer>* app_metadata_;
-};
-
-class TransportMessageWriter final : public FlightMessageWriter {
- public:
-  explicit TransportMessageWriter(ServerDataStream* stream)
-      : stream_(stream),
-        app_metadata_(nullptr),
-        ipc_options_(::arrow::ipc::IpcWriteOptions::Defaults()) {}
-
-  Status Begin(const std::shared_ptr<Schema>& schema,
-               const ipc::IpcWriteOptions& options) override {
-    if (batch_writer_) {
-      return Status::Invalid("This writer has already been started.");
-    }
-    ipc_options_ = options;
-    std::unique_ptr<ipc::internal::IpcPayloadWriter> payload_writer(
-        new TransportMessagePayloadWriter(stream_, &app_metadata_));
-
-    ARROW_ASSIGN_OR_RAISE(batch_writer_,
-                          
ipc::internal::OpenRecordBatchWriter(std::move(payload_writer),
-                                                               schema, 
ipc_options_));
-    return Status::OK();
-  }
-
-  Status WriteRecordBatch(const RecordBatch& batch) override {
-    return WriteWithMetadata(batch, nullptr);
-  }
-
-  Status WriteMetadata(std::shared_ptr<Buffer> app_metadata) override {
-    FlightPayload payload{};
-    payload.app_metadata = app_metadata;
-    ARROW_ASSIGN_OR_RAISE(auto success, stream_->WriteData(payload));
-    if (!success) {
-      ARROW_RETURN_NOT_OK(Close());
-      return MakeFlightError(FlightStatusCode::Internal,
-                             "Could not write metadata to stream (client 
disconnect?)");
-    }
-    return Status::OK();
-  }
-
-  Status WriteWithMetadata(const RecordBatch& batch,
-                           std::shared_ptr<Buffer> app_metadata) override {
-    RETURN_NOT_OK(CheckStarted());
-    app_metadata_ = app_metadata;
-    auto status = batch_writer_->WriteRecordBatch(batch);
-    if (!status.ok()) {
-      ARROW_RETURN_NOT_OK(Close());
-    }
-    return status;
-  }
-
-  Status Close() override {
-    if (batch_writer_) {
-      RETURN_NOT_OK(batch_writer_->Close());
-    }
-    return Status::OK();
-  }
-
-  ipc::WriteStats stats() const override {
-    ARROW_CHECK_NE(batch_writer_, nullptr);
-    return batch_writer_->stats();
-  }
-
- private:
-  Status CheckStarted() {
-    if (!batch_writer_) {
-      return Status::Invalid("This writer is not started. Call Begin() with a 
schema");
-    }
-    return Status::OK();
-  }
-
-  ServerDataStream* stream_;
-  std::unique_ptr<ipc::RecordBatchWriter> batch_writer_;
-  std::shared_ptr<Buffer> app_metadata_;
-  ::arrow::ipc::IpcWriteOptions ipc_options_;
-};
-
-/// \brief Adapt TransportDataStream to the FlightMetadataWriter
-///   interface for DoPut.
-class TransportMetadataWriter final : public FlightMetadataWriter {
- public:
-  explicit TransportMetadataWriter(ServerDataStream* stream) : stream_(stream) 
{}
-
-  Status WriteMetadata(const Buffer& buffer) override {
-    return stream_->WritePutMetadata(buffer);
-  }
-
- private:
-  ServerDataStream* stream_;
-};
-}  // namespace
-
 Status ServerTransport::DoGet(const ServerCallContext& context, const Ticket& 
ticket,
                               ServerDataStream* stream) {
   std::unique_ptr<FlightDataStream> data_stream;
   RETURN_NOT_OK(base_->DoGet(context, ticket, &data_stream));
-
-  if (!data_stream) return Status::KeyError("No data in this flight");
-
-  // Write the schema as the first message in the stream
-  ARROW_ASSIGN_OR_RAISE(auto schema_payload, data_stream->GetSchemaPayload());
-  ARROW_ASSIGN_OR_RAISE(auto success, stream->WriteData(schema_payload));
-  // Connection terminated
-  if (!success) return Status::OK();
-
-  // Consume data stream and write out payloads
-  while (true) {
-    ARROW_ASSIGN_OR_RAISE(FlightPayload payload, data_stream->Next());
-    // End of stream
-    if (payload.ipc_message.metadata == nullptr) break;
-    ARROW_ASSIGN_OR_RAISE(auto success, stream->WriteData(payload));
-    // Connection terminated
-    if (!success) return Status::OK();
-  }
-  RETURN_NOT_OK(stream->WritesDone());
-  return data_stream->Close();
+  return WriteDataStream(std::move(data_stream), stream);
 }
 
 Status ServerTransport::DoPut(const ServerCallContext& context,
diff --git a/cpp/src/arrow/flight/transport_server_internal.cc 
b/cpp/src/arrow/flight/transport_server_internal.cc
new file mode 100644
index 00000000000..be159afa5d9
--- /dev/null
+++ b/cpp/src/arrow/flight/transport_server_internal.cc
@@ -0,0 +1,332 @@
+// 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.
+
+#include "arrow/flight/transport_server_internal.h"
+
+#include "arrow/buffer.h"
+#include "arrow/flight/serialization_internal.h"
+#include "arrow/flight/transport_server.h"
+#include "arrow/ipc/reader.h"
+
+namespace arrow::flight::internal {
+namespace {
+
+class TransportIpcMessageReader : public ipc::MessageReader {
+ public:
+  TransportIpcMessageReader(std::shared_ptr<PeekableFlightDataReader> 
peekable_reader,
+                            std::shared_ptr<MemoryManager> memory_manager,
+                            std::shared_ptr<Buffer>* app_metadata)
+      : peekable_reader_(std::move(peekable_reader)),
+        memory_manager_(std::move(memory_manager)),
+        app_metadata_(app_metadata) {}
+
+  arrow::Result<std::unique_ptr<ipc::Message>> ReadNextMessage() override {
+    if (stream_finished_) return nullptr;
+    FlightData* data;
+    peekable_reader_->Next(&data);
+    if (!data) {
+      stream_finished_ = true;
+      return nullptr;
+    }
+    if (data->body) {
+      ARROW_ASSIGN_OR_RAISE(data->body, Buffer::ViewOrCopy(data->body, 
memory_manager_));
+    }
+    *app_metadata_ = std::move(data->app_metadata);
+    return data->OpenMessage();
+  }
+
+ private:
+  std::shared_ptr<PeekableFlightDataReader> peekable_reader_;
+  std::shared_ptr<MemoryManager> memory_manager_;
+  // A reference to TransportDataStream.app_metadata_. That class
+  // can't access the app metadata because when it Peek()s the stream,
+  // it may be looking at a dictionary batch, not the record
+  // batch. Updating it here ensures the reader is always updated with
+  // the last metadata message read.
+  std::shared_ptr<Buffer>* app_metadata_;
+  bool stream_finished_ = false;
+};
+
+}  // namespace
+
+TransportMessageReader::TransportMessageReader(
+    ServerDataStream* stream, std::shared_ptr<MemoryManager> memory_manager)
+    : peekable_reader_(new PeekableFlightDataReader(stream)),
+      memory_manager_(std::move(memory_manager)) {}
+
+Status TransportMessageReader::Init() {
+  // Peek the first message to get the descriptor.
+  FlightData* data;
+  peekable_reader_->Peek(&data);
+  if (!data) {
+    return Status::IOError("Stream finished before first message sent");
+  }
+  if (!data->descriptor) {
+    return Status::IOError("Descriptor missing on first message");
+  }
+  descriptor_ = *data->descriptor;
+  // If there's a schema (=DoPut), also Open().
+  if (data->metadata) {
+    return EnsureDataStarted();
+  }
+  peekable_reader_->Next(&data);
+  return Status::OK();
+}
+
+const FlightDescriptor& TransportMessageReader::descriptor() const { return 
descriptor_; }
+
+arrow::Result<std::shared_ptr<Schema>> TransportMessageReader::GetSchema() {
+  RETURN_NOT_OK(EnsureDataStarted());
+  return batch_reader_->schema();
+}
+
+arrow::Result<FlightStreamChunk> TransportMessageReader::Next() {
+  FlightStreamChunk out;
+  FlightData* data = nullptr;
+  peekable_reader_->Peek(&data);
+  if (!data) {
+    out.app_metadata = nullptr;
+    out.data = nullptr;
+    return out;
+  }
+
+  if (!data->metadata) {
+    // Metadata-only (data->metadata is the IPC header)
+    out.app_metadata = data->app_metadata;
+    out.data = nullptr;
+    peekable_reader_->Next(&data);
+    return out;
+  }
+
+  if (!batch_reader_) {
+    RETURN_NOT_OK(EnsureDataStarted());
+    // re-peek here since EnsureDataStarted() advances the stream
+    return Next();
+  }
+  RETURN_NOT_OK(batch_reader_->ReadNext(&out.data));
+  out.app_metadata = std::move(app_metadata_);
+  return out;
+}
+
+ipc::ReadStats TransportMessageReader::stats() const {
+  if (batch_reader_ == nullptr) {
+    return ipc::ReadStats{};
+  }
+  return batch_reader_->stats();
+}
+
+Status TransportMessageReader::EnsureDataStarted() {
+  if (!batch_reader_) {
+    // peek() until we find the first data message; discard metadata
+    if (!peekable_reader_->SkipToData()) {
+      return Status::IOError("Client never sent a data message");
+    }
+    auto message_reader = std::unique_ptr<ipc::MessageReader>(
+        new TransportIpcMessageReader(peekable_reader_, memory_manager_, 
&app_metadata_));
+    ARROW_ASSIGN_OR_RAISE(batch_reader_,
+                          
ipc::RecordBatchStreamReader::Open(std::move(message_reader)));
+  }
+  return Status::OK();
+}
+
+namespace {
+
+/// \brief An IpcPayloadWriter for ServerDataStream.
+///
+/// To support app_metadata and reuse the existing IPC infrastructure,
+/// this takes a pointer to a buffer to be combined with the IPC
+/// payload when writing a Flight payload.
+class TransportMessagePayloadWriter : public ipc::internal::IpcPayloadWriter {
+ public:
+  TransportMessagePayloadWriter(ServerDataStream* stream,
+                                std::shared_ptr<Buffer>* app_metadata)
+      : stream_(stream), app_metadata_(app_metadata) {}
+
+  Status Start() override { return Status::OK(); }
+
+  Status WritePayload(const ipc::IpcPayload& ipc_payload) override {
+    FlightPayload payload;
+    payload.ipc_message = ipc_payload;
+    if (ipc_payload.type == ipc::MessageType::RECORD_BATCH && *app_metadata_) {
+      payload.app_metadata = std::move(*app_metadata_);
+    }
+    ARROW_ASSIGN_OR_RAISE(auto success, stream_->WriteData(payload));
+    if (!success) {
+      return MakeFlightError(
+          FlightStatusCode::Internal,
+          "Could not write record batch to stream (client disconnect?)");
+    }
+    return Status::OK();
+  }
+
+  Status Close() override {
+    // Closing is handled one layer up in TransportMessageWriter::Close
+    return Status::OK();
+  }
+
+ private:
+  ServerDataStream* stream_;
+  std::shared_ptr<Buffer>* app_metadata_;
+};
+
+}  // namespace
+
+TransportMessageWriter::TransportMessageWriter(ServerDataStream* stream)
+    : stream_(stream),
+      app_metadata_(nullptr),
+      ipc_options_(::arrow::ipc::IpcWriteOptions::Defaults()) {}
+
+Status TransportMessageWriter::Begin(const std::shared_ptr<Schema>& schema,
+                                     const ipc::IpcWriteOptions& options) {
+  if (batch_writer_) {
+    return Status::Invalid("This writer has already been started.");
+  }
+  ipc_options_ = options;
+  std::unique_ptr<ipc::internal::IpcPayloadWriter> payload_writer(
+      new TransportMessagePayloadWriter(stream_, &app_metadata_));
+  ARROW_ASSIGN_OR_RAISE(batch_writer_,
+                        
ipc::internal::OpenRecordBatchWriter(std::move(payload_writer),
+                                                             schema, 
ipc_options_));
+  return Status::OK();
+}
+
+Status TransportMessageWriter::WriteRecordBatch(const RecordBatch& batch) {
+  return WriteWithMetadata(batch, nullptr);
+}
+
+Status TransportMessageWriter::WriteMetadata(std::shared_ptr<Buffer> 
app_metadata) {
+  FlightPayload payload{};
+  payload.app_metadata = std::move(app_metadata);
+  ARROW_ASSIGN_OR_RAISE(auto success, stream_->WriteData(payload));
+  if (!success) {
+    ARROW_RETURN_NOT_OK(Close());
+    return MakeFlightError(FlightStatusCode::Internal,
+                           "Could not write metadata to stream (client 
disconnect?)");
+  }
+  return Status::OK();
+}
+
+Status TransportMessageWriter::WriteWithMetadata(const RecordBatch& batch,
+                                                 std::shared_ptr<Buffer> 
app_metadata) {
+  RETURN_NOT_OK(CheckStarted());
+  app_metadata_ = std::move(app_metadata);
+  auto status = batch_writer_->WriteRecordBatch(batch);
+  if (!status.ok()) {
+    ARROW_RETURN_NOT_OK(Close());
+  }
+  return status;
+}
+
+Status TransportMessageWriter::Close() {
+  if (batch_writer_) {
+    RETURN_NOT_OK(batch_writer_->Close());
+  }
+  return Status::OK();
+}
+
+ipc::WriteStats TransportMessageWriter::stats() const {
+  ARROW_CHECK_NE(batch_writer_, nullptr);
+  return batch_writer_->stats();
+}
+
+Status TransportMessageWriter::CheckStarted() {
+  if (!batch_writer_) {
+    return Status::Invalid("This writer is not started. Call Begin() with a 
schema");
+  }
+  return Status::OK();
+}
+
+TransportMetadataWriter::TransportMetadataWriter(ServerDataStream* stream)
+    : stream_(stream) {}
+
+Status TransportMetadataWriter::WriteMetadata(const Buffer& buffer) {
+  return stream_->WritePutMetadata(buffer);
+}
+
+std::atomic<ServerSignalState*> ServerSignalState::running_instance_;
+
+Status ServerSignalState::SetShutdownOnSignals(const std::vector<int>& sigs) {
+  signals_ = sigs;
+  old_signal_handlers_.clear();
+  return Status::OK();
+}
+
+int ServerSignalState::GotSignal() const { return got_signal_; }
+
+void ServerSignalState::HandleSignal(int signum) {
+  auto instance = running_instance_.load();
+  if (instance != nullptr) {
+    instance->DoHandleSignal(signum);
+  }
+}
+
+void ServerSignalState::DoHandleSignal(int signum) {
+  got_signal_ = signum;
+  // Send dummy payload over self-pipe
+  self_pipe_->Send(/*payload=*/0);
+}
+
+void ServerSignalState::WaitForSignals(
+    std::shared_ptr<::arrow::internal::SelfPipe> self_pipe) {
+  // Wait for a signal handler to wake up the pipe
+  auto st = self_pipe->Wait().status();
+  if (!st.ok()) {
+    // Status::Invalid means the pipe was shutdown without any wakeup
+    if (!st.IsInvalid()) {
+      ARROW_LOG(FATAL) << "Failed to wait on self-pipe: " << st.ToString();
+    }
+    // Nothing to shut down: Serve() is already tearing down.
+    return;
+  }
+  auto instance = running_instance_.load();
+  if (instance != nullptr && instance->shutdown_) {
+    ARROW_WARN_NOT_OK(instance->shutdown_(), instance->shutdown_warning_);
+  }
+}
+
+Status WriteDataStream(std::unique_ptr<FlightDataStream> data_stream,
+                       ServerDataStream* stream) {
+  if (!data_stream) {
+    return Status::KeyError("No data in this flight");
+  }
+
+  // Write the schema as the first message in the stream
+  ARROW_ASSIGN_OR_RAISE(auto schema_payload, data_stream->GetSchemaPayload());
+  ARROW_ASSIGN_OR_RAISE(auto success, stream->WriteData(schema_payload));
+  // Connection terminated
+  if (!success) {
+    return Status::OK();
+  }
+
+  // Consume data stream and write out payloads
+  while (true) {
+    ARROW_ASSIGN_OR_RAISE(FlightPayload payload, data_stream->Next());
+    // End of stream
+    if (payload.ipc_message.metadata == nullptr) {
+      break;
+    }
+    ARROW_ASSIGN_OR_RAISE(success, stream->WriteData(payload));
+    // Connection terminated
+    if (!success) {
+      return Status::OK();
+    }
+  }
+  RETURN_NOT_OK(stream->WritesDone());
+  return data_stream->Close();
+}
+
+}  // namespace arrow::flight::internal
diff --git a/cpp/src/arrow/flight/transport_server_internal.h 
b/cpp/src/arrow/flight/transport_server_internal.h
new file mode 100644
index 00000000000..2112d613c6b
--- /dev/null
+++ b/cpp/src/arrow/flight/transport_server_internal.h
@@ -0,0 +1,305 @@
+// 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.
+
+#pragma once
+
+#include <atomic>
+#include <chrono>
+#include <memory>
+#include <thread>
+#include <utility>
+#include <vector>
+
+#include "arrow/flight/platform.h"
+#include "arrow/flight/server.h"
+#include "arrow/flight/visibility.h"
+#include "arrow/result.h"
+#include "arrow/status.h"
+#include "arrow/util/io_util.h"
+#include "arrow/util/logging.h"
+#include "arrow/util/uri.h"
+
+namespace arrow::flight::internal {
+
+class ServerDataStream;
+class PeekableFlightDataReader;
+
+/// \brief Adapt TransportDataStream to the FlightMessageReader
+///   interface for DoPut.
+class TransportMessageReader final : public FlightMessageReader {
+ public:
+  TransportMessageReader(ServerDataStream* stream,
+                         std::shared_ptr<MemoryManager> memory_manager);
+
+  Status Init();
+
+  const FlightDescriptor& descriptor() const override;
+
+  arrow::Result<std::shared_ptr<Schema>> GetSchema() override;
+
+  arrow::Result<FlightStreamChunk> Next() override;
+
+  ipc::ReadStats stats() const override;
+
+ private:
+  /// Ensure we are set up to read data.
+  Status EnsureDataStarted();
+
+  FlightDescriptor descriptor_;
+  std::shared_ptr<PeekableFlightDataReader> peekable_reader_;
+  std::shared_ptr<MemoryManager> memory_manager_;
+  std::shared_ptr<ipc::RecordBatchStreamReader> batch_reader_;
+  std::shared_ptr<Buffer> app_metadata_;
+};
+
+/// \brief A writer for IPC payloads to a ServerDataStream.
+class TransportMessageWriter final : public FlightMessageWriter {
+ public:
+  explicit TransportMessageWriter(ServerDataStream* stream);
+
+  Status Begin(const std::shared_ptr<Schema>& schema,
+               const ipc::IpcWriteOptions& options) override;
+
+  Status WriteRecordBatch(const RecordBatch& batch) override;
+
+  Status WriteMetadata(std::shared_ptr<Buffer> app_metadata) override;
+
+  Status WriteWithMetadata(const RecordBatch& batch,
+                           std::shared_ptr<Buffer> app_metadata) override;
+
+  Status Close() override;
+
+  ipc::WriteStats stats() const override;
+
+ private:
+  Status CheckStarted();
+
+  ServerDataStream* stream_;
+  std::unique_ptr<ipc::RecordBatchWriter> batch_writer_;
+  std::shared_ptr<Buffer> app_metadata_;
+  ::arrow::ipc::IpcWriteOptions ipc_options_;
+};
+
+/// \brief A writer for application-defined metadata to a ServerDataStream.
+class TransportMetadataWriter final : public FlightMetadataWriter {
+ public:
+  explicit TransportMetadataWriter(ServerDataStream* stream);
+
+  Status WriteMetadata(const Buffer& buffer) override;
+
+ private:
+  ServerDataStream* stream_;
+};
+
+/// \brief Write a FlightDataStream to a transport-level stream.
+///
+/// Used by DoGet and DoExchange to stream results back to the client.
+/// The schema is written first, followed by record batches until the
+/// stream is exhausted.
+///
+/// \param[in] data_stream The Arrow data stream to read from.
+/// \param[in] stream The transport-specific data stream to write to.
+Status WriteDataStream(std::unique_ptr<FlightDataStream> data_stream,
+                       ServerDataStream* stream);
+
+/// \brief Manages a background thread that waits for OS signals.
+///
+/// Creates a signal-safe SelfPipe and spawns a thread that blocks on it.
+/// When a signal is received, the signal handler writes to the SelfPipe
+/// to wake the thread. The destructor ensures the thread is joined.
+class ServerSignalHandler {
+ public:
+  ARROW_DISALLOW_COPY_AND_ASSIGN(ServerSignalHandler);
+  ServerSignalHandler() = default;
+
+  /// \brief Initialize the signal handler and start the background thread.
+  ///
+  /// \param[in] self_pipe The pipe the handler thread should wait on It is
+  /// stored before the thread is started, so the signal handler can always
+  /// write to it.
+  /// \param[in] handler A callable that will be invoked on the background
+  ///   thread, receiving the SelfPipe as an argument.
+  template <typename Fn>
+  Status Init(const std::shared_ptr<::arrow::internal::SelfPipe>& self_pipe,
+              Fn&& handler) {
+    self_pipe_ = self_pipe;
+    handle_signals_ = std::thread(std::forward<Fn>(handler), self_pipe_);
+    return Status::OK();
+  }
+
+  /// \brief Shut down the signal handler and join the background thread.
+  ///
+  /// The thread is woken with a plain payload rather than 
SelfPipe::Shutdown():
+  /// a signal handler may have been entered and preempted just before this
+  /// point, and writing to a pipe whose read end was closed raises SIGPIPE in
+  /// that handler, killing the process.
+  Status Shutdown() {
+    self_pipe_->Send(/*payload=*/0);
+    handle_signals_.join();
+    return Status::OK();
+  }
+
+  ~ServerSignalHandler() { ARROW_CHECK_OK(Shutdown()); }
+
+ private:
+  std::shared_ptr<::arrow::internal::SelfPipe> self_pipe_;
+  std::thread handle_signals_;
+};
+
+#if (ATOMIC_INT_LOCK_FREE != 2 || ATOMIC_POINTER_LOCK_FREE != 2)
+#  error "atomic ints and atomic pointers not always lock-free!"
+#endif
+
+/// \brief Manages signal-driven graceful shutdown for server transports.
+///
+/// Installs signal handlers for the given set of signals. When a signal is
+/// received, the registered shutdown callback is invoked. Uses a SelfPipe
+/// to safely bridge the signal handler (which runs in a restricted context)
+/// to a background thread that performs the actual shutdown.
+class ARROW_FLIGHT_EXPORT ServerSignalState {
+ public:
+  ServerSignalState() = default;
+
+  /// \brief Configure which signals should trigger shutdown.
+  ///
+  /// \param[in] sigs List of signal numbers (e.g. SIGINT, SIGTERM).
+  Status SetShutdownOnSignals(const std::vector<int>& sigs);
+  /// \brief Return the last signal that was received, or 0 if none.
+  int GotSignal() const;
+
+  /// \brief Run the server with signal-aware lifecycle management.
+  ///
+  /// Installs signal handlers, calls \p wait (which should block until the
+  /// server stops), and restores original signal handlers on return.
+  /// If a signal is received during \p wait, \p shutdown is called first.
+  ///
+  /// \param[in] wait A callable that blocks until the server stops.
+  /// \param[in] shutdown A callable invoked on signal receipt to stop the 
server.
+  /// starts. \param[in] shutdown_warning Logged if shutdown itself fails.
+  template <typename WaitFn, typename ShutdownFn>
+  Status Serve(WaitFn&& wait, ShutdownFn&& shutdown, const char* 
shutdown_warning) {
+    got_signal_ = 0;
+    old_signal_handlers_.clear();
+    // Everything the signal handler touches must be initialized before the
+    // instance is published: a signal arriving earlier would otherwise find an
+    // empty self-pipe (crash) or an empty shutdown callback, in which case
+    // WaitForSignals() consumes the wakeup and wait() blocks forever.
+    ARROW_ASSIGN_OR_RAISE(self_pipe_,
+                          
::arrow::internal::SelfPipe::Make(/*signal_safe=*/true));
+    shutdown_ = [shutdown = std::forward<ShutdownFn>(shutdown)]() mutable {
+      return shutdown(nullptr);
+    };
+    shutdown_warning_ = shutdown_warning;
+    running_instance_ = this;
+
+    Status status;
+    {
+      ServerSignalHandler signal_handler;
+      status = signal_handler.Init(self_pipe_, 
&ServerSignalState::WaitForSignals);
+      if (status.ok()) {
+        for (size_t i = 0; i < signals_.size(); ++i) {
+          int signum = signals_[i];
+          ::arrow::internal::SignalHandler 
new_handler(&ServerSignalState::HandleSignal),
+              old_handler;
+          auto old = ::arrow::internal::SetSignalHandler(signum, new_handler);
+          if (!old.ok()) {
+            status = old.status();
+            break;
+          }
+          old_signal_handlers_.push_back(std::move(old).ValueOrDie());
+        }
+      }
+      if (status.ok()) {
+        status = wait();
+      }
+      // Stop publishing this instance before the signal thread is joined: the
+      // destructor shuts the self-pipe down, and a signal handler writing to a
+      // closed pipe would kill the process with SIGPIPE.
+      running_instance_ = nullptr;
+      // The signal thread is joined by the destructor here, before the 
callback
+      // is cleared below: it may be executing it right now.
+    }
+
+    shutdown_ = nullptr;
+    shutdown_warning_ = nullptr;
+
+    // Restore the original handlers, whatever the outcome of wait() was.
+    Status restore_status;
+    for (size_t i = 0; i < old_signal_handlers_.size(); ++i) {
+      auto restored =
+          ::arrow::internal::SetSignalHandler(signals_[i], 
old_signal_handlers_[i]);
+      if (!restored.ok() && restore_status.ok()) {
+        restore_status = restored.status();
+      }
+    }
+    if (!status.ok()) {
+      return status;
+    }
+    return restore_status;
+  }
+
+  /// \brief Shut down the server through the given callback.
+  ///
+  /// Clears the running instance pointer, then invokes \p shutdown.
+  ///
+  /// \param[in] shutdown A callable that performs the transport-specific 
shutdown.
+  /// \param[in] deadline Optional deadline for the shutdown.
+  template <typename ShutdownFn>
+  Status Shutdown(ShutdownFn&& shutdown,
+                  const std::chrono::system_clock::time_point* deadline) {
+    running_instance_ = nullptr;
+    return shutdown(deadline);
+  }
+
+  /// \brief Wait for the server to stop without initiating shutdown.
+  ///
+  /// \param[in] wait A callable that blocks until the server stops.
+  template <typename WaitFn>
+  Status Wait(WaitFn&& wait) {
+    RETURN_NOT_OK(wait());
+    running_instance_ = nullptr;
+    return Status::OK();
+  }
+
+ private:
+  /// \brief Static entry point for the OS signal handler.
+  static void HandleSignal(int signum);
+
+  /// \brief Record the received signal and wake the background thread.
+  void DoHandleSignal(int signum);
+
+  /// \brief Background thread that blocks on the SelfPipe, then invokes 
shutdown.
+  static void WaitForSignals(std::shared_ptr<::arrow::internal::SelfPipe> 
self_pipe);
+
+  // Signal handlers (on Windows) and the shutdown handler (other platforms)
+  // are executed in a separate thread, so getting the current thread instance
+  // wouldn't make sense.  This means only a single instance can receive 
signals.
+  static std::atomic<ServerSignalState*> running_instance_;
+
+  // We'll use the self-pipe trick to notify a thread from the signal
+  // handler. The thread will then shut down the server.
+  std::shared_ptr<::arrow::internal::SelfPipe> self_pipe_;
+
+  // Signal handling
+  std::vector<int> signals_;
+  std::vector<::arrow::internal::SignalHandler> old_signal_handlers_;
+  std::atomic<int> got_signal_{0};
+  std::function<Status()> shutdown_;
+  const char* shutdown_warning_ = nullptr;
+};
+
+}  // namespace arrow::flight::internal
diff --git a/cpp/src/arrow/flight/types.cc b/cpp/src/arrow/flight/types.cc
index 495425c4aeb..c4b81184cc6 100644
--- a/cpp/src/arrow/flight/types.cc
+++ b/cpp/src/arrow/flight/types.cc
@@ -840,6 +840,18 @@ arrow::Status Location::Deserialize(std::string_view 
serialized, Location* out)
   return DeserializeProtoString<pb::Location, Location>("Location", 
serialized, out);
 }
 
+arrow::Result<arrow::util::Uri> Location::uri() const {
+  return arrow::util::Uri::FromString(ToString());
+}
+
+int Location::port() const {
+  auto maybe_uri = uri();
+  if (!maybe_uri.ok()) {
+    return -1;
+  }
+  return maybe_uri.ValueUnsafe().port();
+}
+
 arrow::Status FlightEndpoint::SerializeToString(std::string* out) const {
   return SerializeToProtoString<pb::FlightEndpoint>("FlightEndpoint", *this, 
out);
 }
diff --git a/cpp/src/arrow/flight/types.h b/cpp/src/arrow/flight/types.h
index fdd1881a637..dd18c0e0786 100644
--- a/cpp/src/arrow/flight/types.h
+++ b/cpp/src/arrow/flight/types.h
@@ -38,6 +38,7 @@
 #include "arrow/ipc/writer.h"
 #include "arrow/result.h"
 #include "arrow/status.h"
+#include "arrow/util/uri.h"
 
 namespace arrow {
 
@@ -50,10 +51,6 @@ class DictionaryMemo;
 struct ReadStats;
 }  // namespace ipc
 
-namespace util {
-class Uri;
-}  // namespace util
-
 namespace flight {
 
 ARROW_FLIGHT_EXPORT
@@ -564,6 +561,16 @@ struct ARROW_FLIGHT_EXPORT Location : public 
internal::BaseType<Location> {
   /// Use `Deserialize(serialized)` if you want a Result-returning version.
   static arrow::Status Deserialize(std::string_view serialized, Location* out);
 
+  /// \brief Get the URI representation of this location.
+  ///
+  /// \return Arrow result with the URI.
+  arrow::Result<arrow::util::Uri> uri() const;
+
+  /// \brief Get the port of this location.
+  ///
+  /// \return The port number. -1 if the port is not available.
+  int port() const;
+
  private:
   friend class FlightClient;
   friend class FlightServerBase;

Reply via email to