Repository navigation
Expand file tree
/
Copy paths3.go
More file actions
220 lines (196 loc) · 6.86 KB
/
Copy paths3.go
File metadata and controls
220 lines (196 loc) · 6.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
package lambda_go_sdk
import (
"context"
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"math/big"
"strings"
"time"
"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)
}
type cancellationObjectClient interface {
GetObject(context.Context, *s3.GetObjectInput, ...func(*s3.Options)) (*s3.GetObjectOutput, error)
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)
}
func overallProgressKey(renderId string) string {
return fmt.Sprintf("renders/%s/progress.json", renderId)
}
func cancellationKey(renderId string) string {
return fmt.Sprintf("renders/%s/cancel.json", renderId)
}
func cancelRenderOnLambda(client cancellationObjectClient, input CancelRenderOnLambdaInput) error {
progressObject, err := client.GetObject(context.TODO(), &s3.GetObjectInput{
Bucket: new(input.BucketName),
Key: new(overallProgressKey(input.RenderId)),
})
if err != nil {
return fmt.Errorf("could not read progress for render %q: %w", input.RenderId, err)
}
defer progressObject.Body.Close()
progressBody, err := io.ReadAll(progressObject.Body)
if err != nil {
return fmt.Errorf("could not read progress for render %q: %w", input.RenderId, err)
}
var progress struct {
CancellationEnabled bool `json:"cancellationEnabled"`
}
if err := json.Unmarshal(progressBody, &progress); err != nil {
return fmt.Errorf("could not parse progress for render %q: %w", input.RenderId, err)
}
if !progress.CancellationEnabled {
return fmt.Errorf("cannot cancel render %s: the render was not started with enableCancellation: true", input.RenderId)
}
cancellationBody, err := json.Marshal(map[string]int64{"cancelledAt": time.Now().UnixMilli()})
if err != nil {
return fmt.Errorf("could not serialize cancellation signal: %w", err)
}
_, err = client.PutObject(context.TODO(), &s3.PutObjectInput{
Bucket: new(input.BucketName),
Key: new(cancellationKey(input.RenderId)),
Body: strings.NewReader(string(cancellationBody)),
ContentType: new("application/json"),
})
if err != nil {
return fmt.Errorf("could not cancel render %q: %w", input.RenderId, err)
}
return nil
}
// 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
}