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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
// 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::collections::HashMap;
use std::collections::HashSet;
use std::io::Error;
use std::io::ErrorKind;
use std::io::Result;
use std::mem;
use std::pin::Pin;
use std::sync::Arc;
use std::task::Context;
use std::task::Poll;

use anyhow::anyhow;
use async_trait::async_trait;
use bytes::BufMut;
use bytes::Bytes;
use futures::io::Cursor;
use futures::AsyncWrite;
use parking_lot::Mutex;

use crate::accessor::AccessorCapability;
use crate::error::new_other_object_error;
use crate::error::ObjectError;
use crate::ops::OpCreate;
use crate::ops::OpDelete;
use crate::ops::OpList;
use crate::ops::OpRead;
use crate::ops::OpStat;
use crate::ops::OpWrite;
use crate::ops::Operation;
use crate::Accessor;
use crate::AccessorMetadata;
use crate::BytesReader;
use crate::ObjectEntry;
use crate::ObjectMetadata;
use crate::ObjectMode;
use crate::ObjectStreamer;
use crate::Scheme;

/// Builder for memory backend
#[derive(Default)]
pub struct Builder {}

impl Builder {
    /// Consume builder to build a memory backend.
    pub fn build(&mut self) -> Result<Backend> {
        Ok(Backend {
            inner: Arc::new(Mutex::new(HashMap::default())),
        })
    }
}

/// Backend is used to serve `Accessor` support in memory.
#[derive(Debug, Clone)]
pub struct Backend {
    inner: Arc<Mutex<HashMap<String, Bytes>>>,
}

#[async_trait]
impl Accessor for Backend {
    fn metadata(&self) -> AccessorMetadata {
        let mut am = AccessorMetadata::default();
        am.set_scheme(Scheme::Memory)
            .set_root("/")
            .set_name(&format!("{:?}", &self.inner as *const _))
            .set_capabilities(
                AccessorCapability::Read | AccessorCapability::Write | AccessorCapability::List,
            );

        am
    }

    async fn create(&self, path: &str, args: OpCreate) -> Result<()> {
        match args.mode() {
            ObjectMode::FILE => {
                let mut map = self.inner.lock();
                map.insert(path.to_string(), Bytes::new());

                Ok(())
            }
            ObjectMode::DIR => {
                let mut map = self.inner.lock();
                map.insert(path.to_string(), Bytes::new());

                Ok(())
            }
            _ => unreachable!(),
        }
    }

    async fn read(&self, path: &str, args: OpRead) -> Result<BytesReader> {
        let map = self.inner.lock();

        let data = map.get(path).ok_or_else(|| {
            Error::new(
                ErrorKind::NotFound,
                ObjectError::new(Operation::Read, path, anyhow!("key not exists in map")),
            )
        })?;

        let mut data = data.clone();
        if let Some(offset) = args.offset() {
            if offset >= data.len() as u64 {
                return Err(new_other_object_error(
                    Operation::Read,
                    path,
                    anyhow!("offset out of bound {} >= {}", offset, data.len()),
                ));
            }
            data = data.slice(offset as usize..data.len());
        };

        if let Some(size) = args.size() {
            if size > data.len() as u64 {
                return Err(new_other_object_error(
                    Operation::Read,
                    path,
                    anyhow!("size out of bound {} > {}", size, data.len()),
                ));
            }
            data = data.slice(0..size as usize);
        };

        Ok(Box::new(Cursor::new(data)))
    }

    async fn write(&self, path: &str, args: OpWrite, r: BytesReader) -> Result<u64> {
        let mut buf = Vec::with_capacity(args.size() as usize);
        let n = futures::io::copy(r, &mut buf).await?;
        if n != args.size() {
            return Err(new_other_object_error(
                Operation::Write,
                path,
                anyhow!("write short, expect {} actual {}", args.size(), n),
            ));
        }
        let mut map = self.inner.lock();
        map.insert(path.to_string(), Bytes::from(buf));

        Ok(n)
    }

