|
| 1 | +use std::{error, io::Cursor}; |
| 2 | + |
| 3 | +use aws_lambda_events::s3::object_lambda::{GetObjectContext, S3ObjectLambdaEvent}; |
| 4 | +use aws_sdk_s3::Client as S3Client; |
| 5 | +use lambda_runtime::{run, service_fn, Error, LambdaEvent}; |
| 6 | +use s3::{GetFile, SendFile}; |
| 7 | +use thumbnailer::{create_thumbnails, ThumbnailSize}; |
| 8 | + |
| 9 | +mod s3; |
| 10 | + |
| 11 | +/** |
| 12 | +This s3 object lambda handler |
| 13 | + * downloads the asked file |
| 14 | + * creates a PNG thumbnail from it |
| 15 | + * forwards it to the browser |
| 16 | +*/ |
| 17 | +pub(crate) async fn function_handler<T: SendFile + GetFile>( |
| 18 | + event: LambdaEvent<S3ObjectLambdaEvent>, |
| 19 | + size: u32, |
| 20 | + client: &T, |
| 21 | +) -> Result<String, Box<dyn error::Error>> { |
| 22 | + tracing::info!("handler starts"); |
| 23 | + |
| 24 | + let context: GetObjectContext = event.payload.get_object_context.unwrap(); |
| 25 | + |
| 26 | + let route = context.output_route; |
| 27 | + let token = context.output_token; |
| 28 | + let s3_url = context.input_s3_url; |
| 29 | + |
| 30 | + tracing::info!("Route: {}, s3_url: {}", route, s3_url); |
| 31 | + |
| 32 | + let image = client.get_file(s3_url)?; |
| 33 | + tracing::info!("Image loaded. Length: {}", image.len()); |
| 34 | + |
| 35 | + let thumbnail = get_thumbnail(image, size); |
| 36 | + tracing::info!("thumbnail created. Length: {}", thumbnail.len()); |
| 37 | + |
| 38 | + // It sends the thumbnail back to the user |
| 39 | + |
| 40 | + client.send_file(route, token, thumbnail).await |
| 41 | + |
| 42 | + /* |
| 43 | + match client.send_file(route, token, thumbnail).await { |
| 44 | + Ok(msg) => tracing::info!(msg), |
| 45 | + Err(msg) => tracing::info!(msg) |
| 46 | + }; |
| 47 | +
|
| 48 | + tracing::info!("handler ends"); |
| 49 | +
|
| 50 | + Ok(()) |
| 51 | + */ |
| 52 | +} |
| 53 | + |
| 54 | +fn get_thumbnail(vec: Vec<u8>, size: u32) -> Vec<u8> { |
| 55 | + let reader = Cursor::new(vec); |
| 56 | + let mut thumbnails = create_thumbnails(reader, mime::IMAGE_PNG, [ThumbnailSize::Custom((size, size))]).unwrap(); |
| 57 | + |
| 58 | + let thumbnail = thumbnails.pop().unwrap(); |
| 59 | + let mut buf = Cursor::new(Vec::new()); |
| 60 | + thumbnail.write_png(&mut buf).unwrap(); |
| 61 | + |
| 62 | + buf.into_inner() |
| 63 | +} |
| 64 | + |
| 65 | +#[tokio::main] |
| 66 | +async fn main() -> Result<(), Error> { |
| 67 | + // required to enable CloudWatch error logging by the runtime |
| 68 | + tracing_subscriber::fmt() |
| 69 | + .with_max_level(tracing::Level::TRACE) |
| 70 | + // disable printing the name of the module in every log line. |
| 71 | + .with_target(false) |
| 72 | + // this needs to be set to false, otherwise ANSI color codes will |
| 73 | + // show up in a confusing manner in CloudWatch logs. |
| 74 | + .with_ansi(false) |
| 75 | + // disabling time is handy because CloudWatch will add the ingestion time. |
| 76 | + .without_time() |
| 77 | + .init(); |
| 78 | + |
| 79 | + let shared_config = aws_config::load_from_env().await; |
| 80 | + let client = S3Client::new(&shared_config); |
| 81 | + let client_ref = &client; |
| 82 | + |
| 83 | + let func = service_fn(move |event| async move { function_handler(event, 128, client_ref).await }); |
| 84 | + |
| 85 | + let _ = run(func).await; |
| 86 | + |
| 87 | + Ok(()) |
| 88 | +} |
| 89 | + |
| 90 | +#[cfg(test)] |
| 91 | +mod tests { |
| 92 | + use std::fs::File; |
| 93 | + use std::io::BufReader; |
| 94 | + use std::io::Read; |
| 95 | + |
| 96 | + use super::*; |
| 97 | + use async_trait::async_trait; |
| 98 | + use aws_lambda_events::s3::object_lambda::Configuration; |
| 99 | + use aws_lambda_events::s3::object_lambda::HeadObjectContext; |
| 100 | + use aws_lambda_events::s3::object_lambda::ListObjectsContext; |
| 101 | + use aws_lambda_events::s3::object_lambda::ListObjectsV2Context; |
| 102 | + use aws_lambda_events::s3::object_lambda::UserIdentity; |
| 103 | + use aws_lambda_events::s3::object_lambda::UserRequest; |
| 104 | + use aws_lambda_events::serde_json::json; |
| 105 | + use lambda_runtime::{Context, LambdaEvent}; |
| 106 | + use mockall::mock; |
| 107 | + use s3::GetFile; |
| 108 | + use s3::SendFile; |
| 109 | + |
| 110 | + #[tokio::test] |
| 111 | + async fn response_is_good() { |
| 112 | + mock! { |
| 113 | + FakeS3Client {} |
| 114 | + |
| 115 | + #[async_trait] |
| 116 | + impl GetFile for FakeS3Client { |
| 117 | + pub fn get_file(&self, url: String) -> Result<Vec<u8>, Box<dyn error::Error>>; |
| 118 | + } |
| 119 | + #[async_trait] |
| 120 | + impl SendFile for FakeS3Client { |
| 121 | + pub async fn send_file(&self, route: String, token: String, vec: Vec<u8>) -> Result<String, Box<dyn error::Error>>; |
| 122 | + } |
| 123 | + } |
| 124 | + |
| 125 | + let mut mock = MockFakeS3Client::new(); |
| 126 | + |
| 127 | + mock.expect_get_file() |
| 128 | + .withf(|u: &String| u.eq("S3_URL")) |
| 129 | + .returning(|_1| Ok(get_file("testdata/image.png"))); |
| 130 | + |
| 131 | + mock.expect_send_file() |
| 132 | + .withf(|r: &String, t: &String, by| { |
| 133 | + let thumbnail = get_file("testdata/thumbnail.png"); |
| 134 | + return r.eq("O_ROUTE") && t.eq("O_TOKEN") && by == &thumbnail; |
| 135 | + }) |
| 136 | + .returning(|_1, _2, _3| Ok("File sent.".to_string())); |
| 137 | + |
| 138 | + let payload = get_s3_event(); |
| 139 | + let context = Context::default(); |
| 140 | + let event = LambdaEvent { payload, context }; |
| 141 | + |
| 142 | + let result = function_handler(event, 10, &mock).await.unwrap(); |
| 143 | + |
| 144 | + assert_eq!(("File sent."), result); |
| 145 | + } |
| 146 | + |
| 147 | + fn get_file(name: &str) -> Vec<u8> { |
| 148 | + let f = File::open(name); |
| 149 | + let mut reader = BufReader::new(f.unwrap()); |
| 150 | + let mut buffer = Vec::new(); |
| 151 | + |
| 152 | + reader.read_to_end(&mut buffer).unwrap(); |
| 153 | + |
| 154 | + return buffer; |
| 155 | + } |
| 156 | + |
| 157 | + fn get_s3_event() -> S3ObjectLambdaEvent { |
| 158 | + return S3ObjectLambdaEvent { |
| 159 | + x_amz_request_id: ("ID".to_string()), |
| 160 | + head_object_context: (Some(HeadObjectContext::default())), |
| 161 | + list_objects_context: (Some(ListObjectsContext::default())), |
| 162 | + get_object_context: (Some(GetObjectContext { |
| 163 | + input_s3_url: ("S3_URL".to_string()), |
| 164 | + output_route: ("O_ROUTE".to_string()), |
| 165 | + output_token: ("O_TOKEN".to_string()), |
| 166 | + })), |
| 167 | + list_objects_v2_context: (Some(ListObjectsV2Context::default())), |
| 168 | + protocol_version: ("VERSION".to_string()), |
| 169 | + user_identity: (UserIdentity::default()), |
| 170 | + user_request: (UserRequest::default()), |
| 171 | + configuration: (Configuration { |
| 172 | + access_point_arn: ("APRN".to_string()), |
| 173 | + supporting_access_point_arn: ("SAPRN".to_string()), |
| 174 | + payload: (json!(null)), |
| 175 | + }), |
| 176 | + }; |
| 177 | + } |
| 178 | +} |
0 commit comments