Skip to content

🎥 Make videos programmatically with React

Lambda Go SDK: upload large inputProps to S3 (#8987)

iliya-vidrushb6b3e5187109
diff --git a/packages/lambda-go/go.mod b/packages/lambda-go/go.mod
index ef2a6cc9e6..2ef4a7765b 100644
--- a/packages/lambda-go/go.mod
+++ b/packages/lambda-go/go.mod
@@ -5,14 +5,31 @@ go 1.26
toolchain go1.26.5
require (
- github.com/aws/aws-sdk-go v1.55.8
+ github.com/aws/aws-sdk-go-v2 v1.42.1
+ github.com/aws/aws-sdk-go-v2/config v1.32.29
+ github.com/aws/aws-sdk-go-v2/service/lambda v1.96.0
+ github.com/aws/aws-sdk-go-v2/service/s3 v1.105.0
+ github.com/aws/smithy-go v1.27.3
github.com/go-playground/validator/v10 v10.13.0
)
require (
+ github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.14 // indirect
+ github.com/aws/aws-sdk-go-v2/credentials v1.19.28 // indirect
+ github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.30 // indirect
+ github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.30 // indirect
+ github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.30 // indirect
+ github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.31 // indirect
+ github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.13 // indirect
+ github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.23 // indirect
+ github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.30 // indirect
+ github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.31 // indirect
+ github.com/aws/aws-sdk-go-v2/service/signin v1.4.0 // indirect
+ github.com/aws/aws-sdk-go-v2/service/sso v1.32.0 // indirect
+ github.com/aws/aws-sdk-go-v2/service/ssooidc v1.37.0 // indirect
+ github.com/aws/aws-sdk-go-v2/service/sts v1.44.0 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
- github.com/jmespath/go-jmespath v0.4.0 // indirect
github.com/leodido/go-urn v1.2.3 // indirect
golang.org/x/crypto v0.52.0 // indirect
golang.org/x/sys v0.45.0 // indirect
diff --git a/packages/lambda-go/go.sum b/packages/lambda-go/go.sum
index f82dec35e0..67d8fcb0fa 100644
--- a/packages/lambda-go/go.sum
+++ b/packages/lambda-go/go.sum
@@ -1,5 +1,41 @@
-github.com/aws/aws-sdk-go v1.55.8 h1:JRmEUbU52aJQZ2AjX4q4Wu7t4uZjOu71uyNmaWlUkJQ=
-github.com/aws/aws-sdk-go v1.55.8/go.mod h1:ZkViS9AqA6otK+JBBNH2++sx1sgxrPKcSzPPvQkUtXk=
+github.com/aws/aws-sdk-go-v2 v1.42.1 h1:9eOTgu1z/dVtYpNZ3/8/XbbaX0x/BqE3HUzAzs6K0ek=
+github.com/aws/aws-sdk-go-v2 v1.42.1/go.mod h1:5pKeft2eJj+gElQ38Jqg4ibCqh+/AK33/0X3hip7IjM=
+github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.14 h1:3IZY0XAJquT3aHzbkHfPzy4ACPcEjVG0x87KOwtpqGY=
+github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.14/go.mod h1:zwM6veDkhGgQFqkBy+uT28AAYpLu+uFMlPl+rCg/73E=
+github.com/aws/aws-sdk-go-v2/config v1.32.29 h1:BcMHHnpiWKogf+gGfpj3K1w+Sktz29XDo/cPSAPO3FU=
+github.com/aws/aws-sdk-go-v2/config v1.32.29/go.mod h1:+Kbhn8Es4kPUph3F/0W7avykytc+Jh2Ld9/msv9ljV4=
+github.com/aws/aws-sdk-go-v2/credentials v1.19.28 h1:zTXJSsNcoO91/mTXsZoYf0AK8dvNPiA58/VtyGXR+wM=
+github.com/aws/aws-sdk-go-v2/credentials v1.19.28/go.mod h1:Kd9E0JzDBW/q1xbsHFrev/GnbAf5J0Ng8xoyc7HZ91Q=
+github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.30 h1:/hi1JADLEW9YYryEz1w4GQu0EtP23pP553Cf9KgsDV4=
+github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.30/go.mod h1:/3AOgy4K17Dm4ucMZVC/MJkzy5kmfKUcINRHZyo0koQ=
+github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.30 h1:xM/Is9cKMHa8Jj8zkvWhvrFkZsXJV9E+BB4g0HW0duQ=
+github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.30/go.mod h1:WueJeNDZvK1fMYEWJIkcivBfEzUkTpBhzlrUKKY8EuA=
+github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.30 h1:jn46zC9LdsVR/ZpMIJqMqb8hHv31BlLx3ulVqNspUOk=
+github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.30/go.mod h1:1hTMsAgbdS/AtUi4bw8+gUuh1pceo+eXRLfpSuSQj3M=
+github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.31 h1:3GUprIsfmGcC5SACIyB0e7E0BM1O1b3Erl5CePYIAeQ=
+github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.31/go.mod h1:7PuV1yl5e2xnUbm+RqvVg5i2iBM8EyijZNoI9wsOoOc=
+github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.13 h1:mbRIur/BiHK6SKPjoBIXSE/hJ6g6JGRLuxQy1jGjlN4=
+github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.13/go.mod h1:ITg9em2KbJx1s0y4aqRX5OYWG6HBZ5TVR//OdpEZ2CQ=
+github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.23 h1:9Fjh6fi/U5JEStVZijmaMpUwE/gvBJj7x2B/PjbO9To=
+github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.23/go.mod h1:iMoT2f1tClxrWAAnKCXjZQ6LOmfLrMG14wmnWpM+F14=
+github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.30 h1:/Z5jmNrKsSD7EmDjzAPsm/3L9IuOkzaynklJZ1qX7S4=
+github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.30/go.mod h1:lEzEZnOosE7zi8Z6royW1cFJTD9fpab4Ul1SBrllewk=
+github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.31 h1:uao4A3QZ5UmB326V6KF+qRpv9Tjz7IlnlnTbbANntlU=
+github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.31/go.mod h1:I/1+z0VwL1GhQyLgkoHDlygpUZ+iTAwOQ/NsftiUL2I=
+github.com/aws/aws-sdk-go-v2/service/lambda v1.96.0 h1:LQFghb8Azoe9vAmambrUCUoM/wfi437AMd70wQjCa20=
+github.com/aws/aws-sdk-go-v2/service/lambda v1.96.0/go.mod h1:gKWVtxlMTgoLU9m6FDw7z6FAEFh8u8CoaPJx0zWk5J8=
+github.com/aws/aws-sdk-go-v2/service/s3 v1.105.0 h1:XptwLL+UHXgafYMIHTy59IRovLbhz3znkxY2uS/pbXU=
+github.com/aws/aws-sdk-go-v2/service/s3 v1.105.0/go.mod h1:zdmCoFO/dSI7GlrwsPqFJI+WlFnSU4Tc8TJnlXrM1Do=
+github.com/aws/aws-sdk-go-v2/service/signin v1.4.0 h1:sLzmJGCMv+C8KqiJgEqDLB6vxaJGmobRh4rr//ZpA3w=
+github.com/aws/aws-sdk-go-v2/service/signin v1.4.0/go.mod h1:mxC0nT/C8wMMS97DemZPzvUZxvIt+2Iq+eS3JdFZGgg=
+github.com/aws/aws-sdk-go-v2/service/sso v1.32.0 h1:qjMmry/cBDee1E/2gyvel0uRYCi3mwRZ2hf6N+GAodo=
+github.com/aws/aws-sdk-go-v2/service/sso v1.32.0/go.mod h1:u8af9Nqkmqnr96f7v9nHqzZT9XBwbXEkTiqT4ROuJSE=
+github.com/aws/aws-sdk-go-v2/service/ssooidc v1.37.0 h1:fpOlDPI55HdszaxapEGk6HsGosOUaM2YPWJpjMgp8UI=
+github.com/aws/aws-sdk-go-v2/service/ssooidc v1.37.0/go.mod h1:DMPWJBjYs6+3+f/qhBFEFPPlQ6NlhWjai3dJNvipJ84=
+github.com/aws/aws-sdk-go-v2/service/sts v1.44.0 h1:bLZ0PolJ8J+HkJHztcXORUpHXBye2U8298lCEMi6ZCU=
+github.com/aws/aws-sdk-go-v2/service/sts v1.44.0/go.mod h1:9gdl4RrflIdpDb2TlXshWgR1F9TeCkvqDx77Vpr4Z/Q=
+github.com/aws/smithy-go v1.27.3 h1:F3Zb497UhhskkfpJmfkXswyo+t0sh9OTBnIHjogWbVY=
+github.com/aws/smithy-go v1.27.3/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
@@ -11,10 +47,6 @@ github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJn
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
github.com/go-playground/validator/v10 v10.13.0 h1:cFRQdfaSMCOSfGCCLB20MHvuoHb/s5G8L5pu2ppK5AQ=
github.com/go-playground/validator/v10 v10.13.0/go.mod h1:dwu7+CG8/CtBiJFZDz4e+5Upb6OLw04gtBYw0mcG/z4=
-github.com/jmespath/go-jmespath v0.4.0 h1:BEgLn5cpjn8UN1mAw4NjwDrS35OdebyEtFe+9YPoQUg=
-github.com/jmespath/go-jmespath v0.4.0/go.mod h1:T8mJZnbsbmF+m6zOOFylbeCJqk5+pHWvzYPziyZiYoo=
-github.com/jmespath/go-jmespath/internal/testify v1.5.1 h1:shLQSRRSCCPj3f2gpwzGwWFoC7ycTf1rcQZHOlsJ6N8=
-github.com/jmespath/go-jmespath/internal/testify v1.5.1/go.mod h1:L3OGu8Wl2/fWfCI6z80xFu9LTZmf1ZRjMHUOPmWr69U=
github.com/leodido/go-urn v1.2.3 h1:6BE2vPT0lqoz3fmOesHZiaiFh7889ssCo2GMvLCfiuA=
github.com/leodido/go-urn v1.2.3/go.mod h1:7ZrI8mTSeBSHl/UaRyKQW1qZeMgak41ANeCNaVckg+4=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
@@ -33,8 +65,6 @@ golang.org/x/sys v0.45.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc=
golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
-gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10=
-gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
diff --git a/packages/lambda-go/internalops.go b/packages/lambda-go/internalops.go
index dadcf06ad5..7ac1fd921d 100644
--- a/packages/lambda-go/internalops.go
+++ b/packages/lambda-go/internalops.go
@@ -5,12 +5,6 @@ import (
)
func constructRenderInternals(options *RemotionOptions) (*renderInternalOptions, error) {
-
- inputProps, serializeError := serializeInputProps(options.InputProps, "video-or-audio")
-
- if serializeError != nil {
- return nil, serializeError
- }
validate := validator.New()
validationErrors := validate.Struct(options)
if validationErrors != nil {
@@ -18,6 +12,14 @@ func constructRenderInternals(options *RemotionOptions) (*renderInternalOptions,
return nil, validationErrors
}
+ // Serialize (and, if too large, upload) inputProps only after validation so
+ // that an invalid request does not trigger S3 side effects.
+ inputProps, serializeError := serializeInputProps(options.InputProps, options.Region, "video-or-audio", options.ForceBucketName, options.ForcePathStyle)
+
+ if serializeError != nil {
+ return nil, serializeError
+ }
+
jpegQuality := 80
if options.JpegQuality != 0 {
jpegQuality = options.JpegQuality
diff --git a/packages/lambda-go/invocations.go b/packages/lambda-go/invocations.go
index 46bbbd4d5a..4ba196f055 100644
--- a/packages/lambda-go/invocations.go
+++ b/packages/lambda-go/invocations.go
@@ -1,24 +1,24 @@
package lambda_go_sdk
import (
+ "context"
"encoding/json"
"fmt"
- "github.com/aws/aws-sdk-go/aws"
- "github.com/aws/aws-sdk-go/aws/session"
- "github.com/aws/aws-sdk-go/service/lambda"
+ awsconfig "github.com/aws/aws-sdk-go-v2/config"
+ "github.com/aws/aws-sdk-go-v2/service/lambda"
)
func invokeRenderLambda(options RemotionOptions) (*RemotionRenderResponse, error) {
- // Create a new AWS session
- sess := session.Must(session.NewSessionWithOptions(session.Options{
- Config: aws.Config{Region: aws.String(options.Region)},
- SharedConfigState: session.SharedConfigEnable,
- }))
-
- // Create a new Lambda client
- svc := lambda.New(sess)
+ awsConfig, configError := awsconfig.LoadDefaultConfig(
+ context.Background(),
+ awsconfig.WithRegion(options.Region),
+ )
+ if configError != nil {
+ return nil, fmt.Errorf("could not load AWS config: %w", configError)
+ }
+ svc := lambda.NewFromConfig(awsConfig)
internalParams, validateError := constructRenderInternals(&options)
@@ -32,12 +32,12 @@ func invokeRenderLambda(options RemotionOptions) (*RemotionRenderResponse, error
}
invocationPayload := &lambda.InvokeInput{
- FunctionName: aws.String(options.FunctionName),
+ FunctionName: new(options.FunctionName),
Payload: internalParamJsonObject,
}
// Invoke Lambda function
- invocationResult, invocationError := svc.Invoke(invocationPayload)
+ invocationResult, invocationError := svc.Invoke(context.Background(), invocationPayload)
if invocationError != nil {
return nil, fmt.Errorf("could not invoke Lambda function %q: %w", options.FunctionName, invocationError)
@@ -57,14 +57,14 @@ func invokeRenderLambda(options RemotionOptions) (*RemotionRenderResponse, error
func invokeRenderProgressLambda(config RenderConfig) (*RenderProgress, error) {
- // Create a new AWS session
- sess := session.Must(session.NewSessionWithOptions(session.Options{
- Config: aws.Config{Region: aws.String(config.Region)},
- SharedConfigState: session.SharedConfigEnable,
- }))
-
- // Create a new Lambda client
- svc := lambda.New(sess)
+ awsConfig, configError := awsconfig.LoadDefaultConfig(
+ context.Background(),
+ awsconfig.WithRegion(config.Region),
+ )
+ if configError != nil {
+ return nil, fmt.Errorf("could not load AWS config: %w", configError)
+ }
+ svc := lambda.NewFromConfig(awsConfig)
internalParams, validateError := constructGetProgressInternals(&config)
@@ -78,12 +78,12 @@ func invokeRenderProgressLambda(config RenderConfig) (*RenderProgress, error) {
}
invocationParams := &lambda.InvokeInput{
- FunctionName: aws.String(config.FunctionName),
+ FunctionName: new(config.FunctionName),
Payload: internalParamsJSON,
}
// Invoke Lambda function
- invokeResult, invokeError := svc.Invoke(invocationParams)
+ invokeResult, invokeError := svc.Invoke(context.Background(), invocationParams)
if invokeError != nil {
return nil, fmt.Errorf("could not invoke Lambda function %q: %w", config.FunctionName, invokeError)
diff --git a/packages/lambda-go/lambda_go_sdk_test.go b/packages/lambda-go/lambda_go_sdk_test.go
index 5f8257ca6f..87f264a51d 100644
--- a/packages/lambda-go/lambda_go_sdk_test.go
+++ b/packages/lambda-go/lambda_go_sdk_test.go
@@ -1,11 +1,48 @@
package lambda_go_sdk
import (
+ "bytes"
+ "context"
"encoding/json"
+ "errors"
+ "io"
"log"
+ "strings"
"testing"
+
+ "github.com/aws/aws-sdk-go-v2/aws"
+ "github.com/aws/aws-sdk-go-v2/service/s3"
+ "github.com/aws/aws-sdk-go-v2/service/s3/types"
+ "github.com/aws/smithy-go"
)
+type bucketLocationGetterMock struct {
+ output *s3.GetBucketLocationOutput
+ err error
+}
+
+func (mock bucketLocationGetterMock) GetBucketLocation(
+ _ context.Context,
+ _ *s3.GetBucketLocationInput,
+ _ ...func(*s3.Options),
+) (*s3.GetBucketLocationOutput, error) {
+ return mock.output, mock.err
+}
+
+type objectUploaderMock struct {
+ input *s3.PutObjectInput
+ err error
+}
+
+func (mock *objectUploaderMock) PutObject(
+ _ context.Context,
+ input *s3.PutObjectInput,
+ _ ...func(*s3.Options),
+) (*s3.PutObjectOutput, error) {
+ mock.input = input
+ return &s3.PutObjectOutput{}, mock.err
+}
+
func TestPrintVersion(t *testing.T) {
payload, err := constructRenderInternals(&RemotionOptions{
Region: "us-east-1",
@@ -28,3 +65,234 @@ func TestPrintVersion(t *testing.T) {
println(string(jsonData))
}
+
+func TestSerializeNilInputProps(t *testing.T) {
+ result, err := serializeInputProps(nil, "us-east-1", "video-or-audio", "", false)
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if result.Type != "payload" || result.Payload != "{}" {
+ t.Fatalf("expected empty payload object, got %+v", result)
+ }
+}
+
+func TestSerializeInlineInputProps(t *testing.T) {
+ result, err := serializeInputProps(map[string]interface{}{"data": "hello"}, "us-east-1", "video-or-audio", "", false)
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if result.Type != "payload" {
+ t.Fatalf("expected inline payload, got type %q", result.Type)
+ }
+ if result.Payload != `{"data":"hello"}` {
+ t.Fatalf("unexpected payload: %q", result.Payload)
+ }
+}
+
+func TestNeedsUpload(t *testing.T) {
+ tests := []struct {
+ name string
+ payloadSize int
+ inputType string
+ want bool
+ }{
+ {name: "video below limit", payloadSize: maxVideoInlinePayloadSize - 1, inputType: "video-or-audio", want: false},
+ {name: "video at limit", payloadSize: maxVideoInlinePayloadSize, inputType: "video-or-audio", want: false},
+ {name: "video above limit", payloadSize: maxVideoInlinePayloadSize + 1, inputType: "video-or-audio", want: true},
+ {name: "still below limit", payloadSize: maxStillInlinePayloadSize - 1, inputType: "still", want: false},
+ {name: "still at limit", payloadSize: maxStillInlinePayloadSize, inputType: "still", want: false},
+ {name: "still above limit", payloadSize: maxStillInlinePayloadSize + 1, inputType: "still", want: true},
+ }
+
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ if got := needsUpload(test.payloadSize, test.inputType); got != test.want {
+ t.Fatalf("needsUpload(%d, %q) = %v, want %v", test.payloadSize, test.inputType, got, test.want)
+ }
+ })
+ }
+}
+
+func TestNeedsUploadWarningRounding(t *testing.T) {
+ previousWriter := log.Writer()
+ var output bytes.Buffer
+ log.SetOutput(&output)
+ t.Cleanup(func() {
+ log.SetOutput(previousWriter)
+ })
+
+ if !needsUpload(maxVideoInlinePayloadSize+1, "video-or-audio") {
+ t.Fatal("video payload above the limit should need upload")
+ }
+ if !strings.Contains(output.String(), "over 194KB") {
+ t.Fatalf("expected rounded video limit in warning, got %q", output.String())
+ }
+
+ output.Reset()
+ if !needsUpload(maxStillInlinePayloadSize+1, "still") {
+ t.Fatal("still payload above the limit should need upload")
+ }
+ if !strings.Contains(output.String(), "over 4994KB") {
+ t.Fatalf("expected rounded still limit in warning, got %q", output.String())
+ }
+}
+
+func TestIsBucketInRegion(t *testing.T) {
+ accessDenied := &smithy.GenericAPIError{Code: "AccessDenied", Message: "denied"}
+ tests := []struct {
+ name string
+ output *s3.GetBucketLocationOutput
+ err error
+ region string
+ want bool
+ wantErr bool
+ wrappedErr error
+ }{
+ {
+ name: "matching region",
+ output: &s3.GetBucketLocationOutput{LocationConstraint: types.BucketLocationConstraint("eu-west-1")},
+ region: "eu-west-1",
+ want: true,
+ },
+ {
+ name: "different region",
+ output: &s3.GetBucketLocationOutput{LocationConstraint: types.BucketLocationConstraint("eu-west-1")},
+ region: "us-west-1",
+ want: false,
+ },
+ {
+ name: "empty location is us-east-1",
+ output: &s3.GetBucketLocationOutput{},
+ region: regionUsEast1,
+ want: true,
+ },
+ {
+ name: "missing bucket",
+ err: &smithy.GenericAPIError{Code: "NoSuchBucket", Message: "missing"},
+ region: regionUsEast1,
+ want: false,
+ },
+ {
+ name: "access error",
+ err: accessDenied,
+ region: regionUsEast1,
+ wantErr: true,
+ wrappedErr: accessDenied,
+ },
+ }
+
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ got, err := isBucketInRegion(bucketLocationGetterMock{
+ output: test.output,
+ err: test.err,
+ }, "remotionlambda-test", test.region)
+ if got != test.want {
+ t.Fatalf("isBucketInRegion() = %v, want %v", got, test.want)
+ }
+ if (err != nil) != test.wantErr {
+ t.Fatalf("isBucketInRegion() error = %v, wantErr %v", err, test.wantErr)
+ }
+ if test.wrappedErr != nil && !errors.Is(err, test.wrappedErr) {
+ t.Fatalf("expected error to wrap %v, got %v", test.wrappedErr, err)
+ }
+ })
+ }
+}
+
+func TestUploadInputPropsOmitsACL(t *testing.T) {
+ uploader := &objectUploaderMock{}
+ if err := uploadInputPropsToS3(uploader, "bucket", "input-props/hash.json", `{"hello":"world"}`); err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if uploader.input == nil {
+ t.Fatal("PutObject was not called")
+ }
+ if uploader.input.ACL != "" {
+ t.Fatalf("expected no object ACL, got %q", uploader.input.ACL)
+ }
+ if got := aws.ToString(uploader.input.ContentType); got != "application/json" {
+ t.Fatalf("unexpected content type: %q", got)
+ }
+ payload, err := io.ReadAll(uploader.input.Body)
+ if err != nil {
+ t.Fatalf("could not read uploaded payload: %v", err)
+ }
+ if got := string(payload); got != `{"hello":"world"}` {
+ t.Fatalf("unexpected uploaded payload: %q", got)
+ }
+}
+
+func TestUploadInputPropsWrapsErrors(t *testing.T) {
+ uploadError := errors.New("upload failed")
+ err := uploadInputPropsToS3(&objectUploaderMock{err: uploadError}, "bucket", "key", "payload")
+ if !errors.Is(err, uploadError) {
+ t.Fatalf("expected wrapped upload error, got %v", err)
+ }
+}
+
+func TestPayloadDataAlias(t *testing.T) {
+ serialized := &SerializedInputProps{Type: "payload", Payload: "{}"}
+ var legacy *PayloadData = serialized
+ if legacy != serialized {
+ t.Fatal("PayloadData alias changed the pointer")
+ }
+}
+
+func TestRandomHashFormat(t *testing.T) {
+ const alphabet = "abcdefghijklmnopqrstuvwxyz0123456789"
+ for i := 0; i < 100; i++ {
+ hash, err := randomHash()
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if len(hash) != 10 {
+ t.Fatalf("expected 10 character hash, got %q", hash)
+ }
+ for _, char := range hash {
+ if !strings.ContainsRune(alphabet, char) {
+ t.Fatalf("unexpected character %q in hash %q", char, hash)
+ }
+ }
+ }
+}
+
+func TestNewS3ClientConfiguration(t *testing.T) {
+ t.Setenv("AWS_EC2_METADATA_DISABLED", "true")
+ client, err := newS3Client("eu-west-1", true)
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ options := client.Options()
+ if options.Region != "eu-west-1" {
+ t.Fatalf("unexpected S3 region: %q", options.Region)
+ }
+ if !options.UsePathStyle {
+ t.Fatal("expected path-style S3 addressing")
+ }
+}
+
+func TestBucketNamingAndKeys(t *testing.T) {
+ name, err := makeBucketName("us-east-1")
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if !strings.HasPrefix(name, "remotionlambda-useast1-") {
+ t.Fatalf("unexpected bucket name: %q", name)
+ }
+ if len(name) != len("remotionlambda-useast1-")+10 {
+ t.Fatalf("expected 10 char random suffix, got %q", name)
+ }
+
+ if key := inputPropsKey("abc123"); key != "input-props/abc123.json" {
+ t.Fatalf("unexpected key: %q", key)
+ }
+
+ // Same payload must hash to the same object name.
+ if hashPayload("x") != hashPayload("x") {
+ t.Fatal("hashPayload is not deterministic")
+ }
+ if hashPayload("x") == hashPayload("y") {
+ t.Fatal("hashPayload collided for different inputs")
+ }
+}
diff --git a/packages/lambda-go/models.go b/packages/lambda-go/models.go
index c5ba3da069..c284a83a9c 100644
--- a/packages/lambda-go/models.go
+++ b/packages/lambda-go/models.go
@@ -219,7 +219,16 @@ type FrameRange struct {
FrameRange [2]int `json:"frameRange"`
}
-type PayloadData struct {
- Type string `json:"type"`
- Payload string `json:"payload"`
+// SerializedInputProps is the serialized form of inputProps sent to the Lambda
+// function. When the props fit inline, Type is "payload" and Payload holds the
+// JSON string. When the props exceed the inline limit they are uploaded to S3,
+// Type is "bucket-url", and Hash/BucketName point to the uploaded object.
+type SerializedInputProps struct {
+ Type string `json:"type"`
+ Payload string `json:"payload,omitempty"`
+ Hash string `json:"hash,omitempty"`
+ BucketName string `json:"bucketName,omitempty"`
}
+
+// PayloadData is kept as an alias for backwards compatibility.
+type PayloadData = SerializedInputProps
diff --git a/packages/lambda-go/s3.go b/packages/lambda-go/s3.go
new file mode 100644
index 0000000000..6da37ae49f
--- /dev/null
+++ b/packages/lambda-go/s3.go
@@ -0,0 +1,162 @@
+package lambda_go_sdk
+
+import (
+ "context"
+ "crypto/rand"
+ "crypto/sha256"
+ "encoding/hex"
+ "errors"
+ "fmt"
+ "math/big"
+ "strings"
+
+ "github.com/aws/aws-sdk-go-v2/aws"
+ "github.com/aws/aws-sdk-go-v2/config"
+ "github.com/aws/aws-sdk-go-v2/service/s3"
+ "github.com/aws/aws-sdk-go-v2/service/s3/types"
+ "github.com/aws/smithy-go"
+)
+
+const bucketNamePrefix = "remotionlambda-"
+const regionUsEast1 = "us-east-1"
+
+type bucketLocationGetter interface {
+ GetBucketLocation(context.Context, *s3.GetBucketLocationInput, ...func(*s3.Options)) (*s3.GetBucketLocationOutput, error)
+}
+
+type objectUploader interface {
+ PutObject(context.Context, *s3.PutObjectInput, ...func(*s3.Options)) (*s3.PutObjectOutput, error)
+}
+
+// hashPayload returns the SHA256 hex digest used as the input-props object name.
+func hashPayload(payload string) string {
+ sum := sha256.Sum256([]byte(payload))
+ return hex.EncodeToString(sum[:])
+}
+
+// randomHash returns a 10 character [a-z0-9] string used as a bucket suffix.
+func randomHash() (string, error) {
+ const alphabet = "abcdefghijklmnopqrstuvwxyz0123456789"
+ b := make([]byte, 10)
+ for i := range b {
+ index, err := rand.Int(rand.Reader, big.NewInt(int64(len(alphabet))))
+ if err != nil {
+ return "", fmt.Errorf("could not generate random hash: %w", err)
+ }
+ b[i] = alphabet[index.Int64()]
+ }
+ return string(b), nil
+}
+
+// makeBucketName mirrors the JS SDK bucket naming convention.
+func makeBucketName(region string) (string, error) {
+ suffix, err := randomHash()
+ if err != nil {
+ return "", err
+ }
+ return bucketNamePrefix + strings.ReplaceAll(region, "-", "") + "-" + suffix, nil
+}
+
+func inputPropsKey(hash string) string {
+ return fmt.Sprintf("input-props/%s.json", hash)
+}
+
+// newS3Client creates an S3 client using the same shared config resolution as
+// the Lambda client in invocations.go.
+func newS3Client(region string, forcePathStyle bool) (*s3.Client, error) {
+ awsConfig, err := config.LoadDefaultConfig(
+ context.TODO(),
+ config.WithRegion(region),
+ )
+ if err != nil {
+ return nil, fmt.Errorf("could not load AWS config: %w", err)
+ }
+ return s3.NewFromConfig(awsConfig, func(options *s3.Options) {
+ options.UsePathStyle = forcePathStyle
+ }), nil
+}
+
+// isBucketInRegion reports whether the given bucket lives in region.
+func isBucketInRegion(svc bucketLocationGetter, bucket string, region string) (bool, error) {
+ out, err := svc.GetBucketLocation(context.TODO(), &s3.GetBucketLocationInput{Bucket: new(bucket)})
+ if err != nil {
+ var awsErr smithy.APIError
+ if errors.As(err, &awsErr) && awsErr.ErrorCode() == "NoSuchBucket" {
+ return false, nil
+ }
+ return false, fmt.Errorf("could not get location of S3 bucket %q: %w", bucket, err)
+ }
+ location := string(out.LocationConstraint)
+ return location == region || (location == "" && region == regionUsEast1), nil
+}
+
+// getRemotionBuckets lists the Remotion buckets that exist in region.
+func getRemotionBuckets(svc *s3.Client, region string) ([]string, error) {
+ out, err := svc.ListBuckets(context.TODO(), &s3.ListBucketsInput{})
+ if err != nil {
+ return nil, fmt.Errorf("could not list S3 buckets: %w", err)
+ }
+ buckets := []string{}
+ for _, bucket := range out.Buckets {
+ name := aws.ToString(bucket.Name)
+ if !strings.HasPrefix(name, bucketNamePrefix) {
+ continue
+ }
+ isInRegion, err := isBucketInRegion(svc, name, region)
+ if err != nil {
+ return nil, err
+ }
+ if isInRegion {
+ buckets = append(buckets, name)
+ }
+ }
+ return buckets, nil
+}
+
+// getOrCreateBucket returns the single existing Remotion bucket in the region,
+// creating one if none exist. It errors if multiple candidate buckets exist.
+func getOrCreateBucket(svc *s3.Client, region string) (string, error) {
+ buckets, err := getRemotionBuckets(svc, region)
+ if err != nil {
+ return "", err
+ }
+
+ if len(buckets) > 1 {
+ return "", fmt.Errorf(
+ "you have multiple buckets (%s) in your S3 region (%s) starting with %q. Please see https://remotion.dev/docs/lambda/multiple-buckets",
+ strings.Join(buckets, ", "), region, bucketNamePrefix,
+ )
+ }
+ if len(buckets) == 1 {
+ return buckets[0], nil
+ }
+
+ bucket, err := makeBucketName(region)
+ if err != nil {
+ return "", err
+ }
+ input := &s3.CreateBucketInput{Bucket: new(bucket)}
+ if region != regionUsEast1 {
+ input.CreateBucketConfiguration = &types.CreateBucketConfiguration{
+ LocationConstraint: types.BucketLocationConstraint(region),
+ }
+ }
+ if _, err := svc.CreateBucket(context.TODO(), input); err != nil {
+ return "", fmt.Errorf("failed to create bucket: %w", err)
+ }
+ return bucket, nil
+}
+
+// uploadInputPropsToS3 writes the serialized props to S3 as private JSON.
+func uploadInputPropsToS3(svc objectUploader, bucket string, key string, payload string) error {
+ _, err := svc.PutObject(context.TODO(), &s3.PutObjectInput{
+ Bucket: new(bucket),
+ Key: new(key),
+ Body: strings.NewReader(payload),
+ ContentType: new("application/json"),
+ })
+ if err != nil {
+ return fmt.Errorf("failed to upload inputProps to S3: %w", err)
+ }
+ return nil
+}
diff --git a/packages/lambda-go/utils.go b/packages/lambda-go/utils.go
index c480310e39..17a3ed6f11 100644
--- a/packages/lambda-go/utils.go
+++ b/packages/lambda-go/utils.go
@@ -2,38 +2,78 @@ package lambda_go_sdk
import (
"encoding/json"
- "errors"
"fmt"
+ "log"
+ "math"
)
-func serializeInputProps(inputProps interface{}, inputType string) (*PayloadData, error) {
- payload, err := json.Marshal(inputProps)
+// inline payload margin, matching the client SDK reference implementations:
+// 5KB of headroom for the rest of the Lambda payload + 1KB for webhook data.
+const inlinePayloadMargin = 5_000 + 1_024
+const maxStillInlinePayloadSize = 5_000_000 - inlinePayloadMargin
+const maxVideoInlinePayloadSize = 200_000 - inlinePayloadMargin
+// needsUpload reports whether a payload of the given size must be uploaded to S3
+// instead of being sent inline, and logs a warning when that is the case.
+func needsUpload(payloadSize int, inputType string) bool {
+ maxSize := maxVideoInlinePayloadSize
+ if inputType == "still" {
+ maxSize = maxStillInlinePayloadSize
+ }
+
+ if payloadSize <= maxSize {
+ return false
+ }
+
+ log.Printf(
+ "Warning: The props are over %dKB (%dKB) in size. Uploading them to S3 to circumvent the AWS Lambda payload size limit, which may lead to slowdown.",
+ int(math.Round(float64(maxSize)/1000)), (payloadSize+1023)/1024,
+ )
+ return true
+}
+
+func serializeInputProps(inputProps interface{}, region string, inputType string,
+ userSpecifiedBucketName string, forcePathStyle bool) (*SerializedInputProps, error) {
if inputProps == nil {
- return &PayloadData{
+ return &SerializedInputProps{
Payload: "{}",
Type: "payload",
}, nil
}
+ payload, err := json.Marshal(inputProps)
+ if err != nil {
+ return nil, fmt.Errorf("error serializing inputProps. Check it has no circular references or reduce the size if the object is big: %w", err)
+ }
+
+ if !needsUpload(len(payload), inputType) {
+ return &SerializedInputProps{
+ Payload: string(payload),
+ Type: "payload",
+ }, nil
+ }
+
+ svc, err := newS3Client(region, forcePathStyle)
if err != nil {
- return nil, errors.New("error serializing inputProps. Check it has no circular references or reduce the size if the object is big")
+ return nil, err
}
- // Set maximum inline payload size based on input type
- maxInlinePayloadSize := 200000
- if inputType == "still" {
- maxInlinePayloadSize = 5000000
+ bucketName := userSpecifiedBucketName
+ if bucketName == "" {
+ bucketName, err = getOrCreateBucket(svc, region)
+ if err != nil {
+ return nil, err
+ }
}
- // Check if payload size is within the limit
- if len(payload) > maxInlinePayloadSize {
- return nil, fmt.Errorf("warning: inputProps are over %dKB (%dKB) in size. This is not currently supported", maxInlinePayloadSize/1000, len(payload)/1024)
+ hash := hashPayload(string(payload))
+ if err := uploadInputPropsToS3(svc, bucketName, inputPropsKey(hash), string(payload)); err != nil {
+ return nil, err
}
- return &PayloadData{
- Payload: string(payload),
- Type: "payload",
+ return &SerializedInputProps{
+ Type: "bucket-url",
+ Hash: hash,
+ BucketName: bucketName,
}, nil
-
}
diff --git a/packages/lambda-go/version.go b/packages/lambda-go/version.go
index daf5eac78e..05461ac296 100644
--- a/packages/lambda-go/version.go
+++ b/packages/lambda-go/version.go
@@ -1,3 +1,3 @@
-package lambda_go_sdk;
+package lambda_go_sdk
-const VERSION = "4.0.489"
\ No newline at end of file
+const VERSION = "4.0.489"