Skip to main content

ursa_engine/
session_files.rs

1//! Files a session keeps in memory, and `COPY … TO` them (#517).
2//!
3//! A browser has no disk. The Ursa Shell on the web keeps the files a page
4//! adds in an in-memory object store registered at [`URL`]
5//! (`memory://uploads/`), and a session with that store has *session files*:
6//!
7//! - `COPY … TO 'pos.parquet'` writes `memory://uploads/pos.parquet`;
8//! - `FROM 'pos.parquet'` reads it, before the name is looked for anywhere
9//!   else.
10//!
11//! The write is Ursa's own. DataFusion's file sinks start tokio tasks to
12//! split, serialize and upload what they write, and a browser has no tokio
13//! runtime to start them on: the first `tokio::spawn` panics, which ends the
14//! engine. [`copy_to`] runs the query, serializes its batches with the
15//! writers DataFusion's sinks use (configured from the statement's options
16//! the same way) and puts the bytes in the store, all in the task that asked.
17//!
18//! A native session can have the store for the files a page adds and still
19//! write `COPY … TO` to disk ([`set_copy_to_disk`]), as `ursa serve` does:
20//! its `COPY` is DataFusion's, under the session's root if it has one
21//! (`crate::paths::write_target`). A native session without the store (the
22//! CLI) is untouched: its `COPY` is DataFusion's.
23
24use std::collections::HashMap;
25use std::sync::Arc;
26
27use datafusion::arrow::array::{RecordBatch, UInt64Array};
28use datafusion::arrow::datatypes::{DataType, Field, Schema, SchemaRef};
29use datafusion::arrow::ipc::writer::{FileWriter, IpcWriteOptions};
30use datafusion::arrow::ipc::MetadataVersion;
31use datafusion::common::config::{CsvOptions, JsonOptions, TableParquetOptions};
32use datafusion::common::file_options::csv_writer::CsvWriterOptions;
33use datafusion::common::parsers::CompressionTypeVariant;
34use datafusion::common::tree_node::{TreeNode, TreeNodeRecursion};
35use datafusion::dataframe::DataFrame;
36use datafusion::datasource::file_format::arrow::ArrowFormat;
37use datafusion::datasource::file_format::csv::{CsvFormat, CsvSerializer};
38use datafusion::datasource::file_format::file_type_to_format;
39use datafusion::datasource::file_format::json::{JsonFormat, JsonSerializer};
40use datafusion::datasource::file_format::parquet::ParquetFormat;
41use datafusion::datasource::file_format::write::BatchSerializer;
42use datafusion::datasource::listing::ListingTable;
43use datafusion::datasource::source_as_provider;
44use datafusion::error::{DataFusionError, Result};
45use datafusion::execution::context::SessionState;
46use datafusion::execution::runtime_env::RuntimeEnv;
47use datafusion::logical_expr::dml::CopyTo;
48use datafusion::logical_expr::{LogicalPlan, WriteOp};
49use datafusion::parquet::arrow::arrow_writer::ArrowWriterOptions;
50use datafusion::parquet::arrow::ArrowWriter;
51use datafusion::parquet::file::properties::WriterPropertiesBuilder;
52use datafusion::prelude::{SessionConfig, SessionContext};
53use futures::TryStreamExt;
54use object_store::path::Path as ObjectPath;
55use object_store::{ObjectStore, ObjectStoreExt, PutPayload};
56use url::Url;
57
58/// Where a session's files live.
59pub const URL: &str = "memory://uploads/";
60
61/// The formats [`copy_to`] writes, as a refusal lists them.
62const FORMATS: &str = ".parquet, .csv, .json and .arrow";
63
64/// The session's file store, if it has one.
65pub fn store(runtime: &RuntimeEnv) -> Option<Arc<dyn ObjectStore>> {
66    let url = Url::parse(URL).expect("a valid URL");
67    runtime.object_store_registry.get_store(&url).ok()
68}
69
70/// Whether `COPY … TO` in this session is [`copy_to`]'s: a session with
71/// files that does not write its copies to disk ([`set_copy_to_disk`]), and
72/// any session in the browser, where DataFusion's cannot run.
73pub fn takes_copy(state: &SessionState) -> bool {
74    cfg!(target_arch = "wasm32")
75        || (store(state.runtime_env()).is_some() && !copies_to_disk(state.config()))
76}
77
78/// Whether a session's `COPY … TO` writes to disk though it has files.
79#[derive(Debug)]
80struct CopyToDisk(bool);
81
82/// Make `COPY … TO` in the session `ctx` write to disk (`true`), as
83/// DataFusion's does, though the session has files in memory for the ones a
84/// page adds; or keep its copies with those files (`false`, the default).
85/// The browser has no disk: there `COPY` always keeps the file in memory.
86pub fn set_copy_to_disk(ctx: &SessionContext, on: bool) {
87    let state = ctx.state_ref();
88    let mut state = state.write();
89    state.config_mut().set_extension(Arc::new(CopyToDisk(on)));
90}
91
92/// Whether the session with `config` writes `COPY … TO` to disk though it
93/// has files ([`set_copy_to_disk`]).
94pub fn copies_to_disk(config: &SessionConfig) -> bool {
95    config.get_extension::<CopyToDisk>().is_some_and(|on| on.0)
96}
97
98/// Whether `name` is one a session file is kept under: ASCII letters, digits,
99/// `.`, `_` and `-`, not starting with `.`. Such a name reads back from its
100/// URL as it is written: a URL decodes `%`, ends its path at `#` and `?`, and
101/// a location globs at `*`, `?` and `[`.
102pub fn is_file_name(name: &str) -> bool {
103    !name.is_empty()
104        && !name.starts_with('.')
105        && name
106            .chars()
107            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
108}
109
110/// What a location is to the session's files.
111enum Place<'a> {
112    /// A session file's name: `pos.parquet`, or `memory://uploads/pos.parquet`.
113    File(&'a str),
114    /// A relative path that is no file name, or no name under [`URL`].
115    NotAName,
116    /// A URL somewhere else.
117    Elsewhere,
118}
119
120fn place(location: &str) -> Place<'_> {
121    let name = match location.strip_prefix(URL) {
122        Some(name) => name,
123        // A one-letter scheme is a Windows drive letter.
124        None if matches!(Url::parse(location), Ok(url) if url.scheme().len() > 1) => {
125            return Place::Elsewhere
126        }
127        None => location.strip_prefix("./").unwrap_or(location),
128    };
129    if is_file_name(name) {
130        Place::File(name)
131    } else {
132        Place::NotAName
133    }
134}
135
136/// The URL of the session file `location` names, if the session has it: what
137/// `FROM 'pos.parquet'` reads after `COPY … TO 'pos.parquet'`. `None` for
138/// any other location, which is read as it always was.
139pub async fn existing(runtime: &RuntimeEnv, location: &str) -> Option<String> {
140    let Place::File(name) = place(location) else {
141        return None;
142    };
143    let store = store(runtime)?;
144    store.head(&ObjectPath::from(name)).await.ok()?;
145    Some(format!("{URL}{name}"))
146}
147
148/// The URL `COPY … TO 'target'` writes in a session whose `COPY` is
149/// [`copy_to`]'s ([`takes_copy`]), or why it cannot be written.
150pub fn copy_target(runtime: &RuntimeEnv, target: &str) -> Result<String> {
151    let works = "COPY … TO 'name.parquet' (or .csv, .json, .arrow) keeps the file in this \
152                 session, where FROM 'name.parquet' reads it";
153    if store(runtime).is_none() {
154        return Err(DataFusionError::Plan(format!(
155            "COPY … TO '{target}' has nowhere to write: a browser has no disk, and this \
156             session keeps no files. Run the query and export its result instead"
157        )));
158    }
159    match place(target) {
160        Place::File(name) => Ok(format!("{URL}{name}")),
161        Place::NotAName => Err(DataFusionError::Plan(format!(
162            "COPY … TO '{target}' cannot be written here: a browser has no disk, so a file \
163             is kept in the session under a name of letters, digits, '.', '_' and '-', with \
164             no folder. {works}"
165        ))),
166        Place::Elsewhere => Err(DataFusionError::Plan(format!(
167            "COPY … TO '{target}' cannot be written from a browser, which writes only this \
168             session's files. {works}"
169        ))),
170    }
171}
172
173/// Refuse a target whose extension names no format [`copy_to`] writes, when
174/// no `STORED AS` names one (`stored_as`): DataFusion's refusal says only
175/// that the extension is not registered.
176pub fn check_copy_format(target: &str, stored_as: Option<&str>) -> Result<()> {
177    if stored_as.is_some() {
178        return Ok(());
179    }
180    let extension = target.rsplit_once('.').map(|(_, e)| e.to_ascii_lowercase());
181    match extension.as_deref() {
182        Some("parquet" | "csv" | "json" | "jsonl" | "ndjson" | "arrow") => Ok(()),
183        _ => Err(DataFusionError::Plan(format!(
184            "COPY … TO '{target}' names no format a browser session writes: end the name \
185             in {}, or say STORED AS PARQUET (or CSV, JSON, ARROW)",
186            FORMATS.replace(" and ", " or ")
187        ))),
188    }
189}
190
191/// Run `copy` into the session's files: its query's rows, written as its
192/// format and options say, at its target ([`copy_target`] made it). The frame
193/// is DataFusion's for a `COPY`: one row, `count`.
194pub async fn copy_to(ctx: &SessionContext, copy: &CopyTo) -> Result<DataFrame> {
195    let state = ctx.state();
196    let url = copy_target(state.runtime_env(), &copy.output_url)?;
197    let name = &url[URL.len()..];
198    if !copy.partition_by.is_empty() {
199        return Err(DataFusionError::Plan(
200            "COPY … PARTITIONED BY writes a directory of files, and a browser session keeps \
201             single files; leave PARTITIONED BY out"
202                .into(),
203        ));
204    }
205    // The options, read as DataFusion's physical planner reads them.
206    let mut options: HashMap<String, String> = copy.options.clone();
207    match options
208        .remove("single_file_output")
209        .as_deref()
210        .map(str::trim)
211    {
212        None | Some("true") => {}
213        Some(_) => {
214            return Err(DataFusionError::Plan(
215                "COPY … TO writes one file in a browser session; leave single_file_output out"
216                    .into(),
217            ))
218        }
219    }
220    let format = file_type_to_format(&copy.file_type)?.create(&state, &options)?;
221    // Ursa's Parquet format checks the files it reads around DataFusion's.
222    let format = match format.downcast_ref::<ursa_io::parquet_footer::ValidParquet>() {
223        Some(checked) => Arc::clone(checked.inner()),
224        None => format,
225    };
226    let writer = if let Some(csv) = format.downcast_ref::<CsvFormat>() {
227        Writer::csv(csv.options())?
228    } else if let Some(json) = format.downcast_ref::<JsonFormat>() {
229        Writer::json(json.options())?
230    } else if let Some(parquet) = format.downcast_ref::<ParquetFormat>() {
231        Writer::Parquet(Box::new(parquet.options().clone()))
232    } else if format.is::<ArrowFormat>() {
233        Writer::Arrow
234    } else {
235        return Err(DataFusionError::Plan(format!(
236            "COPY … TO writes {FORMATS} files in a browser session, and '{}' is none of them",
237            copy.file_type.get_ext()
238        )));
239    };
240
241    let schema: SchemaRef = Arc::clone(copy.input.schema().inner());
242    let frame = DataFrame::new(state, copy.input.as_ref().clone());
243    let batches: Vec<RecordBatch> = frame.execute_stream().await?.try_collect().await?;
244    let rows: usize = batches.iter().map(RecordBatch::num_rows).sum();
245    let bytes = writer.write(&schema, batches)?;
246
247    let store = store(ctx.state().runtime_env().as_ref())
248        .ok_or_else(|| DataFusionError::Internal("the session's files are gone".into()))?;
249    store
250        .put(&ObjectPath::from(name), PutPayload::from(bytes))
251        .await
252        .map_err(|e| DataFusionError::External(Box::new(e)))?;
253
254    let count = Arc::new(Schema::new(vec![Field::new(
255        "count",
256        DataType::UInt64,
257        false,
258    )]));
259    let batch = RecordBatch::try_new(count, vec![Arc::new(UInt64Array::from(vec![rows as u64]))])?;
260    ctx.read_batch(batch)
261}
262
263/// Refuse an `INSERT INTO` a table of files, in a session whose `COPY` is
264/// [`copy_to`]'s: the insert runs the file sinks a browser cannot.
265pub fn check_insert(plan: &LogicalPlan) -> Result<()> {
266    let mut refused = None;
267    plan.apply(|node| {
268        if let LogicalPlan::Dml(dml) = node {
269            let files = source_as_provider(&dml.target)
270                .is_ok_and(|table| table.downcast_ref::<ListingTable>().is_some());
271            if files && matches!(dml.op, WriteOp::Insert(_)) {
272                refused = Some(dml.table_name.to_string());
273                return Ok(TreeNodeRecursion::Stop);
274            }
275        }
276        Ok(TreeNodeRecursion::Continue)
277    })?;
278    match refused {
279        None => Ok(()),
280        Some(table) => Err(DataFusionError::Plan(format!(
281            "INSERT INTO {table} cannot run in a browser session: {table} is a table of \
282             files, and a browser cannot append to them. COPY (SELECT …) TO 'name.parquet' \
283             writes a file, and CREATE TABLE … AS keeps rows in the session"
284        ))),
285    }
286}
287
288/// How a file is serialized.
289enum Writer {
290    Csv(CsvSerializer),
291    Json,
292    Parquet(Box<TableParquetOptions>),
293    Arrow,
294}
295
296impl Writer {
297    fn csv(options: &CsvOptions) -> Result<Writer> {
298        let options = CsvWriterOptions::try_from(options)?;
299        uncompressed("CSV", options.compression)?;
300        let header = options.writer_options.header();
301        Ok(Writer::Csv(
302            CsvSerializer::new()
303                .with_builder(options.writer_options)
304                .with_header(header),
305        ))
306    }
307
308    fn json(options: &JsonOptions) -> Result<Writer> {
309        uncompressed("JSON", options.compression)?;
310        Ok(Writer::Json)
311    }
312
313    /// The file's bytes. A result with no batch still writes its schema (a
314    /// CSV its header).
315    fn write(self, schema: &SchemaRef, mut batches: Vec<RecordBatch>) -> Result<Vec<u8>> {
316        let mut bytes = Vec::new();
317        match self {
318            Writer::Csv(serializer) => {
319                if batches.is_empty() {
320                    batches.push(RecordBatch::new_empty(Arc::clone(schema)));
321                }
322                for (i, batch) in batches.into_iter().enumerate() {
323                    bytes.extend_from_slice(&serializer.serialize(batch, i == 0)?);
324                }
325            }
326            // One object a line, as DataFusion writes JSON.
327            Writer::Json => {
328                let serializer = JsonSerializer::new();
329                for (i, batch) in batches.into_iter().enumerate() {
330                    bytes.extend_from_slice(&serializer.serialize(batch, i == 0)?);
331                }
332            }
333            Writer::Parquet(options) => {
334                // As DataFusion's sink: the Arrow schema goes in the file's
335                // metadata through the options, unless they say to skip it.
336                let mut options = *options;
337                if !options.global.skip_arrow_metadata {
338                    options.arrow_schema(schema);
339                }
340                let properties = WriterPropertiesBuilder::try_from(&options)?.build();
341                let options = ArrowWriterOptions::new()
342                    .with_properties(properties)
343                    .with_skip_arrow_metadata(true);
344                let mut writer =
345                    ArrowWriter::try_new_with_options(&mut bytes, Arc::clone(schema), options)?;
346                for batch in &batches {
347                    writer.write(batch)?;
348                }
349                writer.close()?;
350            }
351            // An Arrow IPC file, not compressed (DataFusion's is, with LZ4)
352            // and aligned to 8 bytes, not DataFusion's 64: its reader finds
353            // the schema of a file in an object store 8 bytes after the
354            // magic number, so it cannot read back the files its sink writes.
355            Writer::Arrow => {
356                let options = IpcWriteOptions::try_new(8, false, MetadataVersion::V5)?;
357                let mut writer = FileWriter::try_new_with_options(&mut bytes, schema, options)?;
358                for batch in &batches {
359                    writer.write(batch)?;
360                }
361                writer.finish()?;
362            }
363        }
364        Ok(bytes)
365    }
366}
367
368/// Refuse a compressed text file: DataFusion compresses one as it uploads it,
369/// in the tasks a browser cannot start.
370fn uncompressed(format: &str, compression: CompressionTypeVariant) -> Result<()> {
371    if compression == CompressionTypeVariant::UNCOMPRESSED {
372        return Ok(());
373    }
374    Err(DataFusionError::Plan(format!(
375        "COPY … TO does not write compressed {format} in a browser session; leave the \
376         compression out, or write a .parquet file, which is compressed"
377    )))
378}
379
380#[cfg(test)]
381mod tests {
382    use super::*;
383
384    #[test]
385    fn places() {
386        assert!(matches!(place("pos.parquet"), Place::File("pos.parquet")));
387        assert!(matches!(place("./pos.parquet"), Place::File("pos.parquet")));
388        assert!(matches!(
389            place("memory://uploads/pos.parquet"),
390            Place::File("pos.parquet")
391        ));
392        for not in [
393            "out/pos.parquet",
394            "/tmp/pos.parquet",
395            "../pos.parquet",
396            "my file.csv",
397            "p*.csv",
398            ".hidden",
399            "",
400            "memory://uploads/a/b.csv",
401            "memory://uploads/",
402        ] {
403            assert!(matches!(place(not), Place::NotAName), "{not}");
404        }
405        for elsewhere in [
406            "https://example.com/pos.parquet",
407            "s3://bucket/pos.parquet",
408            "memory://other/pos.parquet",
409            "file:///tmp/pos.parquet",
410        ] {
411            assert!(matches!(place(elsewhere), Place::Elsewhere), "{elsewhere}");
412        }
413    }
414}