|
| 1 | +use std::io::Cursor; |
| 2 | + |
| 3 | +use aws_lambda_events::{event::s3::S3Event, s3::S3EventRecord}; |
| 4 | +use aws_sdk_s3::Client as S3Client; |
| 5 | +use lambda_runtime::{run, service_fn, Error, LambdaEvent}; |
| 6 | +use s3::{GetFile, PutFile}; |
| 7 | +use thumbnailer::{create_thumbnails, ThumbnailSize}; |
| 8 | + |
| 9 | +mod s3; |
| 10 | + |
| 11 | +/** |
| 12 | +This lambda handler |
| 13 | + * listen to file creation events |
| 14 | + * downloads the created file |
| 15 | + * creates a thumbnail from it |
| 16 | + * uploads the thumbnail to bucket "[original bucket name]-thumbs". |
| 17 | +
|
| 18 | +Make sure that |
| 19 | + * the created png file has no strange characters in the name |
| 20 | + * there is another bucket with "-thumbs" suffix in the name |
| 21 | + * this lambda only gets event from png file creation |
| 22 | + * this lambda has permission to put file into the "-thumbs" bucket |
| 23 | +*/ |
| 24 | +pub(crate) async fn function_handler<T: PutFile + GetFile>( |
| 25 | + event: LambdaEvent<S3Event>, |
| 26 | + size: u32, |
| 27 | + client: &T, |
| 28 | +) -> Result<(), Error> { |
| 29 | + let records = event.payload.records; |
| 30 | + |
| 31 | + for record in records.into_iter() { |
| 32 | + let (bucket, key) = match get_file_props(record) { |
| 33 | + Ok(touple) => touple, |
| 34 | + Err(msg) => { |
| 35 | + tracing::info!("Record skipped with reason: {}", msg); |
| 36 | + continue; |
| 37 | + } |
| 38 | + }; |
| 39 | + |
| 40 | + let image = match client.get_file(&bucket, &key).await { |
| 41 | + Ok(vec) => vec, |
| 42 | + Err(msg) => { |
| 43 | + tracing::info!("Can not get file from S3: {}", msg); |
| 44 | + continue; |
| 45 | + } |
| 46 | + }; |
| 47 | + |
| 48 | + let thumbnail = match get_thumbnail(image, size) { |
| 49 | + Ok(vec) => vec, |
| 50 | + Err(msg) => { |
| 51 | + tracing::info!("Can not create thumbnail: {}", msg); |
| 52 | + continue; |
| 53 | + } |
| 54 | + }; |
| 55 | + |
| 56 | + let mut thumbs_bucket = bucket.to_owned(); |
| 57 | + thumbs_bucket.push_str("-thumbs"); |
| 58 | + |
| 59 | + // It uploads the thumbnail into a bucket name suffixed with "-thumbs" |
| 60 | + // So it needs file creation permission into that bucket |
| 61 | + |
| 62 | + match client.put_file(&thumbs_bucket, &key, thumbnail).await { |
| 63 | + Ok(msg) => tracing::info!(msg), |
| 64 | + Err(msg) => tracing::info!("Can not upload thumbnail: {}", msg), |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + Ok(()) |
| 69 | +} |
| 70 | + |
| 71 | +fn get_file_props(record: S3EventRecord) -> Result<(String, String), String> { |
| 72 | + record |
| 73 | + .event_name |
| 74 | + .filter(|s| s.starts_with("ObjectCreated")) |
| 75 | + .ok_or("Wrong event")?; |
| 76 | + |
| 77 | + let bucket = record |
| 78 | + .s3 |
| 79 | + .bucket |
| 80 | + .name |
| 81 | + .filter(|s| !s.is_empty()) |
| 82 | + .ok_or("No bucket name")?; |
| 83 | + |
| 84 | + let key = record.s3.object.key.filter(|s| !s.is_empty()).ok_or("No object key")?; |
| 85 | + |
| 86 | + Ok((bucket, key)) |
| 87 | +} |
| 88 | + |
| 89 | +fn get_thumbnail(vec: Vec<u8>, size: u32) -> Result<Vec<u8>, String> { |
| 90 | + let reader = Cursor::new(vec); |
| 91 | + let mime = mime::IMAGE_PNG; |
| 92 | + let sizes = [ThumbnailSize::Custom((size, size))]; |
| 93 | + |
| 94 | + let thumbnail = match create_thumbnails(reader, mime, sizes) { |
| 95 | + Ok(mut thumbnails) => thumbnails.pop().ok_or("No thumbnail created")?, |
| 96 | + Err(thumb_error) => return Err(thumb_error.to_string()), |
| 97 | + }; |
| 98 | + |
| 99 | + let mut buf = Cursor::new(Vec::new()); |
| 100 | + |
| 101 | + match thumbnail.write_png(&mut buf) { |
| 102 | + Ok(_) => Ok(buf.into_inner()), |
| 103 | + Err(_) => Err("Unknown error when Thumbnail::write_png".to_string()), |
| 104 | + } |
| 105 | +} |
| 106 | + |
| 107 | +#[tokio::main] |
| 108 | +async fn main() -> Result<(), Error> { |
| 109 | + // required to enable CloudWatch error logging by the runtime |
| 110 | + tracing_subscriber::fmt() |
| 111 | + .with_max_level(tracing::Level::INFO) |
| 112 | + // disable printing the name of the module in every log line. |
| 113 | + .with_target(false) |
| 114 | + // this needs to be set to false, otherwise ANSI color codes will |
| 115 | + // show up in a confusing manner in CloudWatch logs. |
| 116 | + .with_ansi(false) |
| 117 | + // disabling time is handy because CloudWatch will add the ingestion time. |
| 118 | + .without_time() |
| 119 | + .init(); |
| 120 | + |
| 121 | + let shared_config = aws_config::load_from_env().await; |
| 122 | + let client = S3Client::new(&shared_config); |
| 123 | + let client_ref = &client; |
| 124 | + |
| 125 | + let func = service_fn(move |event| async move { function_handler(event, 128, client_ref).await }); |
| 126 | + |
| 127 | + run(func).await?; |
| 128 | + |
| 129 | + Ok(()) |
| 130 | +} |
| 131 | + |
| 132 | +#[cfg(test)] |
| 133 | +mod tests { |
| 134 | + use std::collections::HashMap; |
| 135 | + use std::fs::File; |
| 136 | + use std::io::BufReader; |
| 137 | + use std::io::Read; |
| 138 | + |
| 139 | + use super::*; |
| 140 | + use async_trait::async_trait; |
| 141 | + use aws_lambda_events::chrono::DateTime; |
| 142 | + use aws_lambda_events::s3::S3Bucket; |
| 143 | + use aws_lambda_events::s3::S3Entity; |
| 144 | + use aws_lambda_events::s3::S3Object; |
| 145 | + use aws_lambda_events::s3::S3RequestParameters; |
| 146 | + use aws_lambda_events::s3::S3UserIdentity; |
| 147 | + use aws_sdk_s3::error::GetObjectError; |
| 148 | + use lambda_runtime::{Context, LambdaEvent}; |
| 149 | + use mockall::mock; |
| 150 | + use s3::GetFile; |
| 151 | + use s3::PutFile; |
| 152 | + |
| 153 | + #[tokio::test] |
| 154 | + async fn response_is_good() { |
| 155 | + let mut context = Context::default(); |
| 156 | + context.request_id = "test-request-id".to_string(); |
| 157 | + |
| 158 | + let bucket = "test-bucket"; |
| 159 | + let key = "test-key"; |
| 160 | + |
| 161 | + mock! { |
| 162 | + FakeS3Client {} |
| 163 | + |
| 164 | + #[async_trait] |
| 165 | + impl GetFile for FakeS3Client { |
| 166 | + pub async fn get_file(&self, bucket: &str, key: &str) -> Result<Vec<u8>, GetObjectError>; |
| 167 | + } |
| 168 | + #[async_trait] |
| 169 | + impl PutFile for FakeS3Client { |
| 170 | + pub async fn put_file(&self, bucket: &str, key: &str, bytes: Vec<u8>) -> Result<String, String>; |
| 171 | + } |
| 172 | + } |
| 173 | + |
| 174 | + let mut mock = MockFakeS3Client::new(); |
| 175 | + |
| 176 | + mock.expect_get_file() |
| 177 | + .withf(|b: &str, k: &str| b.eq(bucket) && k.eq(key)) |
| 178 | + .returning(|_1, _2| Ok(get_file("testdata/image.png"))); |
| 179 | + |
| 180 | + mock.expect_put_file() |
| 181 | + .withf(|bu: &str, ke: &str, by| { |
| 182 | + let thumbnail = get_file("testdata/thumbnail.png"); |
| 183 | + return bu.eq("test-bucket-thumbs") && ke.eq(key) && by == &thumbnail; |
| 184 | + }) |
| 185 | + .returning(|_1, _2, _3| Ok("Done".to_string())); |
| 186 | + |
| 187 | + let payload = get_s3_event("ObjectCreated", bucket, key); |
| 188 | + let event = LambdaEvent { payload, context }; |
| 189 | + |
| 190 | + let result = function_handler(event, 10, &mock).await.unwrap(); |
| 191 | + |
| 192 | + assert_eq!((), result); |
| 193 | + } |
| 194 | + |
| 195 | + fn get_file(name: &str) -> Vec<u8> { |
| 196 | + let f = File::open(name); |
| 197 | + let mut reader = BufReader::new(f.unwrap()); |
| 198 | + let mut buffer = Vec::new(); |
| 199 | + |
| 200 | + reader.read_to_end(&mut buffer).unwrap(); |
| 201 | + |
| 202 | + return buffer; |
| 203 | + } |
| 204 | + |
| 205 | + fn get_s3_event(event_name: &str, bucket_name: &str, object_key: &str) -> S3Event { |
| 206 | + return S3Event { |
| 207 | + records: (vec![get_s3_event_record(event_name, bucket_name, object_key)]), |
| 208 | + }; |
| 209 | + } |
| 210 | + |
| 211 | + fn get_s3_event_record(event_name: &str, bucket_name: &str, object_key: &str) -> S3EventRecord { |
| 212 | + let s3_entity = S3Entity { |
| 213 | + schema_version: (Some(String::default())), |
| 214 | + configuration_id: (Some(String::default())), |
| 215 | + bucket: (S3Bucket { |
| 216 | + name: (Some(bucket_name.to_string())), |
| 217 | + owner_identity: (S3UserIdentity { |
| 218 | + principal_id: (Some(String::default())), |
| 219 | + }), |
| 220 | + arn: (Some(String::default())), |
| 221 | + }), |
| 222 | + object: (S3Object { |
| 223 | + key: (Some(object_key.to_string())), |
| 224 | + size: (Some(1)), |
| 225 | + url_decoded_key: (Some(String::default())), |
| 226 | + version_id: (Some(String::default())), |
| 227 | + e_tag: (Some(String::default())), |
| 228 | + sequencer: (Some(String::default())), |
| 229 | + }), |
| 230 | + }; |
| 231 | + |
| 232 | + return S3EventRecord { |
| 233 | + event_version: (Some(String::default())), |
| 234 | + event_source: (Some(String::default())), |
| 235 | + aws_region: (Some(String::default())), |
| 236 | + event_time: (DateTime::default()), |
| 237 | + event_name: (Some(event_name.to_string())), |
| 238 | + principal_id: (S3UserIdentity { |
| 239 | + principal_id: (Some("X".to_string())), |
| 240 | + }), |
| 241 | + request_parameters: (S3RequestParameters { |
| 242 | + source_ip_address: (Some(String::default())), |
| 243 | + }), |
| 244 | + response_elements: (HashMap::new()), |
| 245 | + s3: (s3_entity), |
| 246 | + }; |
| 247 | + } |
| 248 | +} |
0 commit comments