    async fn stat(&self, path: &str, _: OpStat) -> Result<ObjectMetadata> {
        if path.ends_with('/') {
            return Ok(ObjectMetadata::new(ObjectMode::DIR));
        }

        let map = self.inner.lock();

        let data = map.get(path).ok_or_else(|| {
            Error::new(
                ErrorKind::NotFound,
                ObjectError::new(Operation::Read, path, anyhow!("key not exists in map")),
            )
        })?;

        let meta = ObjectMetadata::new(ObjectMode::FILE).with_content_length(data.len() as u64);

        Ok(meta)
    }

    async fn delete(&self, path: &str, _: OpDelete) -> Result<()> {
        let mut map = self.inner.lock();
        map.remove(path);

        Ok(())
    }

    async fn list(&self, path: &str, _: OpList) -> Result<ObjectStreamer> {
        let mut path = path.to_string();
        if path == "/" {
            path.clear();
        }

        let map = self.inner.lock();

        let paths = map
            .iter()
            // Make sure k is at the same level with input path.
            .filter_map(|(k, _)| {
                let k = k.as_str();
                // `/xyz` should not belong to `/abc`
                if !k.starts_with(&path) {
                    return None;
                }

                // We should remove `/abc` if self
                if k == path {
                    return None;
                }

                match k[path.len()..].find('/') {
                    // File `/abc/def.csv` must belong to `/abc`
                    None => Some(k.to_string()),
                    Some(idx) => {
                        // The index of first `/` after `/abc`.
                        let dir_idx = idx + 1 + path.len();

                        if dir_idx == k.len() {
                            // Dir `/abc/def/` belongs to `/abc/`
                            Some(k.to_string())
                        } else {
                            // File/Dir `/abc/def/xyz` deoesn't belongs to `/abc`.
                            // But we need to list `/abc/def` out so that we can walk down.
                            Some(k[..dir_idx].to_string())
                        }
                    }
                }
            })
            .collect::<HashSet<_>>();

        Ok(Box::new(DirStream {
            backend: Arc::new(self.clone()),
            paths: paths.into_iter().collect(),
            idx: 0,
        }))
    }
}

struct MapWriter {
    path: String,
    size: u64,
    map: Arc<Mutex<HashMap<String, Bytes>>>,

    buf: bytes::BytesMut,
}

impl AsyncWrite for MapWriter {
    fn poll_write(
        mut self: Pin<&mut Self>,
        _cx: &mut Context<'_>,
        buf: &[u8],
    ) -> Poll<Result<usize>> {
        let size = buf.len();
        self.buf.put_slice(buf);
        Poll::Ready(Ok(size))
    }

    fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Result<()>> {
        Poll::Ready(Ok(()))
    }

    fn poll_close(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Result<()>> {
        if self.buf.len() != self.size as usize {
            return Poll::Ready(Err(new_other_object_error(
                Operation::Write,
                &self.path,
                anyhow!(
                    "write short, expect {} actual {}",
                    self.size,
                    self.buf.len()
                ),
            )));
        }

        let buf = mem::take(&mut self.buf);
        let mut map = self.map.lock();
        map.insert(self.path.clone(), buf.freeze());

        Poll::Ready(Ok(()))
    }
}

struct DirStream {
    backend: Arc<Backend>,
    paths: Vec<String>,
    idx: usize,
}

impl futures::Stream for DirStream {
    type Item = Result<ObjectEntry>;

    fn poll_next(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        if self.idx >= self.paths.len() {
            return Poll::Ready(None);
        }

        let idx = self.idx;
        self.idx += 1;

        let path = self.paths.get(idx).expect("path must valid");

        let de = if path.ends_with('/') {
            ObjectEntry::new(
                self.backend.clone(),
                path,
                ObjectMetadata::new(ObjectMode::DIR),
            )
            .with_complete()
        } else {
            ObjectEntry::new(
                self.backend.clone(),
                path,
                ObjectMetadata::new(ObjectMode::FILE),
            )
        };

        Poll::Ready(Some(Ok(de)))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_accessor_metadata_name() {
        let b1 = Builder::default().build().unwrap();
        assert_eq!(b1.metadata().name(), b1.metadata().name());

        let b2 = Builder::default().build().unwrap();
        assert_ne!(b1.metadata().name(), b2.metadata().name())
    }
}