Skip to main content

vortex_io/object_store/write/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::io;
5use std::sync::Arc;
6
7use bytes::BytesMut;
8use futures::TryStreamExt;
9use futures::stream::FuturesUnordered;
10use object_store::MultipartUpload;
11use object_store::ObjectStore;
12use object_store::ObjectStoreExt;
13use object_store::PutPayload;
14use object_store::PutResult;
15use object_store::path::Path;
16use vortex_error::VortexResult;
17
18use crate::IoBuf;
19use crate::VortexWrite;
20#[cfg(not(target_arch = "wasm32"))]
21use crate::compat::Compat;
22
23/// Adapter type to write data through an [`ObjectStore`] instance.
24///
25/// Each active instance exclusively owns its underlying [`MultipartUpload`]. After writing, the
26/// caller must call [`VortexWrite::shutdown`] to complete and publish the object.
27///
28/// Multipart initiation, part uploads, and completion run on the caller's async runtime so
29/// concurrent writers scale across the caller's worker threads. If a part upload or completion
30/// fails, the writer schedules a background abort once, returns the part/completion error, and
31/// rejects any subsequent writes or completion.
32///
33/// Dropping an uncompleted writer (or cancelling an in-flight `write_all`, `flush`, or `shutdown`
34/// future) schedules an asynchronous abort on a process-lifetime executor (`smol` with a `Compat`
35/// Tokio context on native targets) so cleanup survives both task cancellation and shutdown of the
36/// caller's Tokio runtime. A cancelled `shutdown()` aborts in the background and does not report
37/// whether the object was published. Process termination can still prevent cleanup. If the
38/// underlying [`ObjectStore`] holds pooled keep-alive connections opened on a caller Tokio runtime
39/// that later goes idle (without shutting down) and retries are disabled (`max_retries: 0`), an
40/// abort that reuses such a connection still depends on that runtime remaining driven or retries
41/// opening a fresh connection.
42pub struct ObjectStoreWrite {
43    state: UploadState,
44}
45
46enum UploadState {
47    Active {
48        upload: Box<dyn MultipartUpload>,
49        buffer: BytesMut,
50    },
51    Completed(PutResult),
52    Aborted,
53}
54
55const CHUNK_SIZE: usize = 16 * 1024 * 1024;
56const BUFFER_SIZE: usize = 128 * 1024 * 1024;
57
58impl ObjectStoreWrite {
59    pub async fn new(object_store: Arc<dyn ObjectStore>, location: &Path) -> VortexResult<Self> {
60        let upload = object_store.put_multipart(location).await?;
61        Ok(Self {
62            state: UploadState::Active {
63                upload,
64                buffer: BytesMut::with_capacity(CHUNK_SIZE),
65            },
66        })
67    }
68
69    pub fn put_result(&self) -> Option<&PutResult> {
70        match &self.state {
71            UploadState::Completed(put_result) => Some(put_result),
72            _ => None,
73        }
74    }
75
76    /// Schedule detached cleanup when a part/completion fails, a future is cancelled, or the
77    /// writer is dropped before completing.
78    fn abort_in_background(&mut self) {
79        if !matches!(self.state, UploadState::Active { .. }) {
80            return;
81        }
82        let UploadState::Active { mut upload, .. } =
83            std::mem::replace(&mut self.state, UploadState::Aborted)
84        else {
85            vortex_error::vortex_panic!("checked active state above");
86        };
87        spawn_detached_cleanup(async move {
88            if let Err(err) = upload.abort().await {
89                tracing::warn!(%err, "failed to abort multipart upload in background");
90            }
91        });
92    }
93
94    fn ensure_active(&mut self) -> io::Result<(&mut Box<dyn MultipartUpload>, &mut BytesMut)> {
95        match &mut self.state {
96            UploadState::Active { upload, buffer } => Ok((upload, buffer)),
97            UploadState::Completed(_) => {
98                Err(io::Error::other("multipart upload already completed"))
99            }
100            UploadState::Aborted => Err(io::Error::other(
101                "multipart upload already failed or aborted",
102            )),
103        }
104    }
105
106    /// Flush buffered chunks of up to `CHUNK_SIZE` while more than `min_remaining` bytes remain.
107    ///
108    /// Arms [`AbortOnCancel`] once chunks are removed from the buffer; on failure or cancellation,
109    /// dropping the guard schedules a background abort once and returns the part error.
110    async fn flush_parts(&mut self, min_remaining: usize) -> io::Result<()> {
111        let (_, buffer) = self.ensure_active()?;
112        if buffer.len() <= min_remaining {
113            return Ok(());
114        }
115
116        let guard = AbortOnCancel::new(self);
117        let part_result = {
118            let (upload, buffer) = guard.writer.ensure_active()?;
119            let parts = FuturesUnordered::new();
120            while buffer.len() > min_remaining {
121                let size = buffer.len().min(CHUNK_SIZE);
122                let payload = buffer.split_to(size).freeze();
123                parts.push(upload.put_part(PutPayload::from_bytes(payload)));
124            }
125            parts.try_collect::<Vec<_>>().await
126        };
127
128        part_result?;
129        guard.disarm();
130        Ok(())
131    }
132}
133
134fn spawn_detached_cleanup(fut: impl Future<Output = ()> + Send + 'static) {
135    #[cfg(not(target_arch = "wasm32"))]
136    {
137        smol::spawn(Compat::new(fut)).detach();
138    }
139
140    #[cfg(all(target_arch = "wasm32", feature = "wasm-bindgen"))]
141    {
142        wasm_bindgen_futures::spawn_local(fut);
143    }
144
145    #[cfg(all(target_arch = "wasm32", not(feature = "wasm-bindgen")))]
146    {
147        if let Ok(handle) = tokio::runtime::Handle::try_current() {
148            handle.spawn(fut);
149            return;
150        }
151        drop(fut);
152        tracing::warn!("no async runtime available to abort multipart upload on drop");
153    }
154}
155
156/// Drop guard that aborts an active upload if an in-flight `write_all`, `flush`, or `shutdown`
157/// future is dropped before completing.
158struct AbortOnCancel<'a> {
159    writer: &'a mut ObjectStoreWrite,
160    armed: bool,
161}
162
163impl<'a> AbortOnCancel<'a> {
164    fn new(writer: &'a mut ObjectStoreWrite) -> Self {
165        Self {
166            writer,
167            armed: true,
168        }
169    }
170
171    fn disarm(mut self) {
172        self.armed = false;
173    }
174}
175
176impl Drop for AbortOnCancel<'_> {
177    fn drop(&mut self) {
178        if self.armed {
179            self.writer.abort_in_background();
180        }
181    }
182}
183
184impl Drop for ObjectStoreWrite {
185    fn drop(&mut self) {
186        self.abort_in_background();
187    }
188}
189
190impl VortexWrite for ObjectStoreWrite {
191    async fn write_all<B: IoBuf>(&mut self, buffer: B) -> io::Result<B> {
192        let (_, buf) = self.ensure_active()?;
193        buf.extend_from_slice(buffer.as_slice());
194
195        if buf.len() > BUFFER_SIZE {
196            self.flush_parts(CHUNK_SIZE).await?;
197        }
198
199        Ok(buffer)
200    }
201
202    async fn flush(&mut self) -> io::Result<()> {
203        self.flush_parts(CHUNK_SIZE).await
204    }
205
206    async fn shutdown(&mut self) -> io::Result<()> {
207        if matches!(self.state, UploadState::Completed(_)) {
208            return Ok(());
209        }
210
211        self.flush_parts(0).await?;
212
213        let guard = AbortOnCancel::new(self);
214        let (upload, _) = guard.writer.ensure_active()?;
215        let put_result = upload.complete().await?;
216        guard.writer.state = UploadState::Completed(put_result);
217        guard.disarm();
218        Ok(())
219    }
220}
221
222#[cfg(test)]
223#[cfg(not(target_arch = "wasm32"))]
224mod tests;