davisp commented on code in PR #20326: URL: https://github.com/apache/datafusion/pull/20326#discussion_r2835188205
########## datafusion/ffi/src/table_provider_factory.rs: ########## @@ -0,0 +1,492 @@ +// 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 std::{ffi::c_void, sync::Arc}; + +use abi_stable::{ + StableAbi, + std_types::{RResult, RString, RVec}, +}; +use async_ffi::{FfiFuture, FutureExt}; +use async_trait::async_trait; +use datafusion_catalog::{Session, TableProvider, TableProviderFactory}; +use datafusion_common::TableReference; +use datafusion_common::error::{DataFusionError, Result}; +use datafusion_execution::TaskContext; +use datafusion_expr::CreateExternalTable; +use datafusion_proto::logical_plan::from_proto::{parse_expr, parse_sorts}; +use datafusion_proto::logical_plan::to_proto::{serialize_expr, serialize_sorts}; +use datafusion_proto::logical_plan::{ + DefaultLogicalExtensionCodec, LogicalExtensionCodec, +}; +use datafusion_proto::protobuf::{CreateExternalTableNode, SortExprNodeCollection}; +use prost::Message; +use std::collections::HashMap; +use tokio::runtime::Handle; + +use crate::execution::FFI_TaskContextProvider; +use crate::proto::logical_extension_codec::FFI_LogicalExtensionCodec; +use crate::session::{FFI_SessionRef, ForeignSession}; +use crate::table_provider::{FFI_TableProvider, ForeignTableProvider}; +use crate::{df_result, rresult_return}; + +/// A stable struct for sharing [`TableProviderFactory`] across FFI boundaries. +/// +/// Similar to [`FFI_TableProvider`], this struct uses the FFI-safe pattern where: +/// - The `FFI_*` struct exposes stable function pointers +/// - Private data is stored as an opaque pointer +/// - The `Foreign*` wrapper is used by consumers on the other side of the FFI boundary +/// +/// [`FFI_TableProvider`]: crate::table_provider::FFI_TableProvider +#[repr(C)] +#[derive(Debug, StableAbi)] +pub struct FFI_TableProviderFactory { + /// Create a TableProvider with the given command. + /// + /// # Arguments + /// + /// * `factory` - the table provider factory + /// * `session_config` - session configuration + /// * `cmd_serialized` - a [`CreateExternalTableNode`] protobuf message serialized into bytes + /// to pass across the FFI boundary. + create: unsafe extern "C" fn( + factory: &Self, + session: FFI_SessionRef, + cmd_serialized: RVec<u8>, + ) -> FfiFuture<RResult<FFI_TableProvider, RString>>, + + pub logical_codec: FFI_LogicalExtensionCodec, + + /// Used to create a clone of the factory. This should only need to be called + /// by the receiver of the factory. + pub clone: unsafe extern "C" fn(factory: &Self) -> Self, + + /// Release the memory of the private data when it is no longer being used. + pub release: unsafe extern "C" fn(factory: &mut Self), + + /// Return the major DataFusion version number of this factory. + pub version: unsafe extern "C" fn() -> u64, + + /// Internal data. This is only to be accessed by the provider of the factory. + /// A [`ForeignTableProviderFactory`] should never attempt to access this data. + pub private_data: *mut c_void, + + /// Utility to identify when FFI objects are accessed locally through + /// the foreign interface. See [`crate::get_library_marker_id`] and + /// the crate's `README.md` for more information. + pub library_marker_id: extern "C" fn() -> usize, +} + +unsafe impl Send for FFI_TableProviderFactory {} +unsafe impl Sync for FFI_TableProviderFactory {} + +struct FactoryPrivateData { + factory: Arc<dyn TableProviderFactory + Send>, + runtime: Option<Handle>, +} + +impl FFI_TableProviderFactory { + /// Creates a new [`FFI_TableProvider`]. + pub fn new( + factory: Arc<dyn TableProviderFactory + Send>, + runtime: Option<Handle>, + task_ctx_provider: impl Into<FFI_TaskContextProvider>, + logical_codec: Option<Arc<dyn LogicalExtensionCodec>>, + ) -> Self { + let task_ctx_provider = task_ctx_provider.into(); + let logical_codec = + logical_codec.unwrap_or_else(|| Arc::new(DefaultLogicalExtensionCodec {})); + let logical_codec = FFI_LogicalExtensionCodec::new( + logical_codec, + runtime.clone(), + task_ctx_provider.clone(), + ); + Self::new_with_ffi_codec(factory, runtime, logical_codec) + } + + pub fn new_with_ffi_codec( + factory: Arc<dyn TableProviderFactory + Send>, + runtime: Option<Handle>, + logical_codec: FFI_LogicalExtensionCodec, + ) -> Self { + let private_data = Box::new(FactoryPrivateData { factory, runtime }); + + Self { + create: create_fn_wrapper, + logical_codec, + clone: clone_fn_wrapper, + release: release_fn_wrapper, + version: super::version, + private_data: Box::into_raw(private_data) as *mut c_void, + library_marker_id: crate::get_library_marker_id, + } + } + + fn inner(&self) -> &Arc<dyn TableProviderFactory + Send> { + let private_data = self.private_data as *const FactoryPrivateData; + unsafe { &(*private_data).factory } + } + + fn runtime(&self) -> &Option<Handle> { + let private_data = self.private_data as *const FactoryPrivateData; + unsafe { &(*private_data).runtime } + } +} + +impl Clone for FFI_TableProviderFactory { + fn clone(&self) -> Self { + unsafe { (self.clone)(self) } + } +} + +impl Drop for FFI_TableProviderFactory { + fn drop(&mut self) { + unsafe { (self.release)(self) } + } +} + +unsafe extern "C" fn create_fn_wrapper( + factory: &FFI_TableProviderFactory, + session: FFI_SessionRef, + cmd_serialized: RVec<u8>, +) -> FfiFuture<RResult<FFI_TableProvider, RString>> { + let task_ctx: Result<Arc<TaskContext>, DataFusionError> = + (&factory.logical_codec.task_ctx_provider).try_into(); + let runtime = factory.runtime().clone(); + let logical_codec: Arc<dyn LogicalExtensionCodec> = (&factory.logical_codec).into(); + let ffi_logical_codec = factory.logical_codec.clone(); + let internal_factory = Arc::clone(factory.inner()); + + async move { + let mut foreign_session = None; + let session = rresult_return!( + session + .as_local() + .map(Ok::<&(dyn Session + Send + Sync), DataFusionError>) + .unwrap_or_else(|| { + foreign_session = Some(ForeignSession::try_from(&session)?); + Ok(foreign_session.as_ref().unwrap()) + }) + ); + + let task_ctx = rresult_return!(task_ctx); + + let proto_cmd = + rresult_return!(CreateExternalTableNode::decode(cmd_serialized.as_ref())); + + // Deserialize CreateExternalTable from protobuf + let pb_schema = rresult_return!(proto_cmd.schema.ok_or_else(|| { + DataFusionError::Internal( + "CreateExternalTableNode was missing required field schema".to_string(), + ) + })); + + let constraints = rresult_return!(proto_cmd.constraints.ok_or_else(|| { + DataFusionError::Internal( + "CreateExternalTableNode was missing required field constraints" + .to_string(), + ) + })); + + let definition = if !proto_cmd.definition.is_empty() { + Some(proto_cmd.definition) + } else { + None + }; + + let mut order_exprs = Vec::with_capacity(proto_cmd.order_exprs.len()); + for expr in &proto_cmd.order_exprs { + let sorts = rresult_return!(parse_sorts( + &expr.sort_expr_nodes, + task_ctx.as_ref(), + logical_codec.as_ref(), + )); + order_exprs.push(sorts); + } + + let mut column_defaults = HashMap::with_capacity(proto_cmd.column_defaults.len()); + for (col_name, expr) in &proto_cmd.column_defaults { + let expr = rresult_return!(parse_expr( + expr, + task_ctx.as_ref(), + logical_codec.as_ref() + )); + column_defaults.insert(col_name.clone(), expr); + } + + let table_ref = rresult_return!(proto_cmd.name.as_ref().ok_or_else(|| { + DataFusionError::Internal( + "CreateExternalTableNode was missing required field name".to_string(), + ) + })); + + let name: TableReference = rresult_return!(table_ref.clone().try_into()); + + let cmd = CreateExternalTable { + schema: rresult_return!(pb_schema.try_into()), + name, + location: proto_cmd.location, + file_type: proto_cmd.file_type, + table_partition_cols: proto_cmd.table_partition_cols, + order_exprs, + if_not_exists: proto_cmd.if_not_exists, + or_replace: proto_cmd.or_replace, + temporary: proto_cmd.temporary, + definition, + unbounded: proto_cmd.unbounded, + options: proto_cmd.options, + constraints: constraints.into(), + column_defaults, + }; + + let provider = rresult_return!(internal_factory.create(session, &cmd).await); + + RResult::ROk(FFI_TableProvider::new_with_ffi_codec( + provider, + true, + runtime.clone(), + ffi_logical_codec, + )) + } + .into_ffi() +} + +unsafe extern "C" fn clone_fn_wrapper( + factory: &FFI_TableProviderFactory, +) -> FFI_TableProviderFactory { + let runtime = factory.runtime().clone(); + let old_factory = Arc::clone(factory.inner()); + + let private_data = Box::into_raw(Box::new(FactoryPrivateData { + factory: old_factory, + runtime, + })) as *mut c_void; + + FFI_TableProviderFactory { + create: create_fn_wrapper, + logical_codec: factory.logical_codec.clone(), + clone: clone_fn_wrapper, + release: release_fn_wrapper, + version: super::version, + private_data, + library_marker_id: crate::get_library_marker_id, + } +} + +unsafe extern "C" fn release_fn_wrapper(factory: &mut FFI_TableProviderFactory) { + unsafe { + debug_assert!(!factory.private_data.is_null()); + let private_data = Box::from_raw(factory.private_data as *mut FactoryPrivateData); + drop(private_data); + factory.private_data = std::ptr::null_mut(); + } +} + +/// This wrapper struct exists on the receiver side of the FFI interface, so it has +/// no guarantees about being able to access the data in `private_data`. Any functions +/// defined on this struct must only use the stable functions provided in +/// FFI_TableProviderFactory to interact with the foreign table provider factory. +#[derive(Debug)] +pub struct ForeignTableProviderFactory(pub FFI_TableProviderFactory); + +impl From<&FFI_TableProviderFactory> for Arc<dyn TableProviderFactory> { + fn from(factory: &FFI_TableProviderFactory) -> Self { + if (factory.library_marker_id)() == crate::get_library_marker_id() { + Arc::clone(factory.inner()) as Arc<dyn TableProviderFactory> + } else { + Arc::new(ForeignTableProviderFactory(factory.clone())) + } + } +} + +unsafe impl Send for ForeignTableProviderFactory {} +unsafe impl Sync for ForeignTableProviderFactory {} + +#[async_trait] +impl TableProviderFactory for ForeignTableProviderFactory { + async fn create( + &self, + session: &dyn Session, + cmd: &CreateExternalTable, + ) -> Result<Arc<dyn TableProvider>> { + let session = FFI_SessionRef::new(session, None, self.0.logical_codec.clone()); + + let codec: Arc<dyn LogicalExtensionCodec> = (&self.0.logical_codec).into(); + + // Serialize CreateExternalTable to protobuf + let mut converted_order_exprs: Vec<SortExprNodeCollection> = vec![]; + for order in &cmd.order_exprs { + let temp = SortExprNodeCollection { + sort_expr_nodes: serialize_sorts(order, codec.as_ref())?, + }; + converted_order_exprs.push(temp); + } + + let mut converted_column_defaults = + HashMap::with_capacity(cmd.column_defaults.len()); + for (col_name, expr) in &cmd.column_defaults { + converted_column_defaults + .insert(col_name.clone(), serialize_expr(expr, codec.as_ref())?); + } + + let proto_cmd = CreateExternalTableNode { + name: Some(cmd.name.clone().into()), + location: cmd.location.clone(), + file_type: cmd.file_type.clone(), + schema: Some(cmd.schema.as_ref().try_into()?), + table_partition_cols: cmd.table_partition_cols.clone(), + if_not_exists: cmd.if_not_exists, + or_replace: cmd.or_replace, + temporary: cmd.temporary, + order_exprs: converted_order_exprs, + definition: cmd.definition.clone().unwrap_or_default(), + unbounded: cmd.unbounded, + options: cmd.options.clone(), + constraints: Some(cmd.constraints.clone().into()), + column_defaults: converted_column_defaults, + }; + Review Comment: Also fixed by using the builtin `AsLogicalPlan` conversions. Fixed [here](https://github.com/apache/datafusion/pull/20326/changes/1a6bfa4a0812aff88611780fa644b937ab12a9e5). -- 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. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
