Skip to main content

mito2/series_index/
artifact_writer.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
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//! Owned outputs shared by immutable columnar artifacts.
16
17use bytes::Bytes;
18use object_store::{ObjectStore, Writer};
19use snafu::{IntoError, ResultExt};
20
21use crate::cache::write_cache::{NarthexUpload, WriteCache};
22use crate::error::{JoinSnafu, OpenDalSnafu, Result};
23use crate::series_index::columnar::{invalid, require};
24use crate::sst::{DEFAULT_WRITE_BUFFER_SIZE, DEFAULT_WRITE_CONCURRENCY};
25
26/// Drop owns the live OpenDAL writer, including its private atomic-write temporary file.
27pub(super) struct LiveFile {
28    writer: Option<Writer>,
29    store: ObjectStore,
30    path: String,
31}
32impl Drop for LiveFile {
33    fn drop(&mut self) {
34        if let Some(mut writer) = self.writer.take() {
35            let store = self.store.clone();
36            let path = self.path.clone();
37            common_runtime::spawn_compact(async move {
38                if let Err(error) = writer.abort().await {
39                    common_telemetry::warn!(error; "Aborting artifact output {path}");
40                }
41                if let Err(error) = store.delete(&path).await {
42                    common_telemetry::warn!(error; "Deleting artifact output {path}");
43                }
44            });
45        }
46    }
47}
48
49pub(super) struct Outputs {
50    pub(super) store: ObjectStore,
51    pub(super) active: Option<LiveFile>,
52    pub(super) paths: Vec<String>,
53    pub(super) committed: bool,
54    pub(crate) upload: Option<NarthexUpload>,
55}
56impl Outputs {
57    pub(super) async fn open(&mut self, path: String) -> Result<()> {
58        require(self.active.is_none(), "artifact output already open")?;
59        let path = if self.upload.is_some() {
60            WriteCache::narthex_stage(&path)
61        } else {
62            path
63        };
64        self.paths.push(path.clone());
65        let store = self.store.clone();
66        // The task owns opening: cancellation drops the returned LiveFile and aborts it.
67        self.active = Some(
68            common_runtime::spawn_compact(async move {
69                let writer = store
70                    .writer_with(&path)
71                    .chunk(DEFAULT_WRITE_BUFFER_SIZE.as_bytes() as usize)
72                    .concurrent(DEFAULT_WRITE_CONCURRENCY)
73                    .await
74                    .context(OpenDalSnafu)?;
75                Ok::<_, crate::error::Error>(LiveFile {
76                    writer: Some(writer),
77                    store,
78                    path,
79                })
80            })
81            .await
82            .context(JoinSnafu)??,
83        );
84        Ok(())
85    }
86    pub(super) async fn write(&mut self, bytes: Vec<u8>) -> Result<()> {
87        self.active
88            .as_mut()
89            .and_then(|f| f.writer.as_mut())
90            .ok_or_else(|| invalid("artifact output is not open"))?
91            .write(Bytes::from(bytes))
92            .await
93            .context(OpenDalSnafu)?;
94        Ok(())
95    }
96    pub(super) async fn close(&mut self) -> Result<()> {
97        let file = self
98            .active
99            .as_mut()
100            .ok_or_else(|| invalid("artifact output is not open"))?;
101        file.writer
102            .as_mut()
103            .ok_or_else(|| invalid("artifact output is closed"))?
104            .close()
105            .await
106            .context(OpenDalSnafu)?;
107        file.writer = None;
108        if let Some(upload) = &mut self.upload {
109            let path = file.path.strip_prefix(WriteCache::NARTHEX_STAGE).unwrap();
110            upload.upload_closed(path).await?;
111        }
112        self.active = None;
113        Ok(())
114    }
115    pub(crate) async fn commit(&mut self) {
116        if self.upload.is_some()
117            && let Some(dir) = self
118                .paths
119                .last()
120                .and_then(|p| crate::sst::location::parent_dir(p))
121        {
122            let _ = self.store.delete(dir).await;
123        }
124        self.committed = true;
125    }
126
127    pub(super) async fn cleanup(&mut self) -> Result<()> {
128        if let Some(upload) = &mut self.upload {
129            upload.clean().await;
130        }
131        let mut first_error = None;
132        if let Some(file) = self.active.as_mut()
133            && let Some(writer) = file.writer.as_mut()
134        {
135            match writer.abort().await {
136                Ok(()) => file.writer = None,
137                Err(error) => first_error = Some(OpenDalSnafu.into_error(error)),
138            }
139        }
140        self.active = None;
141        for path in &self.paths {
142            if let Err(error) = self.store.delete(path).await {
143                first_error.get_or_insert_with(|| OpenDalSnafu.into_error(error));
144            }
145        }
146        if first_error.is_none() {
147            let dirs: std::collections::BTreeSet<_> = self
148                .paths
149                .iter()
150                .filter_map(|path| crate::sst::location::parent_dir(path))
151                .collect();
152            for dir in dirs {
153                if let Err(error) = self.store.delete(dir).await {
154                    first_error.get_or_insert_with(|| OpenDalSnafu.into_error(error));
155                }
156            }
157        }
158        if let Some(error) = first_error {
159            Err(error)
160        } else {
161            self.committed = true;
162            Ok(())
163        }
164    }
165}
166impl Drop for Outputs {
167    fn drop(&mut self) {
168        if !self.committed {
169            let mut owned = Self {
170                store: self.store.clone(),
171                active: self.active.take(),
172                paths: std::mem::take(&mut self.paths),
173                committed: true,
174                upload: self.upload.take(),
175            };
176            common_runtime::spawn_compact(async move {
177                if let Err(error) = owned.cleanup().await {
178                    common_telemetry::warn!(error; "Cleaning unpublished format artifact");
179                }
180            });
181        }
182    }
183}
184
185#[cfg(test)]
186mod tests {
187    use super::*;
188
189    #[tokio::test]
190    async fn test_abort_removes_narthex_directory() {
191        let root = common_test_util::temp_dir::create_temp_dir("narthex-abort");
192        let store = ObjectStore::new(
193            object_store::services::Fs::default().root(root.path().to_str().unwrap()),
194        )
195        .unwrap();
196        let dir =
197            crate::sst::location::narthex_file_dir("region/", store_api::storage::FileId::random());
198        let mut outputs = Outputs {
199            store: store.clone(),
200            active: None,
201            paths: Vec::new(),
202            committed: false,
203            upload: None,
204        };
205        outputs.open(format!("{dir}part-0.samples")).await.unwrap();
206        outputs.write(vec![1, 2, 3]).await.unwrap();
207        outputs.close().await.unwrap();
208        assert!(root.path().join(&dir).is_dir());
209        outputs.cleanup().await.unwrap();
210        assert!(!root.path().join(&dir).exists());
211    }
212}