@@ -14,6 +14,7 @@ import (
1414 "strings"
1515
1616 "github.com/aws/aws-sdk-go-v2/config"
17+ s3manager "github.com/aws/aws-sdk-go-v2/feature/s3/manager"
1718 "github.com/aws/aws-sdk-go-v2/service/s3"
1819)
1920
@@ -149,6 +150,40 @@ func parseS3URL(inputURL string) (bucket, key string, err error) {
149150 return parts [0 ], parts [1 ], nil
150151}
151152
153+ // getS3ClientForBucket creates an S3 client configured for the bucket's region
154+ func (d * S3Downloader ) getS3ClientForBucket (ctx context.Context , bucket string ) (* s3.Client , error ) {
155+ // First, load the default config
156+ cfg , err := config .LoadDefaultConfig (ctx )
157+ if err != nil {
158+ return nil , fmt .Errorf ("failed to load AWS config: %w" , err )
159+ }
160+
161+ // Create a client to detect the bucket region
162+ client := s3 .NewFromConfig (cfg )
163+
164+ // Get the actual bucket region
165+ region , err := s3manager .GetBucketRegion (ctx , client , bucket )
166+ if err != nil {
167+ // If we can't detect the region, return the default client
168+ if d .verbose {
169+ fmt .Printf ("Warning: could not detect bucket region, using default: %v\n " , err )
170+ }
171+ return client , nil
172+ }
173+
174+ if d .verbose {
175+ fmt .Printf ("Detected bucket region: %s\n " , region )
176+ }
177+
178+ // Reload config with the correct region
179+ cfg , err = config .LoadDefaultConfig (ctx , config .WithRegion (region ))
180+ if err != nil {
181+ return nil , fmt .Errorf ("failed to load AWS config with region %s: %w" , region , err )
182+ }
183+
184+ return s3 .NewFromConfig (cfg ), nil
185+ }
186+
152187// isCacheValid checks if the cached file is still valid
153188func (d * S3Downloader ) isCacheValid (ctx context.Context , inputURL , cachedFilePath , metadataPath string ) bool {
154189 // Check if cached file exists
@@ -193,12 +228,11 @@ func (d *S3Downloader) getS3ETag(ctx context.Context, inputURL string) (string,
193228 return "" , err
194229 }
195230
196- cfg , err := config . LoadDefaultConfig (ctx )
231+ client , err := d . getS3ClientForBucket (ctx , bucket )
197232 if err != nil {
198- return "" , fmt . Errorf ( "failed to load AWS config: %w" , err )
233+ return "" , err
199234 }
200235
201- client := s3 .NewFromConfig (cfg )
202236 result , err := client .HeadObject (ctx , & s3.HeadObjectInput {
203237 Bucket : & bucket ,
204238 Key : & key ,
@@ -240,12 +274,11 @@ func (d *S3Downloader) downloadFromS3(ctx context.Context, inputURL, destPath st
240274 return "" , err
241275 }
242276
243- cfg , err := config . LoadDefaultConfig (ctx )
277+ client , err := d . getS3ClientForBucket (ctx , bucket )
244278 if err != nil {
245- return "" , fmt . Errorf ( "failed to load AWS config: %w" , err )
279+ return "" , err
246280 }
247281
248- client := s3 .NewFromConfig (cfg )
249282 result , err := client .GetObject (ctx , & s3.GetObjectInput {
250283 Bucket : & bucket ,
251284 Key : & key ,
0 commit comments