|
| 1 | +// Licensed to the Apache Software Foundation (ASF) under one |
| 2 | +// or more contributor license agreements. See the NOTICE file |
| 3 | +// distributed with this work for additional information |
| 4 | +// regarding copyright ownership. The ASF licenses this file |
| 5 | +// to you under the Apache License, Version 2.0 (the |
| 6 | +// "License"); you may not use this file except in compliance |
| 7 | +// with the License. You may obtain a copy of the License at |
| 8 | +// |
| 9 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +// |
| 11 | +// Unless required by applicable law or agreed to in writing, |
| 12 | +// software distributed under the License is distributed on an |
| 13 | +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 14 | +// KIND, either express or implied. See the License for the |
| 15 | +// specific language governing permissions and limitations |
| 16 | +// under the License. |
| 17 | + |
| 18 | +use std::collections::HashMap; |
| 19 | +use std::net::SocketAddr; |
| 20 | + |
| 21 | +use async_trait::async_trait; |
| 22 | +use datafusion::common::{DataFusionError, Result as DataFusionResult}; |
| 23 | +use datafusion::execution::{SessionState, SessionStateBuilder}; |
| 24 | +use datafusion_distributed::{Worker, WorkerQueryContext, WorkerSessionBuilder}; |
| 25 | +use datafusion_python_util::wait_for_future; |
| 26 | +use pyo3::Borrowed; |
| 27 | +use pyo3::exceptions::{PyRuntimeError, PyTypeError}; |
| 28 | +use pyo3::prelude::*; |
| 29 | +use tonic::transport::Server; |
| 30 | + |
| 31 | +use crate::context::PySessionContext; |
| 32 | +use crate::errors::{PyDataFusionError, PyDataFusionResult}; |
| 33 | + |
| 34 | +#[pyclass( |
| 35 | + from_py_object, |
| 36 | + frozen, |
| 37 | + name = "Worker", |
| 38 | + module = "datafusion", |
| 39 | + subclass |
| 40 | +)] |
| 41 | +#[derive(Clone)] |
| 42 | +pub struct PyWorker { |
| 43 | + worker: Worker, |
| 44 | +} |
| 45 | + |
| 46 | +#[pymethods] |
| 47 | +impl PyWorker { |
| 48 | + #[new] |
| 49 | + fn new() -> Self { |
| 50 | + Self { |
| 51 | + worker: Worker::default(), |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + #[staticmethod] |
| 56 | + fn from_session_builder(session_builder: PyWorkerSessionBuilder) -> Self { |
| 57 | + Self { |
| 58 | + worker: Worker::from_session_builder(session_builder), |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + fn with_version(&self, version: String) -> Self { |
| 63 | + Self { |
| 64 | + worker: self.worker.clone().with_version(version), |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + fn with_max_message_size(&self, size: usize) -> Self { |
| 69 | + Self { |
| 70 | + worker: self.worker.clone().with_max_message_size(size), |
| 71 | + } |
| 72 | + } |
| 73 | + |
| 74 | + #[pyo3(signature = (host = "127.0.0.1", port = 50051))] |
| 75 | + fn serve(&self, py: Python<'_>, host: &str, port: u16) -> PyDataFusionResult<()> { |
| 76 | + let addr = parse_socket_addr(host, port)?; |
| 77 | + let worker = self.worker.clone(); |
| 78 | + wait_for_future(py, serve_worker(worker, addr))?.map_err(PyDataFusionError::from) |
| 79 | + } |
| 80 | + |
| 81 | + #[pyo3(signature = (host = "127.0.0.1", port = 50051))] |
| 82 | + fn serve_async<'py>( |
| 83 | + &self, |
| 84 | + py: Python<'py>, |
| 85 | + host: &str, |
| 86 | + port: u16, |
| 87 | + ) -> PyResult<Bound<'py, PyAny>> { |
| 88 | + let addr = parse_socket_addr(host, port)?; |
| 89 | + let worker = self.worker.clone(); |
| 90 | + pyo3_async_runtimes::tokio::future_into_py(py, async move { |
| 91 | + serve_worker(worker, addr) |
| 92 | + .await |
| 93 | + .map_err(PyDataFusionError::from)?; |
| 94 | + Ok(()) |
| 95 | + }) |
| 96 | + } |
| 97 | +} |
| 98 | + |
| 99 | +#[pyclass(name = "WorkerQueryContext", module = "datafusion", subclass)] |
| 100 | +pub struct PyWorkerQueryContext { |
| 101 | + builder: Option<SessionStateBuilder>, |
| 102 | + headers: HashMap<String, String>, |
| 103 | +} |
| 104 | + |
| 105 | +impl PyWorkerQueryContext { |
| 106 | + fn new(ctx: WorkerQueryContext) -> Self { |
| 107 | + let headers = ctx |
| 108 | + .headers |
| 109 | + .iter() |
| 110 | + .map(|(name, value)| { |
| 111 | + ( |
| 112 | + name.as_str().to_owned(), |
| 113 | + value.to_str().unwrap_or_default().to_owned(), |
| 114 | + ) |
| 115 | + }) |
| 116 | + .collect(); |
| 117 | + |
| 118 | + Self { |
| 119 | + builder: Some(ctx.builder), |
| 120 | + headers, |
| 121 | + } |
| 122 | + } |
| 123 | +} |
| 124 | + |
| 125 | +#[pymethods] |
| 126 | +impl PyWorkerQueryContext { |
| 127 | + fn session_context(mut slf: PyRefMut<'_, Self>) -> PyResult<PySessionContext> { |
| 128 | + let builder = slf.builder.take().ok_or_else(|| { |
| 129 | + PyRuntimeError::new_err("WorkerQueryContext.session_context() can only be called once") |
| 130 | + })?; |
| 131 | + Ok(PySessionContext::from_session_state(builder.build())) |
| 132 | + } |
| 133 | + |
| 134 | + #[getter] |
| 135 | + fn headers(&self) -> HashMap<String, String> { |
| 136 | + self.headers.clone() |
| 137 | + } |
| 138 | +} |
| 139 | + |
| 140 | +pub(crate) struct PyWorkerSessionBuilder { |
| 141 | + callback: Py<PyAny>, |
| 142 | +} |
| 143 | + |
| 144 | +impl FromPyObject<'_, '_> for PyWorkerSessionBuilder { |
| 145 | + type Error = PyErr; |
| 146 | + |
| 147 | + fn extract(obj: Borrowed<'_, '_, PyAny>) -> Result<Self, Self::Error> { |
| 148 | + if !obj.is_callable() { |
| 149 | + return Err(PyTypeError::new_err( |
| 150 | + "Expected worker session builder to be callable", |
| 151 | + )); |
| 152 | + } |
| 153 | + |
| 154 | + Ok(Self { |
| 155 | + callback: obj.to_owned().unbind(), |
| 156 | + }) |
| 157 | + } |
| 158 | +} |
| 159 | + |
| 160 | +#[async_trait] |
| 161 | +impl WorkerSessionBuilder for PyWorkerSessionBuilder { |
| 162 | + async fn build_session_state( |
| 163 | + &self, |
| 164 | + ctx: WorkerQueryContext, |
| 165 | + ) -> Result<SessionState, DataFusionError> { |
| 166 | + Python::attach(|py| -> PyResult<SessionState> { |
| 167 | + let ctx = Py::new(py, PyWorkerQueryContext::new(ctx))?; |
| 168 | + let result = self.callback.call1(py, (ctx,))?; |
| 169 | + let session_context = extract_session_context(result.bind(py))?; |
| 170 | + Ok(session_context.ctx.state()) |
| 171 | + }) |
| 172 | + .map_err(|error| DataFusionError::External(Box::new(error))) |
| 173 | + } |
| 174 | +} |
| 175 | + |
| 176 | +fn extract_session_context(obj: &Bound<'_, PyAny>) -> PyResult<PySessionContext> { |
| 177 | + if let Ok(session_context) = obj.extract::<PySessionContext>() { |
| 178 | + return Ok(session_context); |
| 179 | + } |
| 180 | + |
| 181 | + if let Ok(ctx_attr) = obj.getattr("ctx") |
| 182 | + && let Ok(session_context) = ctx_attr.extract::<PySessionContext>() |
| 183 | + { |
| 184 | + return Ok(session_context); |
| 185 | + } |
| 186 | + |
| 187 | + Err(PyTypeError::new_err( |
| 188 | + "WorkerSessionBuilder.build_session_state() must return a datafusion.SessionContext", |
| 189 | + )) |
| 190 | +} |
| 191 | + |
| 192 | +fn parse_socket_addr(host: &str, port: u16) -> PyDataFusionResult<SocketAddr> { |
| 193 | + format!("{host}:{port}").parse().map_err(|error| { |
| 194 | + PyDataFusionError::Common(format!( |
| 195 | + "invalid worker bind address {host}:{port}: {error}" |
| 196 | + )) |
| 197 | + }) |
| 198 | +} |
| 199 | + |
| 200 | +async fn serve_worker(worker: Worker, addr: SocketAddr) -> DataFusionResult<()> { |
| 201 | + Server::builder() |
| 202 | + .add_service(worker.into_worker_server()) |
| 203 | + .serve(addr) |
| 204 | + .await |
| 205 | + .map_err(|error| DataFusionError::External(Box::new(error))) |
| 206 | +} |
0 commit comments