Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix(sfs): image downscaling (#2636)

Eric Hayes10ef9f3d1fc4
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index 365a2ccbde..667d2df9da 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -10508,6 +10508,7 @@ dependencies = [
"aws-sdk-sqs",
"axum",
"chrono",
+ "image",
"macro_auth",
"macro_aws_config",
"macro_cors",
diff --git a/rust/cloud-storage/Cargo.toml b/rust/cloud-storage/Cargo.toml
index 637ca71b43..0308c48e0a 100644
--- a/rust/cloud-storage/Cargo.toml
+++ b/rust/cloud-storage/Cargo.toml
@@ -176,6 +176,23 @@ hex = "0.4.3"
hmac = "0.12.1"
http = "1"
http-body-util = "0.1.2"
+image = { version = "0.25", default-features = false, features = [
+ "avif",
+ "bmp",
+ "dds",
+ "exr",
+ "ff",
+ "gif",
+ "hdr",
+ "ico",
+ "jpeg",
+ "png",
+ "pnm",
+ "qoi",
+ "tga",
+ "tiff",
+ "webp",
+] }
inquire = "0.7"
itertools = "0.14"
jsonwebtoken = { git = "https://github.com/whutchinson98/jsonwebtoken", features = [
diff --git a/rust/cloud-storage/ai/Cargo.toml b/rust/cloud-storage/ai/Cargo.toml
index 4dc5cabb17..a7d981be65 100644
--- a/rust/cloud-storage/ai/Cargo.toml
+++ b/rust/cloud-storage/ai/Cargo.toml
@@ -35,7 +35,7 @@ anthropic = { path = "../anthropic" }
ai_toolset = { path = "../ai_toolset" }
macro_user_id = { path = "../macro_user_id" }
base64 = { workspace = true }
-image = "0.25.9"
+image = { workspace = true }
webp = "0.3.1"
model_file_type = { path = "../model_file_type"}
ai_format = {path = "../ai_format"}
diff --git a/rust/cloud-storage/static_file_service/Cargo.toml b/rust/cloud-storage/static_file_service/Cargo.toml
index 88a363fa89..ab2c9e3f91 100644
--- a/rust/cloud-storage/static_file_service/Cargo.toml
+++ b/rust/cloud-storage/static_file_service/Cargo.toml
@@ -25,6 +25,7 @@ aws-sdk-secretsmanager = { workspace = true }
aws-sdk-sqs.workspace = true
axum = { workspace = true, features = ["tower-log", "ws"] }
chrono = { workspace = true }
+image = { workspace = true }
macro_auth = { path = "../macro_auth" }
macro_aws_config = { path = "../macro_aws_config", features = ["s3"] }
macro_cors = { path = "../macro_cors" }
diff --git a/rust/cloud-storage/static_file_service/src/api/event/poll.rs b/rust/cloud-storage/static_file_service/src/api/event/poll.rs
index 7c47e6b4ab..07276f29b4 100644
--- a/rust/cloud-storage/static_file_service/src/api/event/poll.rs
+++ b/rust/cloud-storage/static_file_service/src/api/event/poll.rs
@@ -50,7 +50,12 @@ async fn poll(sqs_url: String, context: AppState) -> Result<(), PollError> {
tracing::error!("failed to delete sqs message {:?}", e);
e
});
- s3_message::handle_s3_message(message, context.metadata_client.clone()).await;
+ s3_message::handle_s3_message(
+ message,
+ context.metadata_client.clone(),
+ context.storage_client.clone(),
+ )
+ .await;
}
}
Ok(())
diff --git a/rust/cloud-storage/static_file_service/src/api/event/s3_create.rs b/rust/cloud-storage/static_file_service/src/api/event/s3_create.rs
index 186443b687..8de265596b 100644
--- a/rust/cloud-storage/static_file_service/src/api/event/s3_create.rs
+++ b/rust/cloud-storage/static_file_service/src/api/event/s3_create.rs
@@ -1,11 +1,65 @@
use super::message::*;
use crate::service::dynamodb::client::DynamodbClient;
+use crate::service::image::{DownscaleOutcome, format_from_content_type, try_downscale};
+use crate::service::s3::client::S3Client;
use anyhow::{Context, Result};
+use s3_key::StaticFileKey;
+use std::sync::Arc;
+
+#[tracing::instrument(err, skip(metadata_client, storage_client), fields(key = %event.s3.object.key))]
+pub async fn handle_s3_create(
+ event: S3EventRecord,
+ metadata_client: DynamodbClient,
+ storage_client: Arc<S3Client>,
+) -> Result<()> {
+ try_downscale_object(&event, &metadata_client, &storage_client).await?;
-#[tracing::instrument(skip(metadata_client))]
-pub async fn handle_s3_create(event: S3EventRecord, metadata_client: DynamodbClient) -> Result<()> {
metadata_client
.mark_uploaded(event.s3.object.key.as_str())
.await
- .context("could not not mark file uploaded")
+ .context("could not mark file uploaded")
+}
+
+#[tracing::instrument(err, skip(metadata_client, storage_client), fields(key = %event.s3.object.key))]
+async fn try_downscale_object(
+ event: &S3EventRecord,
+ metadata_client: &DynamodbClient,
+ storage_client: &S3Client,
+) -> Result<()> {
+ let key = event.s3.object.key.as_str();
+
+ let file_id = StaticFileKey::from_s3_key(key)
+ .context("invalid static file key")?
+ .file_id;
+
+ let metadata = metadata_client
+ .get_metadata(&file_id)
+ .await
+ .context("failed to load metadata")?;
+
+ let Some(metadata) = metadata else {
+ tracing::debug!(
+ file_id,
+ "no metadata for uploaded object; skipping downscale"
+ );
+ return Ok(());
+ };
+
+ let Some(format) = format_from_content_type(&metadata.content_type) else {
+ return Ok(());
+ };
+
+ let bytes = storage_client.get_object_bytes(key).await?;
+
+ let outcome = tokio::task::spawn_blocking(move || try_downscale(&bytes, format))
+ .await
+ .context("downscale task panicked")??;
+
+ match outcome {
+ DownscaleOutcome::Skipped => Ok(()),
+ DownscaleOutcome::Replaced { bytes } => storage_client
+ .put_object(key, bytes, &metadata.content_type)
+ .await
+ .context("failed to replace object with downscaled version"),
+ }
}
diff --git a/rust/cloud-storage/static_file_service/src/api/event/s3_message.rs b/rust/cloud-storage/static_file_service/src/api/event/s3_message.rs
index bec50361cd..8350e9c1be 100644
--- a/rust/cloud-storage/static_file_service/src/api/event/s3_message.rs
+++ b/rust/cloud-storage/static_file_service/src/api/event/s3_message.rs
@@ -1,11 +1,17 @@
use super::message::{S3EventKind::*, *};
use super::s3_create;
use crate::service::dynamodb::client::DynamodbClient;
+use crate::service::s3::client::S3Client;
use aws_sdk_sqs::types::Message;
use serde_json::from_str;
+use std::sync::Arc;
-#[tracing::instrument(skip(metadata_client))]
-pub async fn handle_s3_message(message: Message, metadata_client: DynamodbClient) -> Option<()> {
+#[tracing::instrument(skip(metadata_client, storage_client))]
+pub async fn handle_s3_message(
+ message: Message,
+ metadata_client: DynamodbClient,
+ storage_client: Arc<S3Client>,
+) -> Option<()> {
tracing::debug!("processing sqs message {:?}", message);
if let Some(text) = message.body {
let body: S3EventNotification = from_str(text.as_str())
@@ -14,7 +20,7 @@ pub async fn handle_s3_message(message: Message, metadata_client: DynamodbClient
err
})
.ok()?;
- handle_s3_events(body, metadata_client.clone()).await;
+ handle_s3_events(body, metadata_client.clone(), storage_client).await;
None
} else {
tracing::warn!("what the freak (no message body)");
@@ -22,8 +28,12 @@ pub async fn handle_s3_message(message: Message, metadata_client: DynamodbClient
}
}
-#[tracing::instrument(skip(metadata_client))]
-async fn handle_s3_events(event: S3EventNotification, metadata_client: DynamodbClient) {
+#[tracing::instrument(skip(metadata_client, storage_client))]
+async fn handle_s3_events(
+ event: S3EventNotification,
+ metadata_client: DynamodbClient,
+ storage_client: Arc<S3Client>,
+) {
for event in event.records {
match event.event_kind {
ObjectCreatedAll
@@ -31,11 +41,13 @@ async fn handle_s3_events(event: S3EventNotification, metadata_client: DynamodbC
| ObjectCreatedPut
| ObjectCreatedCopy
| ObjectCreatedPost => {
- let _ = s3_create::handle_s3_create(event, metadata_client.clone())
- .await
- .map_err(
- |err| tracing::error!(error=?err, "failed to handle S3::CreateObject:*"),
- );
+ let _ = s3_create::handle_s3_create(
+ event,
+ metadata_client.clone(),
+ storage_client.clone(),
+ )
+ .await
+ .map_err(|err| tracing::error!(error=?err, "failed to handle S3::CreateObject:*"));
}
_ => {}
}
diff --git a/rust/cloud-storage/static_file_service/src/service/image.rs b/rust/cloud-storage/static_file_service/src/service/image.rs
new file mode 100644
index 0000000000..6edc86dd82
--- /dev/null
+++ b/rust/cloud-storage/static_file_service/src/service/image.rs
@@ -0,0 +1,74 @@
+use anyhow::{Context, Result};
+use image::{ImageFormat, ImageReader, codecs::jpeg::JpegEncoder};
+use std::io::Cursor;
+
+pub const MAX_DIMENSION: u32 = 1080;
+pub const JPEG_QUALITY: u8 = 85;
+pub const MAX_INPUT_BYTES: usize = 50 * 1024 * 1024;
+
+pub fn format_from_content_type(content_type: &str) -> Option<ImageFormat> {
+ ImageFormat::from_mime_type(content_type)
+}
+
+pub enum DownscaleOutcome {
+ Replaced { bytes: Vec<u8> },
+ Skipped,
+}
+
+#[tracing::instrument(err, skip(bytes), fields(bytes_len = bytes.len(), ?format))]
+pub fn try_downscale(bytes: &[u8], format: ImageFormat) -> Result<DownscaleOutcome> {
+ if bytes.len() > MAX_INPUT_BYTES {
+ tracing::warn!(bytes_len = bytes.len(), "skipping: exceeds max input size");
+ return Ok(DownscaleOutcome::Skipped);
+ }
+
+ if !format.can_read() || !format.can_write() {
+ return Ok(DownscaleOutcome::Skipped);
+ }
+
+ let mut reader = ImageReader::new(Cursor::new(bytes));
+ reader.set_format(format);
+ let img = reader.decode().context("failed to decode image")?;
+
+ let (w, h) = (img.width(), img.height());
+ if w.max(h) <= MAX_DIMENSION {
+ return Ok(DownscaleOutcome::Skipped);
+ }
+
+ let resized = img.resize(
+ MAX_DIMENSION,
+ MAX_DIMENSION,
+ image::imageops::FilterType::Lanczos3,
+ );
+
+ let mut out = Vec::new();
+ if format == ImageFormat::Jpeg {
+ let rgb = resized.to_rgb8();
+ let mut encoder = JpegEncoder::new_with_quality(&mut out, JPEG_QUALITY);
+ encoder
+ .encode(
+ rgb.as_raw(),
+ rgb.width(),
+ rgb.height(),
+ image::ExtendedColorType::Rgb8,
+ )
+ .context("failed to encode jpeg")?;
+ } else {
+ resized
+ .write_to(&mut Cursor::new(&mut out), format)
+ .with_context(|| format!("failed to encode {format:?}"))?;
+ }
+
+ tracing::info!(
+ original_bytes = bytes.len(),
+ resized_bytes = out.len(),
+ original_w = w,
+ original_h = h,
+ "downscaled image"
+ );
+
+ Ok(DownscaleOutcome::Replaced { bytes: out })
+}
+
+#[cfg(test)]
+mod test;
diff --git a/rust/cloud-storage/static_file_service/src/service/image/test.rs b/rust/cloud-storage/static_file_service/src/service/image/test.rs
new file mode 100644
index 0000000000..3a55b96499
--- /dev/null
+++ b/rust/cloud-storage/static_file_service/src/service/image/test.rs
@@ -0,0 +1,105 @@
+use super::*;
+use image::{ImageBuffer, Rgb, RgbImage};
+
+fn encode_rgb_jpeg(w: u32, h: u32) -> Vec<u8> {
+ let img: RgbImage = ImageBuffer::from_pixel(w, h, Rgb([128, 64, 200]));
+ let mut bytes = Vec::new();
+ let mut encoder = JpegEncoder::new_with_quality(&mut bytes, 95);
+ encoder
+ .encode(
+ img.as_raw(),
+ img.width(),
+ img.height(),
+ image::ExtendedColorType::Rgb8,
+ )
+ .unwrap();
+ bytes
+}
+
+fn encode_rgb_png(w: u32, h: u32) -> Vec<u8> {
+ let img: RgbImage = ImageBuffer::from_pixel(w, h, Rgb([128, 64, 200]));
+ let mut bytes = Vec::new();
+ img.write_to(&mut Cursor::new(&mut bytes), ImageFormat::Png)
+ .unwrap();
+ bytes
+}
+
+#[test]
+fn downscales_large_jpeg() {
+ let bytes = encode_rgb_jpeg(4000, 3000);
+ let result = try_downscale(&bytes, ImageFormat::Jpeg).unwrap();
+ let DownscaleOutcome::Replaced { bytes: out } = result else {
+ panic!("expected replacement");
+ };
+
+ let decoded = image::load_from_memory_with_format(&out, ImageFormat::Jpeg).unwrap();
+ assert!(decoded.width().max(decoded.height()) <= MAX_DIMENSION);
+ assert!(out.len() < bytes.len());
+}
+
+#[test]
+fn downscales_large_png() {
+ let bytes = encode_rgb_png(2000, 500);
+ let result = try_downscale(&bytes, ImageFormat::Png).unwrap();
+ let DownscaleOutcome::Replaced { bytes: out } = result else {
+ panic!("expected replacement");
+ };
+
+ let decoded = image::load_from_memory_with_format(&out, ImageFormat::Png).unwrap();
+ assert_eq!(decoded.width().max(decoded.height()), MAX_DIMENSION);
+}
+
+#[test]
+fn skips_small_image() {
+ let bytes = encode_rgb_jpeg(800, 600);
+ let result = try_downscale(&bytes, ImageFormat::Jpeg).unwrap();
+ assert!(matches!(result, DownscaleOutcome::Skipped));
+}
+
+#[test]
+fn skips_image_at_boundary() {
+ let bytes = encode_rgb_jpeg(MAX_DIMENSION, 500);
+ let result = try_downscale(&bytes, ImageFormat::Jpeg).unwrap();
+ assert!(matches!(result, DownscaleOutcome::Skipped));
+}
+
+#[test]
+fn skips_oversized_input_bytes() {
+ let bytes = vec![0u8; MAX_INPUT_BYTES + 1];
+ let result = try_downscale(&bytes, ImageFormat::Jpeg).unwrap();
+ assert!(matches!(result, DownscaleOutcome::Skipped));
+}
+
+#[test]
+fn preserves_aspect_ratio() {
+ let bytes = encode_rgb_jpeg(4000, 2000);
+ let DownscaleOutcome::Replaced { bytes: out } =
+ try_downscale(&bytes, ImageFormat::Jpeg).unwrap()
+ else {
+ panic!("expected replacement");
+ };
+ let decoded = image::load_from_memory_with_format(&out, ImageFormat::Jpeg).unwrap();
+ assert_eq!(decoded.width(), MAX_DIMENSION);
+ assert_eq!(decoded.height(), MAX_DIMENSION / 2);
+}
+
+#[test]
+fn content_type_mapping() {
+ assert_eq!(
+ format_from_content_type("image/jpeg"),
+ Some(ImageFormat::Jpeg)
+ );
+ assert_eq!(
+ format_from_content_type("image/png"),
+ Some(ImageFormat::Png)
+ );
+ assert_eq!(
+ format_from_content_type("image/gif"),
+ Some(ImageFormat::Gif)
+ );
+ assert_eq!(
+ format_from_content_type("image/webp"),
+ Some(ImageFormat::WebP)
+ );
+ assert_eq!(format_from_content_type("application/pdf"), None);
+}
diff --git a/rust/cloud-storage/static_file_service/src/service/mod.rs b/rust/cloud-storage/static_file_service/src/service/mod.rs
index 9ad307ad1f..fd7f1d418f 100644
--- a/rust/cloud-storage/static_file_service/src/service/mod.rs
+++ b/rust/cloud-storage/static_file_service/src/service/mod.rs
@@ -1,2 +1,3 @@
pub mod dynamodb;
+pub mod image;
pub mod s3;
diff --git a/rust/cloud-storage/static_file_service/src/service/s3/client.rs b/rust/cloud-storage/static_file_service/src/service/s3/client.rs
index e5ce5c4236..89c49a284d 100644
--- a/rust/cloud-storage/static_file_service/src/service/s3/client.rs
+++ b/rust/cloud-storage/static_file_service/src/service/s3/client.rs
@@ -1,5 +1,5 @@
use anyhow::{Context, Result};
-use aws_sdk_s3::{self, presigning::PresigningConfig};
+use aws_sdk_s3::{self, presigning::PresigningConfig, primitives::ByteStream};
use std::time::Duration;
#[derive(Debug)]
@@ -44,6 +44,41 @@ impl S3Client {
Ok(())
}
+ #[tracing::instrument(skip(self))]
+ pub async fn get_object_bytes(&self, key: &str) -> Result<Vec<u8>> {
+ let response = self
+ .inner
+ .get_object()
+ .bucket(self.storage_bucket.clone())
+ .key(key)
+ .send()
+ .await
+ .context("failed to get object")?;
+
+ let bytes = response
+ .body
+ .collect()
+ .await
+ .context("failed to read object body")?
+ .into_bytes();
+
+ Ok(bytes.to_vec())
+ }
+
+ #[tracing::instrument(skip(self, bytes), fields(bytes_len = bytes.len()))]
+ pub async fn put_object(&self, key: &str, bytes: Vec<u8>, content_type: &str) -> Result<()> {
+ self.inner
+ .put_object()
+ .bucket(self.storage_bucket.clone())
+ .key(key)
+ .content_type(content_type)
+ .body(ByteStream::from(bytes))
+ .send()
+ .await
+ .context("failed to put object")?;
+ Ok(())
+ }
+
#[tracing::instrument(skip(self))]
pub async fn get_presigned_url(&self, key: String) -> Result<String> {
let presigned_url = self