Skip to main content

object_store/
test_util.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
15use crate::{ObjectStore, Result};
16
17/// Temp folder for object store test
18pub struct TempFolder {
19    store: ObjectStore,
20    // The path under root.
21    path: String,
22}
23
24impl TempFolder {
25    pub fn new(store: &ObjectStore, path: &str) -> Self {
26        Self {
27            store: store.clone(),
28            path: path.to_string(),
29        }
30    }
31
32    pub async fn remove_all(&self) -> Result<()> {
33        self.store.delete_with(&self.path).recursive(true).await
34    }
35}
36
37/// A minimal HTTP/1.1 server for object storage tests. Every connection serves
38/// one request; the handler builds the raw response from the request head.
39pub struct MockHttpServer {
40    pub port: u16,
41    request_heads: std::sync::Arc<std::sync::Mutex<Vec<String>>>,
42}
43
44impl MockHttpServer {
45    pub async fn start(handler: impl Fn(&str) -> String + Send + Sync + 'static) -> Self {
46        use tokio::io::{AsyncReadExt, AsyncWriteExt};
47
48        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
49        let port = listener.local_addr().unwrap().port();
50        let request_heads = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
51        let recorded = request_heads.clone();
52        let handler = std::sync::Arc::new(handler);
53        tokio::spawn(async move {
54            while let Ok((mut stream, _)) = listener.accept().await {
55                let recorded = recorded.clone();
56                let handler = handler.clone();
57                tokio::spawn(async move {
58                    let mut buf = Vec::new();
59                    let mut chunk = [0u8; 4096];
60                    let head_end = loop {
61                        let n = stream.read(&mut chunk).await.unwrap_or(0);
62                        if n == 0 {
63                            return;
64                        }
65                        buf.extend_from_slice(&chunk[..n]);
66                        if let Some(pos) = buf.windows(4).position(|w| w == b"\r\n\r\n") {
67                            break pos + 4;
68                        }
69                    };
70                    let head = String::from_utf8_lossy(&buf[..head_end]).to_string();
71                    let content_length = head
72                        .lines()
73                        .find_map(|line| {
74                            let (name, value) = line.split_once(':')?;
75                            name.eq_ignore_ascii_case("content-length")
76                                .then(|| value.trim().parse::<usize>().ok())?
77                        })
78                        .unwrap_or(0);
79                    while buf.len() < head_end + content_length {
80                        let n = stream.read(&mut chunk).await.unwrap_or(0);
81                        if n == 0 {
82                            break;
83                        }
84                        buf.extend_from_slice(&chunk[..n]);
85                    }
86                    recorded.lock().unwrap().push(head.clone());
87                    let response = handler(&head);
88                    let _ = stream.write_all(response.as_bytes()).await;
89                    let _ = stream.shutdown().await;
90                });
91            }
92        });
93        Self {
94            port,
95            request_heads,
96        }
97    }
98
99    /// Request lines and headers of the requests received so far.
100    pub fn request_heads(&self) -> Vec<String> {
101        self.request_heads.lock().unwrap().clone()
102    }
103
104    pub fn request_count(&self) -> usize {
105        self.request_heads.lock().unwrap().len()
106    }
107}
108
109/// Builds a raw HTTP/1.1 response that closes the connection.
110pub fn http_response(status: &str, headers: &[(&str, String)], body: &str) -> String {
111    let mut out = format!("HTTP/1.1 {status}\r\nconnection: close\r\n");
112    for (name, value) in headers {
113        out.push_str(&format!("{name}: {value}\r\n"));
114    }
115    out.push_str(&format!("content-length: {}\r\n\r\n{body}", body.len()));
116    out
117}