-
Notifications
You must be signed in to change notification settings - Fork 393
Expand file tree
/
Copy pathmain.rs
More file actions
149 lines (120 loc) · 4.63 KB
/
Copy pathmain.rs
File metadata and controls
149 lines (120 loc) · 4.63 KB
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
use std::error;
use aws_lambda_events::s3::object_lambda::{GetObjectContext, S3ObjectLambdaEvent};
use aws_sdk_s3::Client as S3Client;
use lambda_runtime::{run, service_fn, tracing, Error, LambdaEvent};
use s3::{GetFile, SendFile};
mod s3;
/**
This s3 object lambda handler
* downloads the asked file
* creates a PNG thumbnail from it
* forwards it to the browser
*/
pub(crate) async fn function_handler<T: SendFile + GetFile>(
event: LambdaEvent<S3ObjectLambdaEvent>,
size: u32,
client: &T,
) -> Result<String, Box<dyn error::Error>> {
tracing::info!("handler starts");
let context: GetObjectContext = event.payload.get_object_context.unwrap();
let route = context.output_route;
let token = context.output_token;
let s3_url = context.input_s3_url;
tracing::info!("Route: {}, s3_url: {}", route, s3_url);
let image = client.get_file(s3_url)?;
tracing::info!("Image loaded. Length: {}", image.len());
let thumbnail = get_thumbnail(image, size);
tracing::info!("thumbnail created. Length: {}", thumbnail.len());
client.send_file(route, token, thumbnail).await
}
#[cfg(not(test))]
fn get_thumbnail(vec: Vec<u8>, size: u32) -> Vec<u8> {
let reader = std::io::Cursor::new(vec);
let mut thumbnails = thumbnailer::create_thumbnails(
reader,
mime::IMAGE_PNG,
[thumbnailer::ThumbnailSize::Custom((size, size))],
)
.unwrap();
let thumbnail = thumbnails.pop().unwrap();
let mut buf = std::io::Cursor::new(Vec::new());
thumbnail.write_png(&mut buf).unwrap();
buf.into_inner()
}
#[tokio::main]
async fn main() -> Result<(), Error> {
// required to enable CloudWatch error logging by the runtime
tracing::init_default_subscriber();
let shared_config = aws_config::load_from_env().await;
let client = S3Client::new(&shared_config);
let client_ref = &client;
let func = service_fn(move |event| async move { function_handler(event, 128, client_ref).await });
let _ = run(func).await;
Ok(())
}
#[cfg(test)]
fn get_thumbnail(vec: Vec<u8>, _size: u32) -> Vec<u8> {
let s = unsafe { std::str::from_utf8_unchecked(&vec) };
match s {
"IMAGE" => "THUMBNAIL".into(),
_ => "Input is not IMAGE".into(),
}
}
#[cfg(test)]
mod tests {
use super::*;
use async_trait::async_trait;
use aws_lambda_events::s3::object_lambda::{
Configuration, HeadObjectContext, ListObjectsContext, ListObjectsV2Context, UserIdentity, UserRequest,
};
use lambda_runtime::{Context, LambdaEvent};
use mockall::mock;
use s3::{GetFile, SendFile};
use serde_json::json;
#[tokio::test]
async fn response_is_good() {
mock! {
FakeS3Client {}
impl GetFile for FakeS3Client {
fn get_file(&self, url: String) -> Result<Vec<u8>, Box<dyn error::Error>>;
}
#[async_trait]
impl SendFile for FakeS3Client {
async fn send_file(&self, route: String, token: String, vec: Vec<u8>) -> Result<String, Box<dyn error::Error>>;
}
}
let mut mock = MockFakeS3Client::new();
mock.expect_get_file()
.withf(|u| u.eq("S3_URL"))
.returning(|_1| Ok("IMAGE".into()));
mock.expect_send_file()
.withf(|r, t, by| r.eq("O_ROUTE") && t.eq("O_TOKEN") && by == "THUMBNAIL".as_bytes())
.returning(|_1, _2, _3| Ok("File sent.".to_string()));
let payload = get_s3_event();
let context = Context::default();
let event = LambdaEvent { payload, context };
let result = function_handler(event, 10, &mock).await.unwrap();
assert_eq!(("File sent."), result);
}
fn get_s3_event() -> S3ObjectLambdaEvent {
S3ObjectLambdaEvent {
x_amz_request_id: ("ID".to_string()),
head_object_context: (Some(HeadObjectContext::default())),
list_objects_context: (Some(ListObjectsContext::default())),
get_object_context: (Some(GetObjectContext {
input_s3_url: ("S3_URL".to_string()),
output_route: ("O_ROUTE".to_string()),
output_token: ("O_TOKEN".to_string()),
})),
list_objects_v2_context: (Some(ListObjectsV2Context::default())),
protocol_version: ("VERSION".to_string()),
user_identity: (UserIdentity::default()),
user_request: (UserRequest::default()),
configuration: (Configuration {
access_point_arn: ("APRN".to_string()),
supporting_access_point_arn: ("SAPRN".to_string()),
payload: (json!(null)),
}),
}
}
}