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
use {
crate::{
error::{DebianError, Result},
io::{ContentDigest, MultiDigester},
repository::{
RepositoryPathVerification, RepositoryPathVerificationState, RepositoryWrite,
RepositoryWriter,
},
},
async_trait::async_trait,
futures::{AsyncRead, AsyncReadExt as FuturesAsyncReadExt},
rusoto_core::{ByteStream, Client, Region, RusotoError},
rusoto_s3::{
GetBucketLocationRequest, GetObjectError, GetObjectRequest, HeadObjectError,
HeadObjectRequest, PutObjectRequest, S3Client, S3,
},
std::{borrow::Cow, pin::Pin, str::FromStr},
tokio::io::AsyncReadExt as TokioAsyncReadExt,
};
pub struct S3Writer {
client: S3Client,
bucket: String,
key_prefix: Option<String>,
}
impl S3Writer {
pub fn new(region: Region, bucket: impl ToString, key_prefix: Option<&str>) -> Self {
Self {
client: S3Client::new(region),
bucket: bucket.to_string(),
key_prefix: key_prefix.map(|x| x.trim_matches('/').to_string()),
}
}
pub fn new_with_client(
client: Client,
region: Region,
bucket: impl ToString,
key_prefix: Option<&str>,
) -> Self {
Self {
client: S3Client::new_with_client(client, region),
bucket: bucket.to_string(),
key_prefix: key_prefix.map(|x| x.trim_matches('/').to_string()),
}
}
pub fn path_to_key(&self, path: &str) -> String {
if let Some(prefix) = &self.key_prefix {
format!("{}/{}", prefix, path.trim_matches('/'))
} else {
path.trim_matches('/').to_string()
}
}
}
#[async_trait]
impl RepositoryWriter for S3Writer {
async fn verify_path<'path>(
&self,
path: &'path str,
expected_content: Option<(u64, ContentDigest)>,
) -> Result<RepositoryPathVerification<'path>> {
if let Some((expected_size, expected_digest)) = expected_content {
let req = GetObjectRequest {
bucket: self.bucket.clone(),
key: self.path_to_key(path),
..Default::default()
};
match self.client.get_object(req).await {
Ok(output) => {
if let Some(cl) = output.content_length {
if cl as u64 != expected_size {
return Ok(RepositoryPathVerification {
path,
state: RepositoryPathVerificationState::ExistsIntegrityMismatch,
});
}
}
if let Some(body) = output.body {
let mut digester = MultiDigester::default();
let mut remaining = expected_size;
let mut reader = body.into_async_read();
let mut buf = [0u8; 16384];
loop {
let size = reader
.read(&mut buf[..])
.await
.map_err(|e| DebianError::RepositoryIoPath(path.to_string(), e))?;
digester.update(&buf[0..size]);
let size = size as u64;
if size >= remaining || size == 0 {
break;
}
remaining -= size;
}
let digests = digester.finish();
Ok(RepositoryPathVerification {
path,
state: if !digests.matches_digest(&expected_digest) {
RepositoryPathVerificationState::ExistsIntegrityMismatch
} else {
RepositoryPathVerificationState::ExistsIntegrityVerified
},
})
} else {
Ok(RepositoryPathVerification {
path,
state: RepositoryPathVerificationState::Missing,
})
}
}
Err(RusotoError::Service(GetObjectError::NoSuchKey(_))) => {
Ok(RepositoryPathVerification {
path,
state: RepositoryPathVerificationState::Missing,
})
}
Err(e) => Err(DebianError::RepositoryIoPath(
path.to_string(),
std::io::Error::new(std::io::ErrorKind::Other, format!("S3 error: {:?}", e)),
)),
}
} else {
let req = HeadObjectRequest {
bucket: self.bucket.clone(),
key: self.path_to_key(path),
..Default::default()
};
match self.client.head_object(req).await {
Ok(_) => Ok(RepositoryPathVerification {
path,
state: RepositoryPathVerificationState::ExistsNoIntegrityCheck,
}),
Err(RusotoError::Service(HeadObjectError::NoSuchKey(_))) => {
Ok(RepositoryPathVerification {
path,
state: RepositoryPathVerificationState::Missing,
})
}
Err(e) => Err(DebianError::RepositoryIoPath(
path.to_string(),
std::io::Error::new(std::io::ErrorKind::Other, format!("S3 error: {:?}", e)),
)),
}
}
}
async fn write_path<'path, 'reader>(
&self,
path: Cow<'path, str>,
mut reader: Pin<Box<dyn AsyncRead + Send + 'reader>>,
) -> Result<RepositoryWrite<'path>> {
let mut buf = vec![];
reader
.read_to_end(&mut buf)
.await
.map_err(|e| DebianError::RepositoryIoPath(path.to_string(), e))?;
let bytes_written = buf.len() as u64;
let stream = futures::stream::once(async { Ok(bytes::Bytes::from(buf)) });
let req = PutObjectRequest {
bucket: self.bucket.clone(),
key: self.path_to_key(path.as_ref()),
body: Some(ByteStream::new(stream)),
..Default::default()
};
match self.client.put_object(req).await {
Ok(_) => Ok(RepositoryWrite {
path,
bytes_written,
}),
Err(e) => Err(DebianError::RepositoryIoPath(
path.to_string(),
std::io::Error::new(std::io::ErrorKind::Other, format!("S3 error: {:?}", e)),
)),
}
}
}
pub async fn get_bucket_region(bucket: impl ToString) -> Result<Region> {
get_bucket_region_with_client(S3Client::new(Region::UsEast1), bucket).await
}
pub async fn get_bucket_region_with_client(
client: S3Client,
bucket: impl ToString,
) -> Result<Region> {
let req = GetBucketLocationRequest {
bucket: bucket.to_string(),
..Default::default()
};
match client.get_bucket_location(req).await {
Ok(res) => {
if let Some(constraint) = res.location_constraint {
Ok(Region::from_str(&constraint)
.map_err(|_| DebianError::S3BadRegion(constraint))?)
} else {
Ok(Region::UsEast1)
}
}
Err(e) => Err(DebianError::Io(std::io::Error::new(
std::io::ErrorKind::Other,
format!("S3 error: {:?}", e),
))),
}
}