Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(sfs): image optimizer lambda + infra (#2833)
Eric Hayes04e4589de4ba
diff --git a/.gitignore b/.gitignoreindex 7738ab28bd..6a18060116 100644--- a/.gitignore+++ b/.gitignore@@ -8,3 +8,4 @@temp/.env.localrun-local.fish+node_modules/diff --git a/infra/stacks/static-file-service/distribution.ts b/infra/stacks/static-file-service/distribution.tsindex debe9f3fe4..cf0ca8f4ab 100644--- a/infra/stacks/static-file-service/distribution.ts+++ b/infra/stacks/static-file-service/distribution.ts@@ -3,9 +3,10 @@ import * as pulumi from '@pulumi/pulumi';interface StaticFileCloudFrontArgs {bucket: aws.s3.Bucket;+ imageOptimizerUrl: pulumi.Output<string>;+ imageOptimizerFunctionName: pulumi.Output<string>;api: aws.lb.LoadBalancer;stackName: string;- // Optional parametersgeoRestrictions?: {restrictionType: 'whitelist' | 'blacklist';locations: string[];@@ -18,6 +19,19 @@ interface StaticFileCloudFrontArgs {tags: { [key: string]: string };}+const IMAGE_URL_REWRITE_FUNCTION = `+function handler(event) {+ var request = event.request;+ var size = request.querystring.size;++ if (!size) return request;++ request.uri += '/size=' + size.value;+ request.querystring = {};+ return request;+}+`;+export class StaticFileCloudFront extends pulumi.ComponentResource {public readonly distribution: aws.cloudfront.Distribution;public readonly s3AccessControl: aws.cloudfront.OriginAccessControl;@@ -31,7 +45,6 @@ export class StaticFileCloudFront extends pulumi.ComponentResource {super('custom:cdn:StaticFileCloudFront', name, {}, opts);this.tags = args.tags;- // Create Origin Access Control for the CloudFront distributionthis.s3AccessControl = new aws.cloudfront.OriginAccessControl(`${name}-s3-oac`,{@@ -43,8 +56,32 @@ export class StaticFileCloudFront extends pulumi.ComponentResource {{ parent: this });- const s3OriginId = `static-file-bucket`;- const apiOriginId = `static-file-api`;+ const lambdaAccessControl = new aws.cloudfront.OriginAccessControl(+ `${name}-lambda-oac`,+ {+ description: 'Origin Access Control for Image Optimizer Lambda',+ originAccessControlOriginType: 'lambda',+ signingBehavior: 'always',+ signingProtocol: 'sigv4',+ },+ { parent: this }+ );++ const s3OriginId = 'static-file-bucket';+ const lambdaOriginId = 'image-optimizer-lambda';+ const apiOriginId = 'static-file-api';+ const originGroupId = 'image-optimization-group';++ const imageUrlRewrite = new aws.cloudfront.Function(+ `${name}-image-url-rewrite`,+ {+ name: `image-url-rewrite-${args.stackName}`,+ runtime: 'cloudfront-js-2.0',+ code: IMAGE_URL_REWRITE_FUNCTION,+ publish: true,+ },+ { parent: this }+ );const responseHeadersPolicy = new aws.cloudfront.ResponseHeadersPolicy('corp-policy',@@ -68,7 +105,10 @@ export class StaticFileCloudFront extends pulumi.ComponentResource {});- // Create the CloudFront distribution+ const lambdaDomainName = args.imageOptimizerUrl.apply((url) =>+ url.replace('https://', '').replace(/\/+$/, '')+ );+this.distribution = new aws.cloudfront.Distribution(`${name}-distribution`,{@@ -78,6 +118,17 @@ export class StaticFileCloudFront extends pulumi.ComponentResource {originAccessControlId: this.s3AccessControl.id,originId: s3OriginId,},+ {+ domainName: lambdaDomainName,+ originAccessControlId: lambdaAccessControl.id,+ customOriginConfig: {+ httpPort: 80,+ httpsPort: 443,+ originProtocolPolicy: 'https-only',+ originSslProtocols: ['TLSv1.2'],+ },+ originId: lambdaOriginId,+ },{domainName: args.api.dnsName,customOriginConfig: {@@ -89,6 +140,15 @@ export class StaticFileCloudFront extends pulumi.ComponentResource {originId: apiOriginId,},],+ originGroups: [+ {+ originId: originGroupId,+ failoverCriteria: {+ statusCodes: [403, 404, 500, 502, 503, 504],+ },+ members: [{ originId: s3OriginId }, { originId: lambdaOriginId }],+ },+ ],enabled: true,isIpv6Enabled: true,comment: `Static files distribution for ${name}`,@@ -96,16 +156,22 @@ export class StaticFileCloudFront extends pulumi.ComponentResource {{allowedMethods: ['HEAD', 'GET', 'OPTIONS'],pathPattern: '/file/*',- targetOriginId: s3OriginId,+ targetOriginId: originGroupId,cachedMethods: ['GET', 'OPTIONS', 'HEAD'],viewerProtocolPolicy: 'redirect-to-https',forwardedValues: {- queryString: true,+ queryString: false,headers: ['Origin'],cookies: {forward: 'none',},},+ functionAssociations: [+ {+ eventType: 'viewer-request',+ functionArn: imageUrlRewrite.arn,+ },+ ],responseHeadersPolicyId: responseHeadersPolicy.id,minTtl: 0,defaultTtl: 31536000,@@ -175,8 +241,8 @@ export class StaticFileCloudFront extends pulumi.ComponentResource {},viewerProtocolPolicy: 'redirect-to-https',minTtl: 0,- defaultTtl: 2628000, // 1 week- maxTtl: 7884000, // 3 months+ defaultTtl: 2628000,+ maxTtl: 7884000,compress: true,},priceClass: 'PriceClass_100',@@ -214,20 +280,19 @@ export class StaticFileCloudFront extends pulumi.ComponentResource {});- // Configure bucket to allow CloudFront access+ // Allow CloudFront to read from and Lambda to write to the bucketnew aws.s3.BucketPublicAccessBlock(`${name}-access-block`,{bucket: args.bucket.id,blockPublicAcls: true,- blockPublicPolicy: false, // Must be false to allow CloudFront+ blockPublicPolicy: false,ignorePublicAcls: true,- restrictPublicBuckets: false, // Must be false to allow CloudFront,+ restrictPublicBuckets: false,},{ parent: this });- // Create bucket policy to allow CloudFront accessnew aws.s3.BucketPolicy(`${name}-bucket-policy`,{@@ -259,6 +324,17 @@ export class StaticFileCloudFront extends pulumi.ComponentResource {{ parent: this });+ new aws.lambda.Permission(+ `${name}-lambda-cloudfront-permission`,+ {+ action: 'lambda:InvokeFunctionUrl',+ function: args.imageOptimizerFunctionName,+ principal: 'cloudfront.amazonaws.com',+ sourceArn: this.distribution.arn,+ },+ { parent: this }+ );+this.registerOutputs({distribution: this.distribution,originAccessControl: this.s3AccessControl,diff --git a/infra/stacks/static-file-service/static-file-service.ts b/infra/stacks/static-file-service/static-file-service.tsindex c9e80eeed8..d7b54cc4ef 100644--- a/infra/stacks/static-file-service/static-file-service.ts+++ b/infra/stacks/static-file-service/static-file-service.ts@@ -141,6 +141,107 @@ export class StaticFileService extends pulumi.ComponentResource {tags: this.tags,});+ // Image optimizer Lambda — secondary origin in CloudFront origin group.+ // On cache miss for transformed image URLs (e.g. /file/{uuid}/format=webp,width=300),+ // the primary S3 origin returns 403 and CloudFront fails over to this Lambda.+ // The Lambda fetches the original from S3, transforms it, stores the result+ // back in the same bucket, and returns the image.+ const imageOptimizerRole = new aws.iam.Role(+ `${SERVICE_NAME}-image-optimizer-role`,+ {+ name: `${SERVICE_NAME}-image-optimizer-role-${stack}`,+ assumeRolePolicy: JSON.stringify({+ Version: '2012-10-17',+ Statement: [+ {+ Action: 'sts:AssumeRole',+ Effect: 'Allow',+ Principal: { Service: 'lambda.amazonaws.com' },+ },+ ],+ }),+ managedPolicyArns: [aws.iam.ManagedPolicy.AWSLambdaBasicExecutionRole],+ tags: this.tags,+ },+ { parent: this }+ );++ new aws.iam.RolePolicy(+ `${SERVICE_NAME}-image-optimizer-s3-policy`,+ {+ role: imageOptimizerRole.id,+ policy: staticFilesBucket.arn.apply((bucketArn) =>+ JSON.stringify({+ Version: '2012-10-17',+ Statement: [+ {+ Effect: 'Allow',+ Action: 's3:GetObject',+ Resource: `${bucketArn}/*`,+ },+ {+ Effect: 'Allow',+ Action: 's3:PutObject',+ Resource: `${bucketArn}/file/*/*`,+ },+ ],+ })+ ),+ },+ { parent: this }+ );++ const imageOptimizerLambda = new aws.lambda.Function(+ `${SERVICE_NAME}-image-optimizer`,+ {+ name: `${SERVICE_NAME}-image-optimizer-${stack}`,+ role: imageOptimizerRole.arn,+ handler: 'bootstrap',+ runtime: 'provided.al2023',+ code: new pulumi.asset.FileArchive(+ `${BASE_PATH}/target/lambda/image_optimizer/bootstrap.zip`+ ),+ timeout: 30,+ memorySize: 1536,+ environment: {+ variables: {+ BUCKET: STATIC_FILE_BUCKET,+ },+ },+ tags: this.tags,+ },+ { parent: this }+ );++ new aws.iam.RolePolicy(+ `${SERVICE_NAME}-image-optimizer-invoke-policy`,+ {+ role: imageOptimizerRole.id,+ policy: imageOptimizerLambda.arn.apply((lambdaArn) =>+ JSON.stringify({+ Version: '2012-10-17',+ Statement: [+ {+ Effect: 'Allow',+ Action: 'lambda:InvokeFunction',+ Resource: lambdaArn,+ },+ ],+ })+ ),+ },+ { parent: this }+ );++ const imageOptimizerUrl = new aws.lambda.FunctionUrl(+ `${SERVICE_NAME}-image-optimizer-url`,+ {+ functionName: imageOptimizerLambda.name,+ authorizationType: 'AWS_IAM',+ },+ { parent: this }+ );+const notFound = new aws.s3.BucketObject('object',{@@ -157,6 +258,8 @@ export class StaticFileService extends pulumi.ComponentResource {`static-files-${stack}`,{bucket: staticFilesBucket,+ imageOptimizerUrl: imageOptimizerUrl.functionUrl,+ imageOptimizerFunctionName: imageOptimizerLambda.name,api: lb,stackName: stack,customDomain: {diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex 18688ece28..cb56fb0b33 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -5351,6 +5351,26 @@ dependencies = ["quick-error",]+[[package]]+name = "image_optimizer"+version = "0.1.0"+dependencies = [+ "anyhow",+ "aws-sdk-lambda",+ "aws-sdk-s3",+ "base64 0.22.1",+ "image",+ "lambda_runtime",+ "macro_aws_config",+ "macro_entrypoint",+ "macro_env_var",+ "serde",+ "serde_json",+ "serde_urlencoded",+ "tokio",+ "tracing",+]+[[package]]name = "image_proxy_service"version = "0.1.0"diff --git a/rust/cloud-storage/Cargo.toml b/rust/cloud-storage/Cargo.tomlindex 8fc8d1208e..0cfcc02098 100644--- a/rust/cloud-storage/Cargo.toml+++ b/rust/cloud-storage/Cargo.toml@@ -54,6 +54,7 @@ members = ["fusionauth","github","gmail_client",+ "image_optimizer","image_proxy_service","integration_tests/*","invite_email",@@ -178,6 +179,7 @@ hex = "0.4.3"hmac = "0.12.1"http = "1"http-body-util = "0.1.2"+image = "0.25"inquire = "0.7"itertools = "0.14"jsonwebtoken = { git = "https://github.com/whutchinson98/jsonwebtoken", features = [@@ -264,5 +266,6 @@ once_cell = "1.21.3"scraper = "0.18"strum_macros = "0.27.1"unicode-segmentation = "1.9.0"+serde_urlencoded = "0.7.1"url = "2.5.0"zip = "=2.4.2"diff --git a/rust/cloud-storage/ai/Cargo.toml b/rust/cloud-storage/ai/Cargo.tomlindex 4dc5cabb17..5f041da7b4 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"-webp = "0.3.1"+image = { workspace = true }+webp = { version = "0.3.1" }model_file_type = { path = "../model_file_type"}ai_format = {path = "../ai_format"}diff --git a/rust/cloud-storage/decode_jwt/Cargo.toml b/rust/cloud-storage/decode_jwt/Cargo.tomlindex 33a82863c3..cfb31748e9 100644--- a/rust/cloud-storage/decode_jwt/Cargo.toml+++ b/rust/cloud-storage/decode_jwt/Cargo.toml@@ -23,7 +23,7 @@ http-body-util = { workspace = true }jsonwebtoken = { workspace = true }macro_auth = { path = "../macro_auth", features = ["testing"] }serde_json = { workspace = true }-serde_urlencoded = "0.7"+serde_urlencoded = { workspace = true }tokio = { workspace = true, features = ["macros", "rt"] }tower = { workspace = true }url = { workspace = true }diff --git a/rust/cloud-storage/fusionauth/Cargo.toml b/rust/cloud-storage/fusionauth/Cargo.tomlindex c5f08f2af3..83f7cd41c7 100644--- a/rust/cloud-storage/fusionauth/Cargo.toml+++ b/rust/cloud-storage/fusionauth/Cargo.toml@@ -11,7 +11,7 @@ macro_env = { path = "../macro_env" }reqwest = { workspace = true }serde = { workspace = true }serde_json = { workspace = true }-serde_urlencoded = "0.7.1"+serde_urlencoded = { workspace = true }thiserror = { workspace = true }tracing = { workspace = true }urlencoding = { workspace = true }diff --git a/rust/cloud-storage/image_optimizer/Cargo.toml b/rust/cloud-storage/image_optimizer/Cargo.tomlnew file mode 100644index 0000000000..a440d0d312--- /dev/null+++ b/rust/cloud-storage/image_optimizer/Cargo.toml@@ -0,0 +1,21 @@+[package]+edition = "2024"+name = "image_optimizer"+publish = false+version = "0.1.0"++[dependencies]+anyhow = { workspace = true }+aws-sdk-lambda = { workspace = true }+aws-sdk-s3 = { workspace = true }+base64 = { workspace = true }+image = { workspace = true }+lambda_runtime = { workspace = true }+macro_aws_config = { path = "../macro_aws_config", features = ["s3"] }+macro_entrypoint = { path = "../macro_entrypoint" }+macro_env_var = { path = "../macro_env_var" }+serde = { workspace = true }+serde_json = { workspace = true }+serde_urlencoded = { workspace = true }+tokio = { workspace = true }+tracing = { workspace = true }diff --git a/rust/cloud-storage/image_optimizer/justfile b/rust/cloud-storage/image_optimizer/justfilenew file mode 100644index 0000000000..4f1c35b27e--- /dev/null+++ b/rust/cloud-storage/image_optimizer/justfile@@ -0,0 +1,4 @@+lambda_name := file_name(justfile_directory())++build:+ cargo lambda build --release --bin {{lambda_name}} --output-format zipdiff --git a/rust/cloud-storage/image_optimizer/src/handler.rs b/rust/cloud-storage/image_optimizer/src/handler.rsnew file mode 100644index 0000000000..12507f04be--- /dev/null+++ b/rust/cloud-storage/image_optimizer/src/handler.rs@@ -0,0 +1,145 @@+use lambda_runtime::Error;+use std::collections::HashMap;++use crate::request::{AsyncResizeRequest, FunctionUrlRequest};+use crate::response::{FunctionUrlResponse, error_response, image_response};+use crate::transform::{TransformParams, transform_image};+use crate::{AppContext, DEFAULT_CACHE_TTL, s3};++/// Performs the actual image transform and caches the result in S3.+///+/// 1. Fetch the original from S3.+/// 2. Attempt the transform — on failure, fall back to the original so we still+/// cache something at the variant key (prevents repeated retries).+/// 3. Store the result at the variant S3 key with a long-lived cache header.+/// Future requests hit S3/CloudFront directly without invoking the Lambda.+#[tracing::instrument(skip(ctx), fields(key = %req.transformed_s3_key), err)]+pub async fn handle_async_resize(+ ctx: &AppContext,+ req: AsyncResizeRequest,+) -> Result<FunctionUrlResponse, Error> {+ // 1. Fetch the original file from S3.+ let (original_bytes, content_type) =+ s3::fetch(&ctx.s3_client, &ctx.bucket, &req.original_key).await?;++ let params = TransformParams::from_async_request(&req);+ let original_mime = content_type+ .as_deref()+ .unwrap_or("application/octet-stream");++ // 2. Transform. On failure (unsupported format, corrupt file, etc.) cache the+ // original at the variant key so the next request is served from S3 without+ // re-invoking the Lambda.+ let (bytes, mime) = match transform_image(&original_bytes, ¶ms) {+ Ok((transformed_bytes, output_format)) => (transformed_bytes, output_format.to_mime_type()),+ Err(e) => {+ tracing::warn!(error=?e, "transform failed, caching original at transformed key");+ (original_bytes, original_mime)+ }+ };++ // 3. Store the result at the variant S3 key.+ s3::store(+ &ctx.s3_client,+ &ctx.bucket,+ &req.transformed_s3_key,+ bytes,+ mime,+ DEFAULT_CACHE_TTL,+ )+ .await?;++ Ok(FunctionUrlResponse {+ status_code: 200,+ headers: HashMap::new(),+ body: None,+ is_base64_encoded: false,+ })+}++/// Handles a CloudFront origin-group failover request.+///+/// The CF URL rewrite function has already resolved `format=auto` and rewritten+/// the URI from `/file/{uuid}?size=1080&format=avif` to+/// `/file/{uuid}/format=avif,size=1080`. S3 (primary origin) returned 403/404,+/// so the request failed over here.+///+/// 1. File ID and transform suffix are extracted from `rawPath` during deserialization.+/// 2. Fetch the original from S3.+/// 3. No transform suffix → serve the original with long-lived cache headers.+/// 4. Has suffix → fire-and-forget an async self-invocation to resize and cache+/// the variant, then return the original with `no-cache` so the next request+/// hits the now-cached variant in S3.+#[tracing::instrument(skip(ctx, request), fields(file_id), err)]+pub async fn handle_cloudfront_request(+ ctx: &AppContext,+ request: FunctionUrlRequest,+) -> Result<FunctionUrlResponse, Error> {+ // 1. File ID and transform suffix are extracted during deserialization.+ let Some(file_id) = &request.path.file_id else {+ return Ok(error_response(400, "Invalid request path"));+ };+ tracing::Span::current().record("file_id", file_id.as_str());++ // 2. Fetch the original from S3.+ let original_key = format!("file/{file_id}");++ let (original_bytes, content_type) =+ match s3::fetch(&ctx.s3_client, &ctx.bucket, &original_key).await {+ Ok(result) => result,+ Err(e) => {+ tracing::warn!(error=?e, "original not found");+ return Ok(error_response(404, "Image not found"));+ }+ };++ let original_mime = content_type+ .as_deref()+ .unwrap_or("application/octet-stream");++ let cache_control = format!("public, max-age={DEFAULT_CACHE_TTL}");++ // 3. No transform suffix → serve original with long-lived cache.+ let Some(suffix) = &request.path.transform_suffix else {+ return Ok(image_response(+ 200,+ &original_bytes,+ original_mime,+ &cache_control,+ ));+ };++ // 4. Parse the suffix with serde_urlencoded and kick off async resize.+ // Return the original immediately with no-cache headers; the async+ // invocation stores the resized variant at the transformed S3 key so+ // CloudFront serves it on subsequent requests.+ let Some(params) = TransformParams::from_suffix(suffix) else {+ return Ok(error_response(400, "Invalid transform parameters"));+ };++ let transformed_s3_key = format!("file/{file_id}/{suffix}");++ let async_request = AsyncResizeRequest {+ original_key,+ transformed_s3_key,+ size: params.size,+ };++ let payload = serde_json::to_vec(&async_request)?;+ ctx.lambda_client+ .invoke()+ .function_name(&ctx.function_name)+ .invocation_type(aws_sdk_lambda::types::InvocationType::Event)+ .payload(aws_sdk_lambda::primitives::Blob::new(payload))+ .send()+ .await+ .inspect_err(|e| tracing::error!(error=?e, "failed to invoke async resize"))+ .ok();++ Ok(image_response(+ 200,+ &original_bytes,+ original_mime,+ "no-store, no-cache, must-revalidate",+ ))+}diff --git a/rust/cloud-storage/image_optimizer/src/main.rs b/rust/cloud-storage/image_optimizer/src/main.rsnew file mode 100644index 0000000000..c2b004c479--- /dev/null+++ b/rust/cloud-storage/image_optimizer/src/main.rs@@ -0,0 +1,61 @@+mod handler;+mod request;+mod response;+mod s3;+mod transform;++use aws_sdk_lambda::Client as LambdaClient;+use aws_sdk_s3::Client as S3Client;+use lambda_runtime::{Error, LambdaEvent, run, service_fn};+use request::LambdaRequest;++macro_env_var::env_var! {+ pub struct EnvConfig {+ pub Bucket,+ pub AwsLambdaFunctionName,+ }+}++/// One year in seconds.+pub const DEFAULT_CACHE_TTL: &str = "31536000";++/// Shared state available to all Lambda invocations.+#[derive(Clone)]+pub struct AppContext {+ pub s3_client: S3Client,+ pub lambda_client: LambdaClient,+ pub bucket: String,+ pub function_name: String,+}++async fn handle(+ ctx: AppContext,+ event: LambdaEvent<LambdaRequest>,+) -> Result<response::FunctionUrlResponse, Error> {+ let (request, _) = event.into_parts();+ match request {+ LambdaRequest::AsyncResize(req) => handler::handle_async_resize(&ctx, req).await,+ LambdaRequest::FunctionUrl(req) => handler::handle_cloudfront_request(&ctx, req).await,+ }+}++#[tokio::main]+async fn main() -> Result<(), Error> {+ macro_entrypoint::MacroEntrypoint::default().init();++ let aws_config = macro_aws_config::get_macro_aws_config().await;+ let env = EnvConfig::unwrap_new();++ let ctx = AppContext {+ s3_client: S3Client::new(&aws_config),+ lambda_client: LambdaClient::new(&aws_config),+ bucket: env.bucket.to_string(),+ function_name: env.aws_lambda_function_name.to_string(),+ };++ run(service_fn(move |event: LambdaEvent<LambdaRequest>| {+ let ctx = ctx.clone();+ async move { handle(ctx, event).await }+ }))+ .await+}diff --git a/rust/cloud-storage/image_optimizer/src/request.rs b/rust/cloud-storage/image_optimizer/src/request.rsnew file mode 100644index 0000000000..fb2ddc29f6--- /dev/null+++ b/rust/cloud-storage/image_optimizer/src/request.rs@@ -0,0 +1,68 @@+#[cfg(test)]+mod test;++use serde::{Deserialize, Serialize};++/// Incoming request from a Lambda Function URL (forwarded by CloudFront).+#[derive(Deserialize)]+pub struct FunctionUrlRequest {+ /// Parsed from the CF-rewritten `rawPath`, e.g. `/file/{uuid}/format=avif,size=1080`.+ #[serde(rename = "rawPath", default, deserialize_with = "deserialize_path")]+ pub path: FilePath,+}++/// File path parsed from the CloudFront-rewritten URI.+#[derive(Default)]+pub struct FilePath {+ /// The file ID (UUID) extracted from the path.+ pub file_id: Option<String>,+ /// The transform suffix (e.g. `format=avif,size=1080`), set by the CF URL rewrite function.+ pub transform_suffix: Option<String>,+}++fn deserialize_path<'de, D: serde::Deserializer<'de>>(+ deserializer: D,+) -> Result<FilePath, D::Error> {+ let raw = String::deserialize(deserializer)?;++ let Some(after_prefix) = raw+ .trim_start_matches('/')+ .strip_prefix("file/")+ .filter(|s| !s.is_empty())+ else {+ return Ok(FilePath::default());+ };++ Ok(match after_prefix.split_once('/') {+ None => FilePath {+ file_id: Some(after_prefix.to_string()),+ transform_suffix: None,+ },+ Some((id, suffix)) if !id.is_empty() && !suffix.is_empty() => FilePath {+ file_id: Some(id.to_string()),+ transform_suffix: Some(suffix.to_string()),+ },+ _ => FilePath::default(),+ })+}++/// Payload for an async (self-invoked) resize job.+#[derive(Debug, Deserialize, Serialize)]+pub struct AsyncResizeRequest {+ /// S3 key of the original file, e.g. `file/{uuid}`.+ pub original_key: String,+ /// S3 key where the transformed result will be stored.+ pub transformed_s3_key: String,+ /// Target size in pixels (longest edge).+ pub size: u32,+}++/// Top-level Lambda event — either a CloudFront-originated request or an async resize job.+#[derive(Deserialize)]+#[serde(untagged)]+pub enum LambdaRequest {+ /// Self-invoked async resize (tried first because it has required fields that disambiguate).+ AsyncResize(AsyncResizeRequest),+ /// CloudFront Function URL request.+ FunctionUrl(FunctionUrlRequest),+}diff --git a/rust/cloud-storage/image_optimizer/src/request/test.rs b/rust/cloud-storage/image_optimizer/src/request/test.rsnew file mode 100644index 0000000000..b2b718b64f--- /dev/null+++ b/rust/cloud-storage/image_optimizer/src/request/test.rs@@ -0,0 +1,96 @@+use super::*;+use crate::transform::TransformParams;++fn event(raw_path: &str) -> serde_json::Value {+ serde_json::json!({ "rawPath": raw_path })+}++#[test]+fn original_file() {+ let req: FunctionUrlRequest = serde_json::from_value(event("/file/abc-123")).unwrap();+ assert_eq!(req.path.file_id.as_deref(), Some("abc-123"));+ assert_eq!(req.path.transform_suffix, None);+}++#[test]+fn variant_with_suffix() {+ let req: FunctionUrlRequest = serde_json::from_value(event("/file/abc-123/size=1080")).unwrap();+ assert_eq!(req.path.file_id.as_deref(), Some("abc-123"));+ assert_eq!(req.path.transform_suffix.as_deref(), Some("size=1080"));+}++#[test]+fn uuid_file_id() {+ let req: FunctionUrlRequest =+ serde_json::from_value(event("/file/e2df5846-c391-4df6-952b-c2bb259c9ea7/size=720"))+ .unwrap();+ assert_eq!(+ req.path.file_id.as_deref(),+ Some("e2df5846-c391-4df6-952b-c2bb259c9ea7")+ );+ assert_eq!(req.path.transform_suffix.as_deref(), Some("size=720"));+}++#[test]+fn wrong_prefix() {+ let req: FunctionUrlRequest = serde_json::from_value(event("/other/abc-123")).unwrap();+ assert_eq!(req.path.file_id, None);+}++#[test]+fn empty_file_id() {+ let req: FunctionUrlRequest = serde_json::from_value(event("/file/")).unwrap();+ assert_eq!(req.path.file_id, None);+}++#[test]+fn trailing_slash_no_suffix() {+ let req: FunctionUrlRequest = serde_json::from_value(event("/file/abc-123/")).unwrap();+ assert_eq!(req.path.file_id, None);+}++#[test]+fn root_path() {+ let req: FunctionUrlRequest = serde_json::from_value(event("/")).unwrap();+ assert_eq!(req.path.file_id, None);+}++#[test]+fn suffix_roundtrip() {+ let req: FunctionUrlRequest = serde_json::from_value(event("/file/abc/size=500")).unwrap();+ let suffix = req.path.transform_suffix.as_deref().unwrap();+ let params = TransformParams::from_suffix(suffix).unwrap();+ assert_eq!(params.size, 500);+}++#[test]+fn suffix_missing_size_returns_none() {+ assert!(TransformParams::from_suffix("other=123").is_none());+}++#[test]+fn suffix_size_zero_returns_none() {+ assert!(TransformParams::from_suffix("size=0").is_none());+}++#[test]+fn suffix_size_over_max_returns_none() {+ assert!(TransformParams::from_suffix("size=9999").is_none());+}++#[test]+fn lambda_request_dispatches_async_resize() {+ let payload = serde_json::json!({+ "original_key": "file/abc",+ "transformed_s3_key": "file/abc/size=1080",+ "size": 1080+ });+ let req: LambdaRequest = serde_json::from_value(payload).unwrap();+ assert!(matches!(req, LambdaRequest::AsyncResize(_)));+}++#[test]+fn lambda_request_dispatches_function_url() {+ let req: LambdaRequest = serde_json::from_value(event("/file/abc")).unwrap();+ assert!(matches!(req, LambdaRequest::FunctionUrl(_)));+}diff --git a/rust/cloud-storage/image_optimizer/src/response.rs b/rust/cloud-storage/image_optimizer/src/response.rsnew file mode 100644index 0000000000..ec015c4a5e--- /dev/null+++ b/rust/cloud-storage/image_optimizer/src/response.rs@@ -0,0 +1,47 @@+use base64::Engine;+use serde::Serialize;+use std::collections::HashMap;++/// Lambda Function URL response returned to CloudFront.+#[derive(Serialize)]+pub struct FunctionUrlResponse {+ #[serde(rename = "statusCode")]+ pub status_code: u16,+ pub headers: HashMap<String, String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub body: Option<String>,+ #[serde(rename = "isBase64Encoded")]+ pub is_base64_encoded: bool,+}++/// Builds a base64-encoded image response with the given cache-control header.+pub fn image_response(+ status: u16,+ body: &[u8],+ content_type: &str,+ cache_control: &str,+) -> FunctionUrlResponse {+ let mut headers = HashMap::new();+ headers.insert("content-type".to_string(), content_type.to_string());+ headers.insert("cache-control".to_string(), cache_control.to_string());++ FunctionUrlResponse {+ status_code: status,+ headers,+ body: Some(base64::engine::general_purpose::STANDARD.encode(body)),+ is_base64_encoded: true,+ }+}++/// Builds a JSON error response.+pub fn error_response(status: u16, message: &str) -> FunctionUrlResponse {+ let mut headers = HashMap::new();+ headers.insert("content-type".to_string(), "application/json".to_string());++ FunctionUrlResponse {+ status_code: status,+ headers,+ body: Some(serde_json::json!({"error": message}).to_string()),+ is_base64_encoded: false,+ }+}diff --git a/rust/cloud-storage/image_optimizer/src/s3.rs b/rust/cloud-storage/image_optimizer/src/s3.rsnew file mode 100644index 0000000000..5216d882bc--- /dev/null+++ b/rust/cloud-storage/image_optimizer/src/s3.rs@@ -0,0 +1,46 @@+use anyhow::{Context, Result};+use aws_sdk_s3::Client;++/// Downloads an object from S3, returning its bytes and content-type.+pub async fn fetch(client: &Client, bucket: &str, key: &str) -> Result<(Vec<u8>, Option<String>)> {+ let output = client+ .get_object()+ .bucket(bucket)+ .key(key)+ .send()+ .await+ .context("failed to get object from S3")?;++ let content_type = output.content_type().map(String::from);+ let bytes = output+ .body+ .collect()+ .await+ .context("failed to read S3 body")?+ .into_bytes()+ .to_vec();++ Ok((bytes, content_type))+}++/// Uploads an object to S3 with the given content-type and cache-control.+pub async fn store(+ client: &Client,+ bucket: &str,+ key: &str,+ body: Vec<u8>,+ content_type: &str,+ cache_ttl: &str,+) -> Result<()> {+ client+ .put_object()+ .bucket(bucket)+ .key(key)+ .body(body.into())+ .content_type(content_type)+ .cache_control(format!("public, max-age={cache_ttl}"))+ .send()+ .await+ .context("failed to store object in S3")?;+ Ok(())+}diff --git a/rust/cloud-storage/image_optimizer/src/transform.rs b/rust/cloud-storage/image_optimizer/src/transform.rsnew file mode 100644index 0000000000..345a9a2071--- /dev/null+++ b/rust/cloud-storage/image_optimizer/src/transform.rs@@ -0,0 +1,87 @@+use anyhow::{Context, Result, bail};+use image::imageops::FilterType;+use image::{ImageDecoder, ImageFormat};+use serde::Deserialize;+use std::io::Cursor;++use crate::request::AsyncResizeRequest;++const MAX_SIZE: u32 = 4096;++/// Raw query parameters deserialized from the CF-rewritten path suffix.+#[derive(Deserialize)]+pub struct QueryParams {+ /// Target size in pixels (longest edge).+ pub size: Option<u32>,+}++/// Validated resize parameters.+pub struct TransformParams {+ /// Target size in pixels (longest edge). Images smaller than this are not upscaled.+ pub size: u32,+}++impl TransformParams {+ /// Parses the CF-rewritten path suffix (e.g. `size=1080`) using `serde_urlencoded`.+ /// Returns `None` if `size` is absent or out of range.+ pub fn from_suffix(suffix: &str) -> Option<Self> {+ let query: QueryParams = serde_urlencoded::from_str(&suffix.replace(',', "&")).ok()?;+ let size = query.size.filter(|s| (1..=MAX_SIZE).contains(s))?;+ Some(Self { size })+ }++ /// Reconstructs transform parameters from an [`AsyncResizeRequest`] payload.+ pub fn from_async_request(req: &AsyncResizeRequest) -> Self {+ Self { size: req.size }+ }+}++/// Decodes, resizes, and re-encodes an image in its original format.+///+/// 1. Detect the source format from magic bytes.+/// 2. Decode and apply EXIF orientation.+/// 3. Downscale if either dimension exceeds `params.size` (aspect-ratio-preserving).+/// 4. Re-encode in the source format. Bails if the format cannot be written.+///+/// Animated formats (GIF) are returned as-is because frame-by-frame resizing is not supported.+pub fn transform_image(bytes: &[u8], params: &TransformParams) -> Result<(Vec<u8>, ImageFormat)> {+ // 1. Detect source format from magic bytes.+ let source_format = match image::guess_format(bytes) {+ Ok(f) => f,+ Err(e) => bail!("failed to detect image format: {e}"),+ };++ if source_format == ImageFormat::Gif {+ return Ok((bytes.to_vec(), ImageFormat::Gif));+ }++ if !source_format.can_write() {+ bail!("format {source_format:?} cannot be re-encoded");+ }++ // 2. Decode and correct for EXIF orientation.+ let mut reader = image::ImageReader::new(Cursor::new(bytes));+ reader.set_format(source_format);+ let mut decoder = reader.into_decoder().context("failed to create decoder")?;+ let orientation = decoder+ .orientation()+ .unwrap_or(image::metadata::Orientation::NoTransforms);+ let mut img = image::DynamicImage::from_decoder(decoder).context("failed to decode image")?;+ img.apply_orientation(orientation);++ // 3. Downscale if the image is larger than the requested size. Images already+ // at or below the target size are left untouched (no upscaling).+ let size = params.size;+ let img = if img.width() > size || img.height() > size {+ img.resize(size, size, FilterType::Lanczos3)+ } else {+ img+ };++ // 4. Re-encode in the source format.+ let mut buf = Cursor::new(Vec::new());+ img.write_to(&mut buf, source_format)+ .context("failed to encode image")?;++ Ok((buf.into_inner(), source_format))+}diff --git a/rust/cloud-storage/justfile b/rust/cloud-storage/justfileindex d0da8a2805..57461e8862 100644--- a/rust/cloud-storage/justfile+++ b/rust/cloud-storage/justfile@@ -47,6 +47,7 @@ build_lambdas:ulimit -n 10240 && just user_link_cleanup_handler/buildulimit -n 10240 && just email_scheduled_handler/buildulimit -n 10240 && just email_sfs_delete_handler/build+ ulimit -n 10240 && just image_optimizer/build# TESTINGdiff --git a/rust/cloud-storage/macro_middleware/Cargo.toml b/rust/cloud-storage/macro_middleware/Cargo.tomlindex 0f13f2ec01..e7191a390a 100644--- a/rust/cloud-storage/macro_middleware/Cargo.toml+++ b/rust/cloud-storage/macro_middleware/Cargo.toml@@ -52,5 +52,5 @@ user_quota = { path = "../user_quota", optional = true }uuid = { workspace = true }[dev-dependencies]-serde_urlencoded = "0.7"+serde_urlencoded = { workspace = true }urlencoding = { workspace = true }diff --git a/rust/cloud-storage/s3_key/src/static_file_key.rs b/rust/cloud-storage/s3_key/src/static_file_key.rsindex 4a897b0026..35b953a786 100644--- a/rust/cloud-storage/s3_key/src/static_file_key.rs+++ b/rust/cloud-storage/s3_key/src/static_file_key.rs@@ -1,39 +1,86 @@const STATIC_FILE_PREFIX: &str = "file";/// Represents an S3 key in the static file storage bucket.-/// Format: `file/{file_id}`+///+/// Original: `file/{file_id}`+/// Variant: `file/{file_id}/{transform_key}`#[derive(Eq, PartialEq, Debug, Clone)]-pub struct StaticFileKey {- /// The file ID (UUID).- pub file_id: String,+pub enum StaticFileKey {+ /// The original uploaded file.+ Original {+ /// The file ID (UUID).+ file_id: String,+ },+ /// A transformed variant of the file (resized, reformatted, etc.).+ Variant {+ /// The file ID (UUID).+ file_id: String,+ /// The opaque transform key (e.g. `format=avif,size=1080`).+ transform_key: String,+ },}impl StaticFileKey {- /// Creates a new static file key from a file ID.+ /// Creates a new original file key from a file ID.pub fn new(file_id: impl Into<String>) -> Self {- Self {+ Self::Original {file_id: file_id.into(),}}+ /// Returns the file ID.+ pub fn file_id(&self) -> &str {+ match self {+ Self::Original { file_id } | Self::Variant { file_id, .. } => file_id,+ }+ }++ /// Returns the S3 key prefix for all variants of this file.+ /// Format: `file/{file_id}/`+ pub fn variant_prefix(&self) -> String {+ format!("{STATIC_FILE_PREFIX}/{}/", self.file_id())+ }+/// Parses an S3 key from the static file storage bucket.pub fn from_s3_key(key: &str) -> Result<Self, anyhow::Error> {- let file_id = key+ let rest = key.strip_prefix(&format!("{STATIC_FILE_PREFIX}/")).ok_or_else(|| anyhow::anyhow!("expected key to start with '{STATIC_FILE_PREFIX}/'"))?;- if file_id.is_empty() {+ if rest.is_empty() {anyhow::bail!("file_id is empty");}- Ok(Self {- file_id: file_id.to_string(),- })+ match rest.split_once('/') {+ None => Ok(Self::Original {+ file_id: rest.to_string(),+ }),+ Some((file_id, transform_key)) => {+ if file_id.is_empty() {+ anyhow::bail!("file_id is empty");+ }+ if transform_key.is_empty() {+ anyhow::bail!("transform_key is empty");+ }+ Ok(Self::Variant {+ file_id: file_id.to_string(),+ transform_key: transform_key.to_string(),+ })+ }+ }}/// Reconstructs the S3 key string.pub fn to_key(&self) -> String {- format!("{STATIC_FILE_PREFIX}/{}", self.file_id)+ match self {+ Self::Original { file_id } => format!("{STATIC_FILE_PREFIX}/{file_id}"),+ Self::Variant {+ file_id,+ transform_key,+ } => {+ format!("{STATIC_FILE_PREFIX}/{file_id}/{transform_key}")+ }+ }}}diff --git a/rust/cloud-storage/s3_key/src/static_file_key/test.rs b/rust/cloud-storage/s3_key/src/static_file_key/test.rsindex fc21272449..31357e887c 100644--- a/rust/cloud-storage/s3_key/src/static_file_key/test.rs+++ b/rust/cloud-storage/s3_key/src/static_file_key/test.rs@@ -4,14 +4,29 @@ use super::*;fn test_new() {let key = StaticFileKey::new("abc-123");assert_eq!(key.to_key(), "file/abc-123");- assert_eq!(key.file_id, "abc-123");+ assert_eq!(key.file_id(), "abc-123");}#[test]-fn test_from_s3_key() {+fn test_from_s3_key_original() {let key = StaticFileKey::from_s3_key("file/abc-123").unwrap();- assert_eq!(key.file_id, "abc-123");+ assert_eq!(key.file_id(), "abc-123");assert_eq!(key.to_key(), "file/abc-123");+ assert!(matches!(key, StaticFileKey::Original { .. }));+}++#[test]+fn test_from_s3_key_variant() {+ let key = StaticFileKey::from_s3_key("file/abc-123/format=avif,size=1080").unwrap();+ assert_eq!(key.file_id(), "abc-123");+ assert_eq!(key.to_key(), "file/abc-123/format=avif,size=1080");+ assert!(matches!(+ key,+ StaticFileKey::Variant {+ ref transform_key,+ ..+ } if transform_key == "format=avif,size=1080"+ ));}#[test]@@ -20,6 +35,19 @@ fn test_display() {assert_eq!(format!("{key}"), "file/abc-123");}+#[test]+fn test_variant_prefix() {+ let key = StaticFileKey::new("abc-123");+ assert_eq!(key.variant_prefix(), "file/abc-123/");+}++#[test]+fn test_roundtrip() {+ let key = StaticFileKey::from_s3_key("file/abc-123/format=webp,quality=90,size=300").unwrap();+ let reparsed = StaticFileKey::from_s3_key(&key.to_key()).unwrap();+ assert_eq!(key, reparsed);+}+#[test]fn test_invalid_prefix() {assert!(StaticFileKey::from_s3_key("other/abc-123").is_err());@@ -29,3 +57,8 @@ fn test_invalid_prefix() {fn test_empty_file_id() {assert!(StaticFileKey::from_s3_key("file/").is_err());}++#[test]+fn test_empty_transform_key() {+ assert!(StaticFileKey::from_s3_key("file/abc-123/").is_err());+}diff --git a/rust/cloud-storage/serde_utils/Cargo.toml b/rust/cloud-storage/serde_utils/Cargo.tomlindex 6038862f65..591c2b795e 100644--- a/rust/cloud-storage/serde_utils/Cargo.toml+++ b/rust/cloud-storage/serde_utils/Cargo.toml@@ -14,5 +14,5 @@ urlencoding = { version = "2", optional = true }[dev-dependencies]cool_asserts = "2"-serde_urlencoded = { version = "0.7" }+serde_urlencoded = { workspace = true }url = { workspace = true, features = ["serde"] }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.rsindex ffba3f8e8e..c3770634e2 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@@ -4,15 +4,19 @@ use anyhow::{Context, Result};#[tracing::instrument(skip(metadata_client))]pub async fn handle_s3_create(event: S3EventRecord, metadata_client: DynamodbClient) -> Result<()> {- let file_id = s3_key::StaticFileKey::from_s3_key(&event.s3.object.key)+ // Skip CloudFront image optimizer keys (e.g. "file/{uuid}/format=webp,width=300")+ if event.s3.object.key.matches('/').count() > 1 {+ return Ok(());+ }++ let key = s3_key::StaticFileKey::from_s3_key(&event.s3.object.key).inspect_err(|err| tracing::error!(error=?err, key=%event.s3.object.key, "unexpected s3 key format"),)- .context("failed to parse file_id from s3 key")?- .file_id;-+ .context("failed to parse file_id from s3 key")?;+ let file_id = key.file_id();metadata_client- .mark_uploaded(&file_id)+ .mark_uploaded(file_id).await.context("could not mark file uploaded")}diff --git a/rust/cloud-storage/static_file_service/src/api/file/bulk_delete_file.rs b/rust/cloud-storage/static_file_service/src/api/file/bulk_delete_file.rsindex a175bde3ef..495f3ce6d8 100644--- a/rust/cloud-storage/static_file_service/src/api/file/bulk_delete_file.rs+++ b/rust/cloud-storage/static_file_service/src/api/file/bulk_delete_file.rs@@ -173,6 +173,15 @@ pub async fn handle_bulk_delete_file(results[*idx].error = Some(format!("metadata deletion failed: {}", e));}}++ for (_, file_id) in &successful_indices_and_ids {+ let scaled_prefix = format!("file/{file_id}/");+ storage_client+ .delete_objects_by_prefix(&scaled_prefix)+ .await+ .inspect_err(|e| tracing::warn!(error=?e, file_id=%file_id, "failed to delete scaled variants"))+ .ok();+ }}// Calculate statisticsdiff --git a/rust/cloud-storage/static_file_service/src/api/file/delete_file.rs b/rust/cloud-storage/static_file_service/src/api/file/delete_file.rsindex f6ef6ca9da..38f7c4455d 100644--- a/rust/cloud-storage/static_file_service/src/api/file/delete_file.rs+++ b/rust/cloud-storage/static_file_service/src/api/file/delete_file.rs@@ -73,5 +73,12 @@ pub async fn handle_delete_file(}})?;+ let scaled_prefix = format!("file/{file_id}/");+ storage_client+ .delete_objects_by_prefix(&scaled_prefix)+ .await+ .inspect_err(|e| tracing::warn!(error=?e, "failed to delete scaled variants"))+ .ok();+Ok((StatusCode::OK, "Ok".to_string()).into_response())}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.rsindex e5ce5c4236..13b8039bad 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@@ -63,6 +63,41 @@ impl S3Client {Ok(macro_aws_config::transform_aws_url(presigned_url.uri()))}+ #[tracing::instrument(skip(self), err)]+ pub async fn delete_objects_by_prefix(&self, prefix: &str) -> Result<()> {+ let mut continuation_token: Option<String> = None;++ loop {+ let mut req = self+ .inner+ .list_objects_v2()+ .bucket(&self.storage_bucket)+ .prefix(prefix);++ if let Some(token) = &continuation_token {+ req = req.continuation_token(token);+ }++ let response = req.send().await.context("failed to list objects")?;+ let keys: Vec<String> = response+ .contents()+ .iter()+ .filter_map(|obj| obj.key().map(String::from))+ .collect();++ if !keys.is_empty() {+ self.bulk_hard_delete_objects(keys).await;+ }++ match response.next_continuation_token() {+ Some(token) => continuation_token = Some(token.to_string()),+ None => break,+ }+ }++ Ok(())+ }+#[tracing::instrument(skip(self), fields(count = keys.len()))]pub async fn bulk_hard_delete_objects(&self, keys: Vec<String>) -> Vec<Result<()>> {if keys.is_empty() {diff --git a/rust/cloud-storage/target/lambda/image_optimizer/bootstrap.zip b/rust/cloud-storage/target/lambda/image_optimizer/bootstrap.zipnew file mode 100644index 0000000000..eaa68e3bd0Binary files /dev/null and b/rust/cloud-storage/target/lambda/image_optimizer/bootstrap.zip differ