object_storage_lib/
lib.rs1mod action;
2mod config;
3mod context;
4
5use async_trait::async_trait;
6pub use config::Config;
7pub use config::Oss;
8use context::Context;
9use headers::{ContentType, HeaderMapExt};
10use hyper;
11use hyper::body::Incoming;
12use hyper::{Request, Response, StatusCode};
13use object_storage_sdk as sdk;
14use sdk::storage::GetReq;
15use std::collections::HashMap;
16use std::net::SocketAddr;
17use std::sync::Arc;
18use tihu::SharedString;
19use tihu_native::http::Body;
20use tihu_native::http::BoxBody;
21use tihu_native::http::HttpHandler;
22use tihu_native::http::RequestData;
23
24pub struct GetMapping {
25 path_prefix: SharedString, key_prefix: SharedString, }
28
29pub struct UploadMapping {
30 path: SharedString, key_prefix: SharedString, }
33
34pub struct OssHandler {
35 context: Arc<Context>,
36 get_mapping: Vec<GetMapping>,
37 upload_mapping: Vec<UploadMapping>,
38 delete_path: Option<SharedString>,
39 namespaces: Vec<SharedString>,
40}
41
42impl OssHandler {
43 pub async fn try_init_from_config(
44 config: Config,
45 adjust_error_code: impl Fn(i32) -> i32 + Send + Sync + 'static,
46 ) -> Result<Self, anyhow::Error> {
47 let context = Context::try_init_from_config(config, adjust_error_code)?;
48 let context = Arc::new(context);
49 return Ok(Self {
50 context: context,
51 get_mapping: Vec::new(),
52 upload_mapping: Vec::new(),
53 delete_path: None,
54 namespaces: Vec::new(),
55 });
56 }
57
58 pub fn add_get_mapping(
59 &mut self,
60 path_prefix: SharedString,
61 key_prefix: SharedString,
62 ) -> &mut Self {
63 self.get_mapping.push(GetMapping {
64 path_prefix: path_prefix.clone(),
65 key_prefix: key_prefix,
66 });
67 self.namespaces.push(path_prefix);
68 return self;
69 }
70
71 pub fn add_upload_mapping(
72 &mut self,
73 path: SharedString,
74 key_prefix: SharedString,
75 ) -> &mut Self {
76 self.upload_mapping.push(UploadMapping {
77 path: path.clone(),
78 key_prefix: key_prefix,
79 });
80 self.namespaces.push(path);
81 return self;
82 }
83
84 pub fn set_delete_path(&mut self, delete_path: SharedString) -> &mut Self {
85 self.delete_path.replace(delete_path.clone());
86 self.namespaces.push(delete_path);
87 return self;
88 }
89
90 pub async fn delete_file(
91 &self,
92 full_key: &str,
93 ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
94 action::storage::delete_file(&self.context, full_key).await
95 }
96}
97
98#[async_trait]
99impl HttpHandler for OssHandler {
100 fn namespace(&self) -> &[SharedString] {
101 return &self.namespaces;
102 }
103 async fn handle(
104 &self,
105 request: Request<Incoming>,
106 _remote_addr: SocketAddr,
107 _request_data: &mut RequestData,
108 prefix: Option<&str>,
109 ) -> Result<Response<BoxBody>, anyhow::Error> {
110 let prefix = prefix.unwrap_or("");
111 let (_, route) = request.uri().path().split_at(prefix.len());
112 for get_mapping in &self.get_mapping {
113 let path_prefix = &get_mapping.path_prefix;
114 let key_prefix = &get_mapping.key_prefix;
115 if route.starts_with(path_prefix.as_ref()) {
116 let key = format!(
117 "{}{}",
118 key_prefix,
119 String::from_utf8_lossy(&route.as_bytes()[path_prefix.len()..])
120 );
121 if key.is_empty() {
122 let mut response = text_response("file not found!");
123 *response.status_mut() = StatusCode::NOT_FOUND;
124 return Ok(response.map(From::from));
125 } else {
126 let query = request
127 .uri()
128 .query()
129 .map(|query| {
130 form_urlencoded::parse(query.as_bytes()).collect::<HashMap<_, _>>()
131 })
132 .unwrap_or_default();
133 let filename = query.get("filename").map(|filename| filename.as_ref());
134 let response =
135 action::storage::get(self.context.clone(), GetReq { key: key }, filename)
136 .await?;
137 return Ok(response.map(From::from));
138 }
139 }
140 }
141
142 for upload_mapping in &self.upload_mapping {
143 let path = &upload_mapping.path;
144 let key_prefix = &upload_mapping.key_prefix;
145 if route == path.as_ref() {
146 let hash = request.headers().get("X-Hash");
147 let hash = hash
148 .map(|hash| hash.to_str().map(|hash| hash.to_string()).ok())
149 .flatten();
150 if let Some(hash) = hash {
151 let response =
152 action::storage::put(self.context.clone(), request, key_prefix, hash)
153 .await?;
154 return Ok(response.map(From::from));
155 } else {
156 let response = Response::builder()
157 .status(StatusCode::BAD_REQUEST)
158 .body(Body::from("BAD REQUEST"))
159 .unwrap();
160 return Ok(response.map(From::from));
161 }
162 }
163 }
164
165 if let Some(delete_path) = self.delete_path.as_ref() {
166 if route == delete_path.as_ref() {
167 let hash = request.headers().get("X-Hash");
168 let hash = hash
169 .map(|hash| hash.to_str().map(|hash| hash.to_string()).ok())
170 .flatten();
171 if let Some(hash) = hash {
172 let response =
173 action::storage::delete(self.context.clone(), request, hash).await?;
174 return Ok(response.map(From::from));
175 } else {
176 let response = Response::builder()
177 .status(StatusCode::BAD_REQUEST)
178 .body(Body::from("BAD REQUEST"))
179 .unwrap();
180 return Ok(response.map(From::from));
181 }
182 }
183 }
184 let mut response = text_response("file not found!");
185 *response.status_mut() = StatusCode::NOT_FOUND;
186 return Ok(response.map(From::from));
187 }
188}
189
190fn text_response<T: Into<Body>>(body: T) -> Response<Body> {
191 let mut response = Response::new(body.into());
192 response
193 .headers_mut()
194 .typed_insert(ContentType::text_utf8());
195 return response;
196}