-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathevent.rs
298 lines (277 loc) · 10.2 KB
/
event.rs
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
use crate::Record;
use reqwest::Method;
use std::borrow::Cow;
use std::sync::Arc;
use tokio::fs::File;
use tokio::io::AsyncReadExt;
use tokio::task::JoinHandle;
use tracing::info;
use std::fs;
use std::io::Read;
#[derive(Debug)]
pub struct Event {
pub record: Record,
step: usize,
joins: Vec<JoinHandle<()>>,
contents: &'static mut Vec<u8>,
contents_leak: Option<Arc<&'static [u8]>>
}
impl Event {
pub async fn run(&mut self) -> Result<(), crate::Error> {
match &self.record.body {
crate::Body::MULTIPART { path, name } => {
let filename = path.rsplit_once("/").unwrap_or(("", path)).1;
let mut file = File::open(path).await?;
let mut contents = vec![];
file.read_to_end(&mut contents).await?;
let mime_type = infer::get(&contents).map_or("text/plain", |mime| mime.mime_type());
for step in (self.record.start..self.record.end).step_by(self.step) {
let c = contents.clone();
let r = self.record.clone();
let n = name.clone();
let m = mime_type.to_string();
let f = filename.to_string();
info!("Step {step} of {:?}", r);
let join = tokio::spawn(async move {
let response = Self::send_file(
r.method.clone(),
format!("{:}{:}", r.host, r.path),
n,
m.into(),
f.into(),
c.into(),
)
.await;
match response {
Ok(resp) => info!("Status of {:?}: {}", r, resp.status()),
Err(err) => info!("Error with step {step} of {:?}: {err}", r),
}
});
tokio::time::sleep(tokio::time::Duration::from_secs(self.step as u64)).await;
self.joins.push(join);
}
}
}
Ok(())
}
pub async fn run_leak(&mut self) -> Result<(), crate::Error> {
match &self.record.body {
crate::Body::MULTIPART { path, name } => {
let filename = path.rsplit_once("/").unwrap_or(("", path)).1;
let mut file = File::open(path).await?;
let mut contents = vec![];
file.read_to_end(&mut contents).await?;
let contents: Arc<&'static [u8]> = Arc::new(Box::leak(contents.into_boxed_slice()));
self.contents_leak = Some(contents.clone());
let mime_type = infer::get(&contents).map_or("text/plain", |mime| mime.mime_type());
for step in (self.record.start..self.record.end).step_by(self.step) {
let r = self.record.clone();
let n = name.clone();
let c = contents.clone();
let m = mime_type.to_string();
let f = filename.to_string();
info!("Step {step} of {:?}", r);
let join = tokio::spawn(async move {
let response = Self::send_file_leak(
r.method.clone(),
format!("{:}{:}", r.host, r.path),
n,
m.into(),
f.into(),
c
)
.await;
match response {
Ok(resp) => info!("Status of {:?}: {}", r, resp.status()),
Err(err) => info!("Error with step {step} of {:?}: {err}", r),
}
});
tokio::time::sleep(tokio::time::Duration::from_secs(self.step as u64)).await;
self.joins.push(join);
}
}
}
Ok(())
}
pub async fn run_unsafe(self: Arc<&'static Self>) -> Result<(), crate::Error> {
let foo = self.clone();
match &foo.record.body {
crate::Body::MULTIPART { ref path, name } => {
let filename = path.rsplit_once("/").unwrap_or(("", path)).1.to_string();
let mut file = fs::File::open(path)?;
unsafe {
let a = *self.clone().as_ref() as *const Event as *mut Event;
file.read_to_end((*a).contents)?;
}
let mime_type =
infer::get(self.contents).map_or("text/plain", |mime| mime.mime_type());
for step in (self.record.start..self.record.end).step_by(self.step) {
let n = name.clone().into();
let f = filename.clone();
info!("Step {step} of {:?}", self.record);
let move_self = self.clone();
let join = tokio::spawn(async move {
let response = move_self.send_multipart(n, f.into(), mime_type).await;
match response {
Ok(resp) => {
info!("Status of {:?}: {}", move_self.record, resp.status())
}
Err(err) => {
info!("Error with step {step} of {:?}: {err}", move_self.record)
}
}
});
tokio::time::sleep(tokio::time::Duration::from_secs(self.step as u64)).await;
unsafe {
let x = *self.clone().as_ref() as *const Event as *mut Event;
(*x).joins.push(join);
}
}
}
}
Ok(())
}
async fn send_file(
method: String,
url: String,
name: String,
mime_type: String,
filename: String,
buf: Cow<'static, [u8]>,
) -> Result<reqwest::Response, crate::Error> {
let client = reqwest::Client::new();
let part = reqwest::multipart::Part::bytes(buf)
.file_name(filename)
.mime_str(&mime_type)?;
let form = reqwest::multipart::Form::new().part(name, part);
let response = client
.request(Method::from_bytes(method.as_bytes())?, url)
.multipart(form)
.send()
.await?;
Ok(response)
}
async fn send_file_leak(
method: String,
url: String,
name: String,
mime_type: String,
filename: String,
buf: Arc<&'static [u8]>,
) -> Result<reqwest::Response, crate::Error> {
let client = reqwest::Client::new();
let part = reqwest::multipart::Part::bytes(*buf.as_ref())
.file_name(filename)
.mime_str(&mime_type)?;
let form = reqwest::multipart::Form::new().part(name, part);
let response = client
.request(Method::from_bytes(method.as_bytes())?, url)
.multipart(form)
.send()
.await?;
Ok(response)
}
async fn send_multipart(
&'static self,
name: Cow<'static, str>,
filename: Cow<'static, str>,
mime_type: &str,
) -> Result<reqwest::Response, crate::Error> {
let client = reqwest::Client::new();
let buf: &Vec<u8> = self.contents.as_ref();
let buf: Cow<'static, [u8]> = buf.into();
let part = reqwest::multipart::Part::bytes(buf)
.file_name(filename)
.mime_str(&mime_type)?;
let form = reqwest::multipart::Form::new().part(name, part);
let response = client
.request(
Method::from_bytes(self.record.method.as_bytes())?,
self.record.host.clone(),
)
.multipart(form)
.send()
.await?;
Ok(response)
}
pub async fn wait(self) -> Result<(), crate::Error> {
for join in self.joins.into_iter() {
tokio::join!(join).0?;
}
if let Some(v) = self.contents_leak {
unsafe {
Box::from_raw(v.as_ptr() as *mut u8);
}
}
Ok(())
}
pub fn new(record: Record, step: usize) -> Event {
static mut CONTENTS: Vec<u8> = vec![];
unsafe {
Event {
record,
step: step as usize,
joins: Vec::new(),
contents: &mut CONTENTS,
contents_leak: None
}
}
}
}
impl Ord for Event {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
if self.record.start == other.record.start {
return self.record.end.cmp(&other.record.end);
}
self.record.start.cmp(&other.record.start)
}
}
impl PartialOrd for Event {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl PartialEq for Event {
fn eq(&self, other: &Self) -> bool {
self.record.start.eq(&other.record.start) && self.record.end.eq(&other.record.end)
}
}
impl Eq for Event {}
impl Clone for Event {
fn clone(&self) -> Self {
Event::new(self.record.clone(), self.step)
}
}
#[cfg(test)]
mod tests {
use crate::event::Event;
use httpmock::prelude::*;
#[tokio::test]
async fn test_send_file() -> Result<(), crate::Error> {
let server = MockServer::start();
let mock = server.mock(|when, then| {
when.method(POST)
.path("/yolo/v2/predict")
.body_contains("file");
then.status(200);
});
let record = crate::Record {
method: "POST".into(),
host: server.base_url(),
start: 0,
end: 8,
path: "/yolo/v2/predict".into(),
body: crate::Body::MULTIPART {
path: "./tests/data/test_data.yaml".into(),
name: "file".into(),
},
};
let mut event = Event::new(record, 2);
event.run().await?;
for join in event.joins.into_iter() {
let _ = tokio::join!(join);
}
mock.assert_hits(4);
Ok(())
}
}