sqlload_python_host/host/
models.rs1use std::path::{Path, PathBuf};
2use std::time::Duration;
3
4use arrow_array::RecordBatch;
5use arrow_schema::SchemaRef;
6use pyo3::types::PyAnyMethods;
7use pyo3::{Py, PyAny, PyResult, Python};
8use sqlload::python_sources::errors::ReadError;
9use sqlload::python_sources::models::{PythonSource, TableRead, TransformCall};
10use sqlload::python_sources::types::{BatchStream, PythonHost, Streamed};
11
12use crate::crossing::errors::CrossError;
13use crate::crossing::models::{Polled, TableBatches};
14use crate::host::_helpers::api_version::api_version_problem;
15use crate::host::constants::API_HOST_MODULE;
16use crate::host::main::error_text::error_text;
17use crate::host::main::read_error::read_error;
18use crate::host::main::table_stream::table_stream;
19use crate::host::main::transform_stream::transform_stream;
20
21#[derive(Debug, Clone, PartialEq, Eq)]
23#[non_exhaustive]
24pub struct ModuleHost {
25 pub runtime: String,
27}
28
29impl PythonHost for ModuleHost {
30 fn discover(&self, root: &Path, python_paths: &[PathBuf]) -> Result<Vec<PythonSource>, String> {
31 if let Some(problem) = api_version_problem() {
32 return Err(problem);
33 }
34 let paths: Vec<String> = python_paths
35 .iter()
36 .map(|path| path.to_string_lossy().into_owned())
37 .collect();
38 let text = Python::attach(|py| -> PyResult<String> {
39 py.import(self.runtime.as_str())?
40 .call_method1("discover", (root.to_string_lossy().into_owned(), paths))?
41 .extract()
42 })
43 .map_err(|error| error_text(&error))?;
44 serde_json::from_str(&text)
45 .map_err(|error| format!("cannot read the Python sources found: {error}"))
46 }
47
48 fn read_table(&self, request: &TableRead) -> Result<Box<dyn BatchStream>, String> {
49 let text = serde_json::to_string(request).map_err(|error| error.to_string())?;
50 Python::attach(|py| -> PyResult<Result<Box<dyn BatchStream>, String>> {
51 let runtime = py.import(self.runtime.as_str())?;
52 let iterator = runtime.call_method1("start_table", (text,))?;
53 let snapshot = match request.logged {
54 true => Some(
55 py.import("functools")?
56 .getattr("partial")?
57 .call1((runtime.getattr("current_state")?, request.table.as_str()))?,
58 ),
59 false => None,
60 };
61 Ok(table_stream(&iterator, snapshot.as_ref(), request))
62 })
63 .map_err(|error| error_text(&error))?
64 }
65
66 fn table_state(&self, table: &str) -> Result<Option<String>, String> {
67 Python::attach(|py| -> PyResult<Option<String>> {
68 py.import(self.runtime.as_str())?
69 .call_method1("table_state", (table,))?
70 .extract()
71 })
72 .map_err(|error| error_text(&error))
73 }
74
75 fn transform_version(&self, name: &str) -> Result<String, String> {
76 let checked = Python::attach(|py| -> PyResult<(Option<String>, Option<String>)> {
77 py.import(API_HOST_MODULE)?
78 .call_method1("transform_version", (name,))?
79 .extract()
80 })
81 .map_err(|error| error_text(&error))?;
82 match checked {
83 (Some(version), _) => Ok(version),
84 (None, problem) => Err(problem.unwrap_or_else(|| format!("{name} cannot run"))),
85 }
86 }
87
88 fn transform(
89 &self,
90 call: &TransformCall,
91 rows: Vec<RecordBatch>,
92 schema: SchemaRef,
93 ) -> Result<Box<dyn BatchStream>, String> {
94 transform_stream(call, rows, schema)
95 }
96
97 fn rename(&self, name: &str, columns: Option<&str>, context: &str) -> Result<String, String> {
98 let called = Python::attach(|py| -> PyResult<(Option<String>, Option<String>)> {
99 py.import(self.runtime.as_str())?
100 .call_method1("rename", (name, columns, context))?
101 .extract()
102 })
103 .map_err(|error| error_text(&error))?;
104 match called {
105 (Some(names), _) => Ok(names),
106 (None, problem) => Err(problem.unwrap_or_else(|| format!("{name} cannot run"))),
107 }
108 }
109
110 fn finish(&self) {
111 let closed = Python::attach(|py| -> PyResult<()> {
112 py.import(self.runtime.as_str())?
113 .call_method0("finish_run")?;
114 py.import(API_HOST_MODULE)?.call_method0("finish")?;
115 Ok(())
116 });
117 if let Err(error) = closed {
118 tracing::warn!(error = %error_text(&error), "cannot close the Python sources' clients");
119 }
120 }
121}
122
123#[derive(Debug)]
125pub struct PythonBatches(pub(crate) TableBatches);
126
127impl BatchStream for PythonBatches {
128 fn next_batch(&mut self) -> Option<Result<Streamed, ReadError>> {
129 loop {
130 match self.0.poll(Duration::from_secs(3600)) {
131 Polled::Batch(batch) => return Some(Ok(Streamed::Batch(batch))),
132 Polled::State(state) => return Some(Ok(Streamed::State(state))),
133 Polled::Failed(CrossError::Python(error)) => return Some(Err(read_error(&error))),
134 Polled::Failed(CrossError::Data(reason)) => return Some(Err(reason.into())),
135 Polled::Failed(CrossError::Http(error)) => return Some(Err(error)),
136 Polled::Pending => {}
137 Polled::Finished => return None,
138 }
139 }
140 }
141}
142
143#[derive(Debug)]
145pub struct TransformBatches {
146 pub(crate) batches: PythonBatches,
147 pub(crate) returned: Py<PyAny>,
148}
149
150impl BatchStream for TransformBatches {
151 fn next_batch(&mut self) -> Option<Result<Streamed, ReadError>> {
152 self.batches.next_batch()
153 }
154
155 fn crossed_dicts(&self) -> bool {
156 Python::attach(|py| {
157 self.returned
158 .bind(py)
159 .getattr("dicts")
160 .and_then(|dicts| dicts.extract::<bool>())
161 .is_ok_and(|dicts| dicts)
162 })
163 }
164}