1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
// Copyright 2022 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use std::sync::Arc;
use std::sync::Mutex;

use time::OffsetDateTime;

use crate::ops::OpStat;
use crate::path::get_basename;
use crate::Accessor;
use crate::Object;
use crate::ObjectMetadata;
use crate::ObjectMode;

/// ObjectEntry is returned by `ObjectStream` or `ObjectIterate` during object list.
///
/// Users can check returning object entry's mode or convert into an object without overhead.
#[derive(Debug)]
pub struct ObjectEntry {
    acc: Arc<dyn Accessor>,
    path: String,
    meta: Arc<Mutex<ObjectMetadata>>,

    /// Complete means this object entry already carries all metadata
    /// that it could have. Don't call metadata anymore.
    ///
    /// # Safety
    ///
    /// It's safe to clone this value. Because complete will only transform
    /// into `true` and never change back.
    ///
    /// For the worse case, we cloned a `false` to new ObjectEntry. The cost
    /// is an extra stat.
    complete: AtomicBool,
}

impl Clone for ObjectEntry {
    fn clone(&self) -> Self {
        Self {
            acc: self.acc.clone(),
            path: self.path.clone(),
            meta: self.meta.clone(),
            // Read comments on this field.
            complete: self.complete.load(Ordering::Relaxed).into(),
        }
    }
}

/// ObjectEntry can convert into object without overhead.
impl From<ObjectEntry> for Object {
    fn from(d: ObjectEntry) -> Self {
        Object::new(d.acc, &d.path)
    }
}

impl ObjectEntry {
    /// Create a new object entry by its corresponding underlying storage.
    pub fn new(acc: Arc<dyn Accessor>, path: &str, meta: ObjectMetadata) -> ObjectEntry {
        debug_assert!(
            meta.mode().is_dir() == path.ends_with('/'),
            "mode {:?} not match with path {}",
            meta.mode(),
            path
        );

        ObjectEntry {
            acc,
            path: path.to_string(),
            meta: Arc::new(Mutex::new(meta)),
            complete: AtomicBool::default(),
        }
    }

    /// Set accessor for this entry.
    pub fn set_accessor(&mut self, acc: Arc<dyn Accessor>) {
        self.acc = acc;
    }

    /// Complete means this object entry already carries all metadata
    /// that it could have. Don't call metadata anymore.
    pub fn set_complete(&mut self) -> &mut Self {
        self.complete.store(true, Ordering::Relaxed);
        self
    }

    /// Complete means this object entry already carries all metadata
    /// that it could have. Don't call metadata anymore.
    pub fn with_complete(mut self) -> Self {
        self.complete = AtomicBool::new(true);
        self
    }

    /// Convert [`ObjectEntry`] into [`Object`].
    ///
    /// This function is the same with already implemented `From` trait.
    /// This function will make our users happier to avoid writing
    /// generic type parameter
    pub fn into_object(self) -> Object {
        self.into()
    }

    /// Return this object entry's object mode.
    pub fn mode(&self) -> ObjectMode {
        self.meta.lock().expect("lock must succeed").mode()
    }

    /// Return this object entry's id.
    ///
    /// The same with [`Object::id()`]
    pub fn id(&self) -> String {
        format!("{}{}", self.acc.metadata().root(), self.path)
    }

    /// Return this object entry's path.
    ///
    /// The same with [`Object::path()`]
    pub fn path(&self) -> &str {
        &self.path
    }

    /// Set path for this entry.
    pub fn set_path(&mut self, path: &str) {
        #[cfg(debug_assertions)]
        {
            let mode = self.meta.lock().expect("lock must succeed").mode();
            assert_eq!(
                mode.is_dir(),
                path.ends_with('/'),
                "mode {mode:?} not match with path {path}",
            );
        }

        self.path = path.to_string();
    }

    /// Return this object entry's name.
    ///
    /// The same with [`Object::name()`]
    pub fn name(&self) -> &str {
        get_basename(&self.path)
    }

    /// Fetch metadata about this object entry.
    pub async fn metadata(&self) -> ObjectMetadata {
        if !self.complete.load(Ordering::Relaxed) {
            // We will ignore all errors happened during inner metadata.
            if let Ok(meta) = self.acc.stat(self.path(), OpStat::new()).await {
                self.set_metadata(meta);
                self.complete.store(true, Ordering::Relaxed);
            }
        }

        self.meta.lock().expect("lock must succeed").clone()
    }

    /// Fetch metadata about this object entry.
    ///
    /// The same with [`Object::blocking_metadata()`]
    pub fn blocking_metadata(&self) -> ObjectMetadata {
        if !self.complete.load(Ordering::Relaxed) {
            // We will ignore all errors happened during inner metadata.
            if let Ok(meta) = self.acc.blocking_stat(self.path(), OpStat::new()) {
                self.set_metadata(meta);
                self.complete.store(true, Ordering::Relaxed);
            }
        }

        self.meta.lock().expect("lock must succeed").clone()
    }

    /// Update ObjectEntry's metadata by setting new one.
    pub fn set_metadata(&self, meta: ObjectMetadata) -> &Self {
        let mut guard = self.meta.lock().expect("lock must succeed");
        *guard = meta;
        self
    }

    /// The size of `ObjectEntry`'s corresponding object
    ///
    /// `content_length` is a prefetched metadata field in `ObjectEntry`.
    pub async fn content_length(&self) -> u64 {
        if let Some(v) = self
            .meta
            .lock()
            .expect("lock must succeed")
            .content_length_raw()
        {
            return v;
        }

        self.metadata()
            .await
            .content_length_raw()
            .unwrap_or_default()
    }

    /// The MD5 message digest of `ObjectEntry`'s corresponding object
    ///
    /// `content_md5` is a prefetched metadata field in `ObjectEntry`
    ///
    /// It doesn't mean this metadata field of object doesn't exist if `content_md5` is `None`.
    /// Then you have to call `ObjectEntry::metadata()` to get the metadata you want.
    pub async fn content_md5(&self) -> Option<String> {
        if let Some(v) = self.meta.lock().expect("lock must succeed").content_md5() {
            return Some(v.to_string());
        }

        self.metadata().await.content_md5().map(|v| v.to_string())
    }

    /// The last modified UTC datetime of `ObjectEntry`'s corresponding object
    ///
    /// `last_modified` is a prefetched metadata field in `ObjectEntry`
    ///
    /// It doesn't mean this metadata field of object doesn't exist if `last_modified` is `None`.
    /// Then you have to call `ObjectEntry::metadata()` to get the metadata you want.
    pub async fn last_modified(&self) -> Option<OffsetDateTime> {
        if let Some(v) = self.meta.lock().expect("lock must succeed").last_modified() {
            return Some(v);
        }

        self.metadata().await.last_modified()
    }

    /// The ETag string of `ObjectEntry`'s corresponding object
    ///
    /// `etag` is a prefetched metadata field in `ObjectEntry`.
    ///
    /// It doesn't mean this metadata field of object doesn't exist if `etag` is `None`.
    /// Then you have to call `ObjectEntry::metadata()` to get the metadata you want.
    pub async fn etag(&self) -> Option<String> {
        if let Some(v) = self.meta.lock().expect("lock must succeed").etag() {
            return Some(v.to_string());
        }

        self.metadata().await.etag().map(|v| v.to_string())
    }
}