nautilus_persistence/backend/
session.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2025 Posei Systems Pty Ltd. All rights reserved.
3//  https://poseitrader.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16use std::{collections::HashMap, sync::Arc, vec::IntoIter};
17
18use compare::Compare;
19use datafusion::{
20    error::Result, logical_expr::expr::Sort, physical_plan::SendableRecordBatchStream, prelude::*,
21};
22use futures::StreamExt;
23use nautilus_core::{UnixNanos, ffi::cvec::CVec};
24use nautilus_model::data::{Data, HasTsInit};
25use nautilus_serialization::arrow::{
26    DataStreamingError, DecodeDataFromRecordBatch, EncodeToRecordBatch, WriteStream,
27};
28use object_store::ObjectStore;
29use url::Url;
30
31use super::kmerge_batch::{EagerStream, ElementBatchIter, KMerge};
32
33#[derive(Debug, Default)]
34pub struct TsInitComparator;
35
36impl<I> Compare<ElementBatchIter<I, Data>> for TsInitComparator
37where
38    I: Iterator<Item = IntoIter<Data>>,
39{
40    fn compare(
41        &self,
42        l: &ElementBatchIter<I, Data>,
43        r: &ElementBatchIter<I, Data>,
44    ) -> std::cmp::Ordering {
45        // Max heap ordering must be reversed
46        l.item.ts_init().cmp(&r.item.ts_init()).reverse()
47    }
48}
49
50pub type QueryResult = KMerge<EagerStream<std::vec::IntoIter<Data>>, Data, TsInitComparator>;
51
52/// Provides a DataFusion session and registers DataFusion queries.
53///
54/// The session is used to register data sources and make queries on them. A
55/// query returns a Chunk of Arrow records. It is decoded and converted into
56/// a Vec of data by types that implement [`DecodeDataFromRecordBatch`].
57#[cfg_attr(
58    feature = "python",
59    pyo3::pyclass(module = "posei_trader.core.nautilus_pyo3.persistence")
60)]
61pub struct DataBackendSession {
62    pub chunk_size: usize,
63    pub runtime: Arc<tokio::runtime::Runtime>,
64    session_ctx: SessionContext,
65    batch_streams: Vec<EagerStream<IntoIter<Data>>>,
66}
67
68impl DataBackendSession {
69    /// Creates a new [`DataBackendSession`] instance.
70    #[must_use]
71    pub fn new(chunk_size: usize) -> Self {
72        let runtime = tokio::runtime::Builder::new_multi_thread()
73            .enable_all()
74            .build()
75            .unwrap();
76        let session_cfg = SessionConfig::new()
77            .set_str("datafusion.optimizer.repartition_file_scans", "false")
78            .set_str("datafusion.optimizer.prefer_existing_sort", "true");
79        let session_ctx = SessionContext::new_with_config(session_cfg);
80        Self {
81            session_ctx,
82            batch_streams: Vec::default(),
83            chunk_size,
84            runtime: Arc::new(runtime),
85        }
86    }
87
88    /// Register an object store with the session context
89    pub fn register_object_store(&mut self, url: &Url, object_store: Arc<dyn ObjectStore>) {
90        self.session_ctx.register_object_store(url, object_store);
91    }
92
93    /// Register an object store with the session context from a URI with optional storage options
94    pub fn register_object_store_from_uri(
95        &mut self,
96        uri: &str,
97        storage_options: Option<std::collections::HashMap<String, String>>,
98    ) -> anyhow::Result<()> {
99        // Create object store from URI using the Rust implementation
100        let (object_store, _, _) =
101            crate::parquet::create_object_store_from_path(uri, storage_options)?;
102
103        // Parse the URI to get the base URL for registration
104        let parsed_uri = Url::parse(uri)?;
105
106        // Register the object store with the session
107        if matches!(
108            parsed_uri.scheme(),
109            "s3" | "gs" | "gcs" | "azure" | "abfs" | "http" | "https"
110        ) {
111            // For cloud storage, register with the base URL (scheme + netloc)
112            let base_url = format!(
113                "{}://{}",
114                parsed_uri.scheme(),
115                parsed_uri.host_str().unwrap_or("")
116            );
117            let base_parsed_url = Url::parse(&base_url)?;
118            self.register_object_store(&base_parsed_url, object_store);
119        }
120
121        Ok(())
122    }
123
124    pub fn write_data<T: EncodeToRecordBatch>(
125        data: &[T],
126        metadata: &HashMap<String, String>,
127        stream: &mut dyn WriteStream,
128    ) -> Result<(), DataStreamingError> {
129        let record_batch = T::encode_batch(metadata, data)?;
130        stream.write(&record_batch)?;
131        Ok(())
132    }
133
134    /// Query a file for its records. the caller must specify `T` to indicate
135    /// the kind of data expected from this query.
136    ///
137    /// `table_name`: Logical `table_name` assigned to this file. Queries to this file should address the
138    /// file by its table name.
139    /// `file_path`: Path to file
140    /// `sql_query`: A custom sql query to retrieve records from file. If no query is provided a default
141    /// query "SELECT * FROM <`table_name`>" is run.
142    ///
143    /// # Safety
144    ///
145    /// The file data must be ordered by the `ts_init` in ascending order for this
146    /// to work correctly.
147    pub fn add_file<T>(
148        &mut self,
149        table_name: &str,
150        file_path: &str,
151        sql_query: Option<&str>,
152    ) -> Result<()>
153    where
154        T: DecodeDataFromRecordBatch + Into<Data>,
155    {
156        let parquet_options = ParquetReadOptions::<'_> {
157            skip_metadata: Some(false),
158            file_sort_order: vec![vec![Sort {
159                expr: col("ts_init"),
160                asc: true,
161                nulls_first: false,
162            }]],
163            ..Default::default()
164        };
165        self.runtime.block_on(self.session_ctx.register_parquet(
166            table_name,
167            file_path,
168            parquet_options,
169        ))?;
170
171        let default_query = format!("SELECT * FROM {} ORDER BY ts_init", &table_name);
172        let sql_query = sql_query.unwrap_or(&default_query);
173        let query = self.runtime.block_on(self.session_ctx.sql(sql_query))?;
174
175        let batch_stream = self.runtime.block_on(query.execute_stream())?;
176
177        self.add_batch_stream::<T>(batch_stream);
178        Ok(())
179    }
180
181    fn add_batch_stream<T>(&mut self, stream: SendableRecordBatchStream)
182    where
183        T: DecodeDataFromRecordBatch + Into<Data>,
184    {
185        let transform = stream.map(|result| match result {
186            Ok(batch) => T::decode_data_batch(batch.schema().metadata(), batch)
187                .unwrap()
188                .into_iter(),
189            Err(e) => panic!("Error getting next batch from RecordBatchStream: {e}"),
190        });
191
192        self.batch_streams
193            .push(EagerStream::from_stream_with_runtime(
194                transform,
195                self.runtime.clone(),
196            ));
197    }
198
199    // Consumes the registered queries and returns a [`QueryResult].
200    // Passes the output of the query though the a KMerge which sorts the
201    // queries in ascending order of `ts_init`.
202    // QueryResult is an iterator that return Vec<Data>.
203    pub fn get_query_result(&mut self) -> QueryResult {
204        let mut kmerge: KMerge<_, _, _> = KMerge::new(TsInitComparator);
205
206        self.batch_streams
207            .drain(..)
208            .for_each(|eager_stream| kmerge.push_iter(eager_stream));
209
210        kmerge
211    }
212}
213
214// Note: Intended to be used on a single Python thread
215unsafe impl Send for DataBackendSession {}
216
217#[must_use]
218pub fn build_query(
219    table: &str,
220    start: Option<UnixNanos>,
221    end: Option<UnixNanos>,
222    where_clause: Option<&str>,
223) -> String {
224    let mut conditions = Vec::new();
225
226    // Add where clause if provided
227    if let Some(clause) = where_clause {
228        conditions.push(clause.to_string());
229    }
230
231    // Add start condition if provided
232    if let Some(start_ts) = start {
233        conditions.push(format!("ts_init >= {start_ts}"));
234    }
235
236    // Add end condition if provided
237    if let Some(end_ts) = end {
238        conditions.push(format!("ts_init <= {end_ts}"));
239    }
240
241    // Build base query
242    let mut query = format!("SELECT * FROM {table}");
243
244    // Add WHERE clause if there are conditions
245    if !conditions.is_empty() {
246        query.push_str(" WHERE ");
247        query.push_str(&conditions.join(" AND "));
248    }
249
250    // Add ORDER BY clause
251    query.push_str(" ORDER BY ts_init");
252
253    query
254}
255
256#[cfg_attr(
257    feature = "python",
258    pyo3::pyclass(module = "posei_trader.core.nautilus_pyo3.persistence", unsendable)
259)]
260pub struct DataQueryResult {
261    pub chunk: Option<CVec>,
262    pub result: QueryResult,
263    pub acc: Vec<Data>,
264    pub size: usize,
265}
266
267impl DataQueryResult {
268    /// Creates a new [`DataQueryResult`] instance.
269    #[must_use]
270    pub const fn new(result: QueryResult, size: usize) -> Self {
271        Self {
272            chunk: None,
273            result,
274            acc: Vec::new(),
275            size,
276        }
277    }
278
279    /// Set new `CVec` backed chunk from data
280    ///
281    /// It also drops previously allocated chunk
282    pub fn set_chunk(&mut self, data: Vec<Data>) -> CVec {
283        self.drop_chunk();
284
285        let chunk: CVec = data.into();
286        self.chunk = Some(chunk);
287        chunk
288    }
289
290    /// Chunks generated by iteration must be dropped after use, otherwise
291    /// it will leak memory. Current chunk is held by the reader,
292    /// drop if exists and reset the field.
293    pub fn drop_chunk(&mut self) {
294        if let Some(CVec { ptr, len, cap }) = self.chunk.take() {
295            let data: Vec<Data> =
296                unsafe { Vec::from_raw_parts(ptr.cast::<nautilus_model::data::Data>(), len, cap) };
297            drop(data);
298        }
299    }
300}
301
302impl Iterator for DataQueryResult {
303    type Item = Vec<Data>;
304
305    fn next(&mut self) -> Option<Self::Item> {
306        for _ in 0..self.size {
307            match self.result.next() {
308                Some(item) => self.acc.push(item),
309                None => break,
310            }
311        }
312
313        // TODO: consider using drain here if perf is unchanged
314        // Some(self.acc.drain(0..).collect())
315        let mut acc: Vec<Data> = Vec::new();
316        std::mem::swap(&mut acc, &mut self.acc);
317        Some(acc)
318    }
319}
320
321impl Drop for DataQueryResult {
322    fn drop(&mut self) {
323        self.drop_chunk();
324        self.result.clear();
325    }
326}
327
328// Note: Intended to be used on a single Python thread
329unsafe impl Send for DataQueryResult {}