1use std::io;
5use std::io::Write;
6use std::sync::Arc;
7use std::sync::atomic::AtomicU64;
8
9use futures::FutureExt;
10use futures::StreamExt;
11use futures::TryStreamExt;
12use futures::future::Fuse;
13use futures::future::LocalBoxFuture;
14use futures::future::ready;
15use futures::pin_mut;
16use futures::select;
17use itertools::Itertools;
18use vortex_array::ArrayContext;
19use vortex_array::ArrayRef;
20use vortex_array::dtype::DType;
21use vortex_array::expr::stats::Stat;
22use vortex_array::iter::ArrayIterator;
23use vortex_array::iter::ArrayIteratorExt;
24use vortex_array::session::ArraySessionExt;
25use vortex_array::stats::PRUNING_STATS;
26use vortex_array::stream::ArrayStream;
27use vortex_array::stream::ArrayStreamAdapter;
28use vortex_array::stream::ArrayStreamExt;
29use vortex_array::stream::SendableArrayStream;
30use vortex_buffer::ByteBuffer;
31use vortex_error::VortexError;
32use vortex_error::VortexExpect;
33use vortex_error::VortexResult;
34use vortex_error::vortex_bail;
35use vortex_error::vortex_err;
36use vortex_io::IoBuf;
37use vortex_io::VortexWrite;
38use vortex_io::kanal_ext::KanalExt;
39use vortex_io::runtime::BlockingRuntime;
40use vortex_io::session::RuntimeSessionExt;
41use vortex_layout::LayoutStrategy;
42use vortex_layout::layouts::file_stats::accumulate_stats;
43use vortex_layout::sequence::SequenceId;
44use vortex_layout::sequence::SequentialStreamAdapter;
45use vortex_layout::sequence::SequentialStreamExt;
46use vortex_session::SessionExt;
47use vortex_session::VortexSession;
48use vortex_session::registry::ReadContext;
49
50use crate::ALLOWED_ENCODINGS;
51use crate::Footer;
52use crate::MAGIC_BYTES;
53use crate::WriteStrategyBuilder;
54use crate::counting::CountingVortexWrite;
55use crate::footer::FileStatistics;
56use crate::segments::writer::BufferedSegmentSink;
57
58pub struct VortexWriteOptions {
64 session: VortexSession,
65 strategy: Arc<dyn LayoutStrategy>,
66 exclude_dtype: bool,
67 max_variable_length_statistics_size: usize,
68 file_statistics: Vec<Stat>,
69}
70
71pub trait WriteOptionsSessionExt: SessionExt {
72 fn write_options(&self) -> VortexWriteOptions {
74 let session = self.session();
75 VortexWriteOptions {
76 strategy: WriteStrategyBuilder::default().build(),
77 session,
78 exclude_dtype: false,
79 file_statistics: PRUNING_STATS.to_vec(),
80 max_variable_length_statistics_size: 64,
81 }
82 }
83}
84impl<S: SessionExt> WriteOptionsSessionExt for S {}
85
86impl VortexWriteOptions {
87 pub fn new(session: VortexSession) -> Self {
89 VortexWriteOptions {
90 strategy: WriteStrategyBuilder::default().build(),
91 session,
92 exclude_dtype: false,
93 file_statistics: PRUNING_STATS.to_vec(),
94 max_variable_length_statistics_size: 64,
95 }
96 }
97
98 pub fn with_strategy(mut self, strategy: Arc<dyn LayoutStrategy>) -> Self {
100 self.strategy = strategy;
101 self
102 }
103
104 pub fn exclude_dtype(mut self) -> Self {
108 self.exclude_dtype = true;
109 self
110 }
111
112 pub fn with_file_statistics(mut self, file_statistics: Vec<Stat>) -> Self {
114 self.file_statistics = file_statistics;
115 self
116 }
117}
118
119impl VortexWriteOptions {
120 pub fn blocking<B: BlockingRuntime>(self, runtime: &B) -> BlockingWrite<'_, B> {
122 BlockingWrite {
123 options: self,
124 runtime,
125 }
126 }
127
128 pub async fn write<W: VortexWrite + Unpin, S: ArrayStream + Send + 'static>(
133 self,
134 write: W,
135 stream: S,
136 ) -> VortexResult<WriteSummary> {
137 self.write_internal(write, ArrayStreamExt::boxed(stream))
138 .await
139 }
140
141 async fn write_internal<W: VortexWrite + Unpin>(
142 self,
143 mut write: W,
144 stream: SendableArrayStream,
145 ) -> VortexResult<WriteSummary> {
146 let ctx = ArrayContext::new(ALLOWED_ENCODINGS.iter().cloned().sorted().collect())
152 .with_registry(self.session.arrays().registry().clone());
154 let dtype = stream.dtype().clone();
155
156 let (mut ptr, eof) = SequenceId::root().split();
157
158 let stream = SequentialStreamAdapter::new(
159 dtype.clone(),
160 stream
161 .try_filter(|chunk| ready(!chunk.is_empty()))
162 .map(move |result| result.map(|chunk| (ptr.advance(), chunk))),
163 )
164 .sendable();
165 let (file_stats, stream) = accumulate_stats(
166 stream,
167 self.file_statistics.clone().into(),
168 self.max_variable_length_statistics_size,
169 &self.session,
170 );
171
172 write.write_all(ByteBuffer::copy_from(MAGIC_BYTES)).await?;
174 let mut position = MAGIC_BYTES.len() as u64;
175
176 let (send, recv) = kanal::bounded_async(1);
178
179 let segments = Arc::new(BufferedSegmentSink::new(send, position));
180
181 let ctx2 = ctx.clone();
184 let session = self.session.clone();
185 let layout_fut = self.session.handle().spawn_nested(move |h| async move {
186 let session = session.with_handle(h);
187 let layout = self
188 .strategy
189 .write_stream(
190 ctx2,
191 Arc::<BufferedSegmentSink>::clone(&segments),
192 stream,
193 eof,
194 &session,
195 )
196 .await?;
197 Ok::<_, VortexError>((layout, segments.segment_specs()))
198 });
199
200 let recv_stream = recv.into_stream();
202 pin_mut!(recv_stream);
203 while let Some(buffer) = recv_stream.next().await {
204 if buffer.is_empty() {
205 continue;
206 }
207 position += buffer.len() as u64;
208 write.write_all(buffer).await?;
209 }
210
211 let (layout, segment_specs) = layout_fut.await?;
212
213 let mut footer = Footer::new(
215 Arc::clone(&layout),
216 segment_specs,
217 if self.file_statistics.is_empty() {
218 None
219 } else {
220 Some(FileStatistics::new_with_dtype(
221 file_stats.stats_sets().into(),
222 &dtype,
223 ))
224 },
225 ReadContext::new(ctx.to_ids()),
226 );
227
228 let footer_buffers = footer
230 .clone()
231 .into_serializer()
232 .with_offset(position)
233 .with_exclude_dtype(self.exclude_dtype)
234 .serialize()?;
235
236 footer = footer.with_approx_byte_size(footer_buffers.iter().map(|b| b.len()).sum());
239
240 for buffer in footer_buffers {
241 position += buffer.len() as u64;
242 write.write_all(buffer).await?;
243 }
244
245 write.flush().await?;
246
247 Ok(WriteSummary {
248 footer,
249 size: position,
250 })
251 }
252
253 pub fn writer<'w, W: VortexWrite + Unpin + 'w>(self, write: W, dtype: DType) -> Writer<'w> {
255 let (arrays_send, arrays_recv) = kanal::bounded_async(1);
257
258 let arrays =
259 ArrayStreamExt::boxed(ArrayStreamAdapter::new(dtype, arrays_recv.into_stream()));
260
261 let write = CountingVortexWrite::new(write);
262 let bytes_written = write.counter();
263 let strategy = Arc::clone(&self.strategy);
264 let future = self.write(write, arrays).boxed_local().fuse();
265
266 Writer {
267 arrays: Some(arrays_send),
268 future,
269 bytes_written,
270 strategy,
271 }
272 }
273}
274
275pub struct Writer<'w> {
277 arrays: Option<kanal::AsyncSender<VortexResult<ArrayRef>>>,
279 future: Fuse<LocalBoxFuture<'w, VortexResult<WriteSummary>>>,
281 bytes_written: Arc<AtomicU64>,
283 strategy: Arc<dyn LayoutStrategy>,
285}
286
287impl Writer<'_> {
288 pub async fn push(&mut self, chunk: ArrayRef) -> VortexResult<()> {
290 let arrays = self.arrays.clone().vortex_expect("missing arrays sender");
291 let send_fut = async move { arrays.send(Ok(chunk)).await }.fuse();
292 pin_mut!(send_fut);
293
294 select! {
297 result = send_fut => {
298 if result.is_err() {
300 return Err(self.handle_failed_task().await);
301 }
302 },
303 result = &mut self.future => {
304 match result {
308 Ok(_) => vortex_bail!("Internal error: writer future completed early"),
309 Err(e) => return Err(e),
310 }
311 }
312 }
313
314 Ok(())
315 }
316
317 pub async fn push_stream(&mut self, mut stream: SendableArrayStream) -> VortexResult<()> {
322 let arrays = self.arrays.clone().vortex_expect("missing arrays sender");
323 let stream_fut = async move {
324 while let Some(chunk) = stream.next().await {
325 arrays.send(chunk).await?;
326 }
327 Ok::<_, kanal::SendError>(())
328 }
329 .fuse();
330 pin_mut!(stream_fut);
331
332 select! {
335 result = stream_fut => {
336 if let Err(_send_err) = result {
337 return Err(self.handle_failed_task().await);
339 }
340 }
341
342 result = &mut self.future => {
343 match result {
347 Ok(_) => vortex_bail!("Internal error: writer future completed early"),
348 Err(e) => return Err(e),
349 }
350 }
351 }
352
353 Ok(())
354 }
355
356 pub fn bytes_written(&self) -> u64 {
358 self.bytes_written
359 .load(std::sync::atomic::Ordering::Relaxed)
360 }
361
362 pub fn buffered_bytes(&self) -> u64 {
364 self.strategy.buffered_bytes()
365 }
366
367 pub async fn finish(mut self) -> VortexResult<WriteSummary> {
370 drop(self.arrays.take());
372
373 self.future.await
375 }
376
377 async fn handle_failed_task(&mut self) -> VortexError {
379 match (&mut self.future).await {
380 Ok(_) => vortex_err!(
381 "Internal error: writer task completed successfully but write future finished early"
382 ),
383 Err(e) => e,
384 }
385 }
386}
387
388pub struct BlockingWrite<'rt, B: BlockingRuntime> {
390 options: VortexWriteOptions,
391 runtime: &'rt B,
392}
393
394impl<'rt, B: BlockingRuntime> BlockingWrite<'rt, B> {
395 pub fn write<W: Write + Unpin>(
397 self,
398 write: W,
399 iter: impl ArrayIterator + Send + 'static,
400 ) -> VortexResult<WriteSummary> {
401 self.runtime.block_on(async move {
402 self.options
403 .write(BlockingWriteAdapter(write), iter.into_array_stream())
404 .await
405 })
406 }
407
408 pub fn writer<'w, W: Write + Unpin + 'w>(
409 self,
410 write: W,
411 dtype: DType,
412 ) -> BlockingWriter<'rt, 'w, B> {
413 BlockingWriter {
414 writer: self.options.writer(BlockingWriteAdapter(write), dtype),
415 runtime: self.runtime,
416 }
417 }
418}
419
420pub struct BlockingWriter<'rt, 'w, B: BlockingRuntime> {
422 runtime: &'rt B,
423 writer: Writer<'w>,
424}
425
426impl<B: BlockingRuntime> BlockingWriter<'_, '_, B> {
427 pub fn push(&mut self, chunk: ArrayRef) -> VortexResult<()> {
428 self.runtime.block_on(self.writer.push(chunk))
429 }
430
431 pub fn bytes_written(&self) -> u64 {
432 self.writer.bytes_written()
433 }
434
435 pub fn buffered_bytes(&self) -> u64 {
436 self.writer.buffered_bytes()
437 }
438
439 pub fn finish(self) -> VortexResult<WriteSummary> {
440 self.runtime.block_on(self.writer.finish())
441 }
442}
443
444struct BlockingWriteAdapter<W>(W);
446
447impl<W: Write + Unpin> VortexWrite for BlockingWriteAdapter<W> {
448 async fn write_all<B: IoBuf>(&mut self, buffer: B) -> io::Result<B> {
449 self.0.write_all(buffer.as_slice())?;
450 Ok(buffer)
451 }
452
453 fn flush(&mut self) -> impl Future<Output = io::Result<()>> {
454 ready(self.0.flush())
455 }
456
457 fn shutdown(&mut self) -> impl Future<Output = io::Result<()>> {
458 ready(Ok(()))
459 }
460}
461
462pub struct WriteSummary {
463 footer: Footer,
464 size: u64,
465 }
467
468impl WriteSummary {
469 pub fn footer(&self) -> &Footer {
471 &self.footer
472 }
473
474 pub fn size(&self) -> u64 {
476 self.size
477 }
478
479 pub fn row_count(&self) -> u64 {
481 self.footer.row_count()
482 }
483}