1use std::iter;
2use std::time::Duration;
3
4use jiff::Timestamp;
5use md5::{Digest as _, Md5};
6use serde::{Deserialize, Serialize};
7use url::Url;
8
9use crate::actions::Method;
10use crate::actions::S3Action;
11use crate::signing::sign;
12use crate::sorting_iter::SortingIterator;
13use crate::{Bucket, Credentials, Map};
14
15#[derive(Debug, Clone)]
21pub struct DeleteObjects<'a, I> {
22 bucket: &'a Bucket,
23 credentials: Option<&'a Credentials>,
24 objects: I,
25 quiet: bool,
26
27 query: Map<'a>,
28 headers: Map<'a>,
29}
30
31impl<'a, I> DeleteObjects<'a, I> {
32 #[inline]
33 pub const fn new(bucket: &'a Bucket, credentials: Option<&'a Credentials>, objects: I) -> Self {
34 Self {
35 bucket,
36 credentials,
37 objects,
38 quiet: false,
39 query: Map::new(),
40 headers: Map::new(),
41 }
42 }
43
44 pub const fn quiet(&self) -> bool {
45 self.quiet
46 }
47
48 pub fn set_quiet(&mut self, quiet: bool) {
49 self.quiet = quiet;
50 }
51}
52
53#[derive(Debug, Clone, Default)]
54pub struct ObjectIdentifier {
55 pub key: String,
56 pub version_id: Option<String>,
57}
58
59impl ObjectIdentifier {
60 #[must_use]
61 pub fn new(key: String) -> Self {
62 Self {
63 key,
64 ..Default::default()
65 }
66 }
67}
68
69#[derive(Debug, Clone, Deserialize)]
70pub struct DeleteObjectsResponse {
71 #[serde(rename = "Deleted", default)]
72 pub deleted: Vec<DeletedObject>,
73 #[serde(rename = "Error", default)]
74 pub errors: Vec<ErrorObject>,
75}
76
77#[derive(Debug, Clone, Deserialize)]
78pub struct DeletedObject {
79 #[serde(rename = "Key")]
80 pub key: String,
81 #[serde(rename = "VersionId")]
82 pub version_id: Option<String>,
83 #[serde(rename = "DeleteMarker")]
84 pub delete_marker: Option<bool>,
85 #[serde(rename = "DeleteMarkerVersionId")]
86 pub delete_marker_version_id: Option<String>,
87}
88
89#[derive(Debug, Clone, Deserialize)]
90pub struct ErrorObject {
91 #[serde(rename = "Key")]
92 pub key: String,
93 #[serde(rename = "VersionId")]
94 pub version_id: Option<String>,
95 #[serde(rename = "Code")]
96 pub code: String,
97 #[serde(rename = "Message")]
98 pub message: String,
99}
100
101impl DeleteObjectsResponse {
102 pub fn parse(s: impl AsRef<[u8]>) -> Result<Self, quick_xml::DeError> {
108 quick_xml::de::from_reader(s.as_ref())
109 }
110}
111
112impl<'a, I> DeleteObjects<'a, I>
113where
114 I: Iterator<Item = &'a ObjectIdentifier>,
115{
116 pub fn body_with_md5(self) -> (String, String) {
122 #[derive(Serialize)]
123 #[serde(rename = "Delete")]
124 struct DeleteSerde<'a> {
125 #[serde(rename = "Object")]
126 objects: Vec<Object<'a>>,
127 #[serde(rename = "Quiet")]
128 quiet: Option<bool>,
129 }
130 #[derive(Serialize)]
131 #[serde(rename = "Delete")]
132 struct Object<'a> {
133 #[serde(rename = "$value")]
134 nodes: Vec<Node<'a>>,
135 }
136
137 #[derive(Serialize)]
138 enum Node<'a> {
139 Key(&'a str),
140 VersionId(&'a str),
141 }
142
143 let objects: Vec<Object<'a>> = self
144 .objects
145 .map(|o| {
146 let mut nodes = vec![Node::Key(o.key.as_str())];
147 if let Some(version_id) = &o.version_id {
148 nodes.push(Node::VersionId(version_id.as_str()));
149 }
150 Object { nodes }
151 })
152 .collect();
153
154 let req = DeleteSerde {
155 objects,
156 quiet: self.quiet.then_some(true),
157 };
158
159 let body = quick_xml::se::to_string(&req).unwrap();
160
161 let content_md5 = crate::base64::encode(Md5::digest(body.as_bytes()));
162 (body, content_md5)
163 }
164}
165
166impl<'a, I> S3Action<'a> for DeleteObjects<'a, I>
167where
168 I: Iterator<Item = &'a ObjectIdentifier>,
169{
170 const METHOD: Method = Method::Post;
171
172 fn query_mut(&mut self) -> &mut Map<'a> {
173 &mut self.query
174 }
175
176 fn headers_mut(&mut self) -> &mut Map<'a> {
177 &mut self.headers
178 }
179
180 fn sign_with_time(&self, expires_in: Duration, time: &Timestamp) -> Url {
181 let url = self.bucket.base_url().clone();
182 let query = SortingIterator::new(iter::once(("delete", "1")), self.query.iter());
183
184 match self.credentials {
185 Some(credentials) => sign(
186 time,
187 Self::METHOD,
188 url,
189 credentials.key(),
190 credentials.secret(),
191 credentials.token(),
192 self.bucket.region(),
193 expires_in.as_secs(),
194 query,
195 self.headers.iter(),
196 ),
197 None => crate::signing::util::add_query_params(url, query),
198 }
199 }
200}
201
202#[cfg(test)]
203mod tests {
204 use pretty_assertions::assert_eq;
205
206 use crate::{Bucket, Credentials, UrlStyle};
207
208 use super::*;
209
210 #[test]
211 fn aws_example() {
212 let date = Timestamp::from_second(1369353600).unwrap();
214 let expires_in = Duration::from_secs(86400);
215
216 let endpoint = "https://s3.amazonaws.com".parse().unwrap();
217 let bucket = Bucket::new(
218 endpoint,
219 UrlStyle::VirtualHost,
220 "examplebucket",
221 "us-east-1",
222 )
223 .unwrap();
224 let credentials = Credentials::new(
225 "AKIAIOSFODNN7EXAMPLE",
226 "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",
227 );
228
229 let objects = [
230 ObjectIdentifier {
231 key: "123".to_owned(),
232 ..Default::default()
233 },
234 ObjectIdentifier {
235 key: "456".to_owned(),
236 version_id: Some("ver1234".to_owned()),
237 },
238 ];
239 let action = DeleteObjects::new(&bucket, Some(&credentials), objects.iter());
240
241 let url = action.sign_with_time(expires_in, &date);
242 let expected = "https://examplebucket.s3.amazonaws.com/?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIOSFODNN7EXAMPLE%2F20130524%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20130524T000000Z&X-Amz-Expires=86400&X-Amz-SignedHeaders=host&delete=1&X-Amz-Signature=0e6170ba8cb7873da76b7fb63638658607f484265935099b3d8cea5195af843c";
243
244 assert_eq!(expected, url.as_str());
245 }
246
247 #[test]
248 fn anonymous_custom_query() {
249 let expires_in = Duration::from_secs(86400);
250
251 let endpoint = "https://s3.amazonaws.com".parse().unwrap();
252 let bucket = Bucket::new(
253 endpoint,
254 UrlStyle::VirtualHost,
255 "examplebucket",
256 "us-east-1",
257 )
258 .unwrap();
259
260 let objects = [
261 ObjectIdentifier {
262 key: "123".to_owned(),
263 ..Default::default()
264 },
265 ObjectIdentifier {
266 key: "456".to_owned(),
267 version_id: Some("ver1234".to_owned()),
268 },
269 ];
270 let action = DeleteObjects::new(&bucket, None, objects.iter());
271 let url = action.sign(expires_in);
272 let expected = "https://examplebucket.s3.amazonaws.com/?delete=1";
273
274 assert_eq!(expected, url.as_str());
275 }
276
277 #[test]
278 fn parse_response_success() {
279 let input = r#"
280 <?xml version="1.0" encoding="UTF-8"?>
281 <DeleteResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
282 <Deleted>
283 <Key>duck.jpg</Key>
284 <VersionId>ver1234</VersionId>
285 <DeleteMarker>true</DeleteMarker>
286 <DeleteMarkerVersionId>del1234</DeleteMarkerVersionId>
287 </Deleted>
288 <Deleted>
289 <Key>duck2.jpg</Key>
290 </Deleted>
291 </DeleteResult>
292 "#;
293
294 let parsed = DeleteObjectsResponse::parse(input).unwrap();
295 assert_eq!(parsed.deleted.len(), 2);
296 assert_eq!(parsed.errors.len(), 0);
297
298 let deleted = &parsed.deleted[0];
299 assert_eq!(deleted.key, "duck.jpg");
300 assert_eq!(deleted.version_id, Some("ver1234".to_string()));
301 assert_eq!(deleted.delete_marker, Some(true));
302 assert_eq!(
303 deleted.delete_marker_version_id,
304 Some("del1234".to_string())
305 );
306
307 let deleted = &parsed.deleted[1];
308 assert_eq!(deleted.key, "duck2.jpg");
309 assert!(deleted.version_id.is_none());
310 assert!(deleted.delete_marker.is_none());
311 assert!(deleted.delete_marker_version_id.is_none());
312 }
313
314 #[test]
315 fn parse_response_errors() {
316 let input = r#"
317 <?xml version="1.0" encoding="UTF-8"?>
318 <DeleteResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
319 <Error>
320 <Key>idk.txt</Key>
321 <Code>ErrorCode</Code>
322 <Message>Error message</Message>
323 </Error>
324 <Error>
325 <Key>idk2.txt</Key>
326 <VersionId>ver2</VersionId>
327 <Code>ErrorCode2</Code>
328 <Message>Error message 2</Message>
329 </Error>
330 </DeleteResult>
331 "#;
332
333 let parsed = DeleteObjectsResponse::parse(input).unwrap();
334 assert_eq!(parsed.deleted.len(), 0);
335 assert_eq!(parsed.errors.len(), 2);
336
337 let error = &parsed.errors[0];
338 assert_eq!(error.key, "idk.txt");
339 assert!(error.version_id.is_none());
340 assert_eq!(error.code, "ErrorCode");
341 assert_eq!(error.message, "Error message");
342
343 let error = &parsed.errors[1];
344 assert_eq!(error.key, "idk2.txt");
345 assert_eq!(error.version_id, Some("ver2".to_string()));
346 assert_eq!(error.code, "ErrorCode2");
347 assert_eq!(error.message, "Error message 2");
348 }
349}