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::StreamExt;
9use futures::channel::oneshot;
10use futures::stream::FuturesUnordered;
11use object_store::MultipartUpload;
12use object_store::ObjectStore;
13use object_store::ObjectStoreExt;
14use object_store::PutPayload;
15use object_store::PutResult;
16use object_store::UploadPart;
17use object_store::path::Path;
18use vortex_error::VortexResult;
19
20use crate::IoBuf;
21use crate::VortexWrite;
22#[cfg(not(target_arch = "wasm32"))]
23use crate::compat::Compat;
24
25/// Adapter type to write data through an [`ObjectStore`] instance.
26///
27/// Call [`VortexWrite::shutdown`] to publish the object or [`Self::abort`] to discard it.
28/// Upload errors preserve the original error and attempt cleanup. Dropping an uncompleted writer
29/// or cancelling a write, flush, or shutdown schedules background cleanup and rejects further writes.
30/// A cancelled shutdown does not report whether the object was published.
31///
32/// Background cleanup survives shutdown of the caller's runtime, but process termination can
33/// prevent cleanup. If the underlying store reuses connections from a caller runtime that goes
34/// idle without shutting down, cleanup still depends on that runtime being driven or retries
35/// opening a fresh connection.
36pub struct ObjectStoreWrite {
37    state: UploadState,
38    concurrency: usize,
39}
40
41struct ActiveUpload {
42    upload: Box<dyn MultipartUpload>,
43    buffer: BytesMut,
44    parts: FuturesUnordered<UploadPart>,
45}
46
47enum UploadState {
48    Active(ActiveUpload),
49    Aborting(oneshot::Receiver<(Box<dyn MultipartUpload>, io::Result<()>)>),
50    Failed(Box<dyn MultipartUpload>),
51    Completed(PutResult),
52    Aborted,
53}
54
55const CHUNK_SIZE: usize = 16 * 1024 * 1024;
56
57impl ObjectStoreWrite {
58    /// Start a multipart upload. The object is not published until shutdown succeeds.
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(ActiveUpload {
63                upload,
64                buffer: BytesMut::with_capacity(CHUNK_SIZE),
65                parts: FuturesUnordered::new(),
66            }),
67            concurrency: 0,
68        })
69    }
70
71    /// Set the maximum number of in-flight parts. Defaults to zero, meaning unlimited.
72    ///
73    /// Upload concurrency controls network throughput, not CPU parallelism. The default avoids
74    /// imposing an arbitrary throughput cap. Set a positive limit to bound adapter-owned buffering
75    /// to that many 16 MiB parts plus one staging part, excluding caller buffers and store internals.
76    /// Configure this before writing; lowering the limit does not cancel existing uploads.
77    pub fn with_concurrency(mut self, concurrency: usize) -> Self {
78        self.concurrency = concurrency;
79        self
80    }
81
82    /// The result of a successful shutdown, or `None` before publication.
83    pub fn put_result(&self) -> Option<&PutResult> {
84        match &self.state {
85            UploadState::Completed(put_result) => Some(put_result),
86            _ => None,
87        }
88    }
89
90    /// Abort this upload, waiting for pending parts before cleanup.
91    ///
92    /// Call this for external errors or empty output, or to await background cleanup after
93    /// cancellation. Cleanup failures can be retried, including after completion fails. Aborting
94    /// again after success is harmless; aborting a published object is an error.
95    pub async fn abort(&mut self) -> io::Result<()> {
96        match self.state {
97            UploadState::Aborted => return Ok(()),
98            UploadState::Completed(_) => {
99                return Err(io::Error::other("multipart upload already completed"));
100            }
101            _ => self.abort_in_background(),
102        }
103        let UploadState::Aborting(receiver) = &mut self.state else {
104            vortex_error::vortex_panic!("abort schedules cleanup before waiting");
105        };
106        let (upload, result) = receiver.await.map_err(io::Error::other)?;
107        self.state = UploadState::Failed(upload);
108        result?;
109        self.state = UploadState::Aborted;
110        Ok(())
111    }
112
113    /// Schedule cleanup independently of the caller's future and runtime. Retain its result so
114    /// explicit abort can await it and retry failures without racing another cleanup attempt.
115    fn abort_in_background(&mut self) {
116        let (mut upload, mut parts) = match std::mem::replace(&mut self.state, UploadState::Aborted)
117        {
118            UploadState::Active(active) => (active.upload, active.parts),
119            UploadState::Failed(upload) => (upload, FuturesUnordered::new()),
120            state => {
121                self.state = state;
122                return;
123            }
124        };
125        let (sender, receiver) = oneshot::channel();
126        self.state = UploadState::Aborting(receiver);
127        spawn_detached_cleanup(async move {
128            // Stores can spawn work internally. Settle parts before aborting so late uploads
129            // cannot race with cleanup, even if the caller cancelled the operation.
130            while parts.next().await.is_some() {}
131            let result = upload.abort().await.map_err(io::Error::from);
132            if let Err(err) = &result {
133                tracing::warn!(%err, "failed to abort multipart upload in background");
134            }
135            drop(sender.send((upload, result)));
136        });
137    }
138
139    fn ensure_active(&mut self) -> io::Result<&mut ActiveUpload> {
140        match &mut self.state {
141            UploadState::Active(active) => Ok(active),
142            UploadState::Completed(_) => {
143                Err(io::Error::other("multipart upload already completed"))
144            }
145            _ => Err(io::Error::other(
146                "multipart upload already failed or aborted",
147            )),
148        }
149    }
150
151    async fn upload_buffer(&mut self) -> io::Result<()> {
152        let concurrency = self.concurrency;
153        let active = self.ensure_active()?;
154        while concurrency != 0 && active.parts.len() >= concurrency {
155            active.parts.next().await.transpose()?;
156        }
157        // Independent, fixed-size allocations keep a submitted part from retaining a larger buffer.
158        let payload = std::mem::replace(&mut active.buffer, BytesMut::with_capacity(CHUNK_SIZE));
159        active.parts.push(
160            active
161                .upload
162                .put_part(PutPayload::from_bytes(payload.freeze())),
163        );
164        Ok(())
165    }
166
167    async fn cleanup_error(&mut self, error: io::Error) -> io::Error {
168        // Background cleanup logs its own errors; never replace the upload error with one.
169        drop(self.abort().await);
170        error
171    }
172}
173
174fn spawn_detached_cleanup(fut: impl Future<Output = ()> + Send + 'static) {
175    #[cfg(not(target_arch = "wasm32"))]
176    {
177        smol::spawn(Compat::new(fut)).detach();
178    }
179
180    #[cfg(all(target_arch = "wasm32", feature = "wasm-bindgen"))]
181    {
182        wasm_bindgen_futures::spawn_local(fut);
183    }
184
185    #[cfg(all(target_arch = "wasm32", not(feature = "wasm-bindgen")))]
186    {
187        if let Ok(handle) = tokio::runtime::Handle::try_current() {
188            handle.spawn(fut);
189            return;
190        }
191        drop(fut);
192        tracing::warn!("no async runtime available to abort multipart upload on drop");
193    }
194}
195
196/// Drop guard that aborts an active upload if an in-flight `write_all`, `flush`, or `shutdown`
197/// future is dropped before completing.
198struct AbortOnCancel<'a> {
199    writer: &'a mut ObjectStoreWrite,
200    armed: bool,
201}
202
203impl<'a> AbortOnCancel<'a> {
204    fn new(writer: &'a mut ObjectStoreWrite) -> Self {
205        Self {
206            writer,
207            armed: true,
208        }
209    }
210
211    fn disarm(mut self) {
212        self.armed = false;
213    }
214}
215
216impl Drop for AbortOnCancel<'_> {
217    fn drop(&mut self) {
218        if self.armed && matches!(self.writer.state, UploadState::Active(_)) {
219            self.writer.abort_in_background();
220        }
221    }
222}
223
224impl Drop for ObjectStoreWrite {
225    fn drop(&mut self) {
226        if matches!(self.state, UploadState::Active(_)) {
227            self.abort_in_background();
228        }
229    }
230}
231
232impl VortexWrite for ObjectStoreWrite {
233    async fn write_all<B: IoBuf>(&mut self, buffer: B) -> io::Result<B> {
234        self.ensure_active()?;
235        let guard = AbortOnCancel::new(self);
236        let mut remaining = buffer.as_slice();
237        while !remaining.is_empty() {
238            let active = guard.writer.ensure_active()?;
239            let len = remaining.len().min(CHUNK_SIZE - active.buffer.len());
240            active.buffer.extend_from_slice(&remaining[..len]);
241            remaining = &remaining[len..];
242            if active.buffer.len() == CHUNK_SIZE
243                && let Err(error) = guard.writer.upload_buffer().await
244            {
245                return Err(guard.writer.cleanup_error(error).await);
246            }
247        }
248        guard.disarm();
249        Ok(buffer)
250    }
251
252    /// Wait for submitted parts without uploading a partial tail or publishing the object.
253    async fn flush(&mut self) -> io::Result<()> {
254        if matches!(self.state, UploadState::Completed(_)) {
255            return Ok(());
256        }
257        self.ensure_active()?;
258        let guard = AbortOnCancel::new(self);
259        while let Some(result) = guard.writer.ensure_active()?.parts.next().await {
260            if let Err(error) = result {
261                return Err(guard.writer.cleanup_error(error.into()).await);
262            }
263        }
264        guard.disarm();
265        Ok(())
266    }
267
268    async fn shutdown(&mut self) -> io::Result<()> {
269        if matches!(self.state, UploadState::Completed(_)) {
270            return Ok(());
271        }
272        self.ensure_active()?;
273        let guard = AbortOnCancel::new(self);
274        if !guard.writer.ensure_active()?.buffer.is_empty()
275            && let Err(error) = guard.writer.upload_buffer().await
276        {
277            return Err(guard.writer.cleanup_error(error).await);
278        }
279        guard.writer.flush().await?;
280        match guard.writer.ensure_active()?.upload.complete().await {
281            Ok(result) => guard.writer.state = UploadState::Completed(result),
282            Err(error) => return Err(guard.writer.cleanup_error(error.into()).await),
283        }
284        guard.disarm();
285        Ok(())
286    }
287}
288
289#[cfg(test)]
290#[cfg(not(target_arch = "wasm32"))]
291mod tests;