sqlload_python_host/crossing/
models.rs1use sqlload::load_naming::models::Naming;
2use sqlload::row_batches::models::{Flatten, ProjectionRules};
3use std::sync::atomic::{AtomicU64, Ordering};
4use std::sync::mpsc::{Receiver, RecvTimeoutError, Sender, SyncSender};
5use std::sync::{Arc, Condvar, Mutex};
6use std::time::Duration;
7
8use arrow_array::RecordBatch;
9use arrow_array::ffi_stream::RecordBatchStreamReader;
10use arrow_schema::Schema;
11use pyo3::pybacked::PyBackedBytes;
12use sqlload::row_batches::main::merge_schema::merge_schema;
13use sqlload::row_batches::models::{JsonRead, RowColumns};
14
15use crate::crossing::errors::CrossError;
16
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19pub enum DictCrossing {
20 Walk,
22 Serialise,
24}
25
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28pub struct CrossingOptions {
29 pub batch_rows: usize,
31 pub max_queued: usize,
33 pub dict_crossing: DictCrossing,
34 pub parse_threads: usize,
36 pub panic_at: Option<PanicSite>,
38 pub max_queued_bytes: usize,
40}
41
42#[derive(Debug, Clone, Default)]
44pub struct ReadContext {
45 pub table: String,
47 pub flatten: Flatten,
48 pub connections: serde_json::Map<String, serde_json::Value>,
49 pub cursor_column: Option<String>,
51 pub masked: Vec<String>,
53 pub arrays: Vec<String>,
55 pub naming: (Naming, Option<usize>),
57 pub zone: Option<chrono_tz::Tz>,
59 pub source_part: Option<u64>,
61}
62
63impl ReadContext {
64 pub fn rules(&self) -> ProjectionRules<'_> {
66 ProjectionRules {
67 cursor_column: self.cursor_column.as_deref(),
68 flatten: Some(&self.flatten),
69 masked: &self.masked,
70 naming: self.naming,
71 }
72 }
73}
74
75#[derive(Debug, Clone, Copy, PartialEq, Eq)]
77pub enum PanicSite {
78 Producer,
80 Parser,
82}
83
84#[derive(Debug)]
86pub(crate) enum Parsed {
87 Batch(RecordBatch),
88 State(String),
90 Failed(CrossError),
91 Done,
92}
93
94#[derive(Debug)]
96pub(crate) struct ParseJob {
97 pub(crate) crossed: Crossed,
98 pub(crate) sender: SyncSender<Parsed>,
99}
100
101#[derive(Debug, Clone)]
103pub(crate) struct Dispatch {
104 pub(crate) order: SyncSender<Option<(Receiver<Parsed>, Option<String>)>>,
106 pub(crate) jobs: Sender<ParseJob>,
107 pub(crate) stats: Arc<CrossingStats>,
109 pub(crate) flatten: Arc<Flatten>,
111}
112
113#[derive(Debug)]
115pub(crate) enum Crossed {
116 Columns(RowColumns),
117 Json {
118 bytes: PyBackedBytes,
119 read: JsonRead,
120 },
121 ArrowStream(RecordBatchStreamReader),
122 ArrowBatch(RecordBatch),
123 Http(String),
125 Checkpoint,
127 Failed(CrossError),
128}
129
130impl Crossed {
131 pub(crate) fn queued_bytes(&self) -> usize {
133 match self {
134 Self::Columns(columns) => columns.approximate_bytes(),
135 Self::Json { bytes, .. } => bytes.len(),
136 Self::ArrowBatch(batch) => batch.get_array_memory_size(),
137 Self::ArrowStream(_) | Self::Http(_) | Self::Checkpoint | Self::Failed(_) => 0,
138 }
139 }
140}
141
142#[derive(Debug, Default)]
144pub(crate) struct ByteBudget {
145 used: Mutex<usize>,
146 freed: Condvar,
147 limit: usize,
148}
149
150impl ByteBudget {
151 pub(crate) fn new(limit: usize) -> Self {
152 Self {
153 used: Mutex::new(0),
154 freed: Condvar::new(),
155 limit,
156 }
157 }
158
159 pub(crate) fn acquire(&self, bytes: usize) {
161 let Ok(mut used) = self.used.lock() else {
162 return;
163 };
164 while *used > 0 && *used + bytes > self.limit {
165 used = match self.freed.wait(used) {
166 Ok(used) => used,
167 Err(_) => return,
168 };
169 }
170 *used += bytes;
171 }
172
173 pub(crate) fn release(&self, bytes: usize) {
175 if let Ok(mut used) = self.used.lock() {
176 *used = used.saturating_sub(bytes);
177 self.freed.notify_all();
178 }
179 }
180}
181
182#[derive(Debug, Default)]
184pub struct CrossingStats {
185 pub(crate) budget: ByteBudget,
186 pub(crate) rows: AtomicU64,
187 pub(crate) batches: AtomicU64,
188 pub(crate) gil_nanos: AtomicU64,
190 pub(crate) parse_nanos: AtomicU64,
192}
193
194impl CrossingStats {
195 pub fn snapshot(&self) -> StatsSnapshot {
197 StatsSnapshot {
198 rows: self.rows.load(Ordering::Relaxed),
199 batches: self.batches.load(Ordering::Relaxed),
200 gil_seconds: self.gil_nanos.load(Ordering::Relaxed) as f64 / 1e9,
201 parse_seconds: self.parse_nanos.load(Ordering::Relaxed) as f64 / 1e9,
202 }
203 }
204
205 pub(crate) fn add(counter: &AtomicU64, elapsed: Duration) {
206 counter.fetch_add(
207 u64::try_from(elapsed.as_nanos()).unwrap_or(u64::MAX),
208 Ordering::Relaxed,
209 );
210 }
211}
212
213#[derive(Debug, Clone, Copy, PartialEq)]
215pub struct StatsSnapshot {
216 pub rows: u64,
217 pub batches: u64,
218 pub gil_seconds: f64,
220 pub parse_seconds: f64,
222}
223
224#[derive(Debug)]
226pub enum Polled {
227 Batch(RecordBatch),
228 State(String),
230 Failed(CrossError),
231 Pending,
233 Finished,
234}
235
236#[derive(Debug)]
238pub struct TableBatches {
239 pub(crate) receiver: Receiver<Parsed>,
240 pub(crate) schema: Schema,
241 pub(crate) stats: Arc<CrossingStats>,
242 pub(crate) finished: bool,
244}
245
246impl TableBatches {
247 pub fn poll(&mut self, timeout: Duration) -> Polled {
249 if self.finished {
250 return Polled::Finished;
251 }
252 match self.receiver.recv_timeout(timeout) {
253 Ok(Parsed::Batch(batch)) => {
254 self.schema = merge_schema(&self.schema, &batch.schema());
255 Polled::Batch(batch)
256 }
257 Ok(Parsed::State(state)) => Polled::State(state),
258 Ok(Parsed::Failed(error)) => {
259 self.finished = true;
260 Polled::Failed(error)
261 }
262 Ok(Parsed::Done) => {
263 self.finished = true;
264 Polled::Finished
265 }
266 Err(RecvTimeoutError::Timeout) => Polled::Pending,
267 Err(RecvTimeoutError::Disconnected) => {
268 self.finished = true;
269 Polled::Failed(CrossError::Data(
270 "the crossing stopped before the table generator finished".to_owned(),
271 ))
272 }
273 }
274 }
275
276 pub fn schema(&self) -> &Schema {
278 &self.schema
279 }
280
281 pub fn stats(&self) -> &CrossingStats {
283 &self.stats
284 }
285}
286
287impl Iterator for TableBatches {
288 type Item = Result<RecordBatch, CrossError>;
289
290 fn next(&mut self) -> Option<Self::Item> {
292 loop {
293 match self.poll(Duration::from_secs(3600)) {
294 Polled::Batch(batch) => return Some(Ok(batch)),
295 Polled::Failed(error) => return Some(Err(error)),
296 Polled::Pending | Polled::State(_) => {}
297 Polled::Finished => return None,
298 }
299 }
300 }
301}