Skip to content

Commit

Permalink
Move BucketRegion to the s3util package.
Browse files Browse the repository at this point in the history
  • Loading branch information
creachadair committed Aug 23, 2024
1 parent 1ae2375 commit 1432264
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 19 deletions.
21 changes: 2 additions & 19 deletions cmd/go-cache-plugin/go-cache-plugin.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,13 @@
package main

import (
"cmp"
"context"
"log"
"os"

"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/creachadair/command"
"github.com/creachadair/flax"
"github.com/tailscale/go-cache-plugin/internal/s3util"
)

func main() {
Expand Down Expand Up @@ -108,22 +106,7 @@ func getBucketRegion(ctx context.Context, bucket string) (string, error) {
if flags.S3Region != "" {
return flags.S3Region, nil
}

// The default AWS region, which we use for resolving the bucket location
// and also serves as the fallback if the API reports an empty region name.
// The API returns "" for buckets in this region for historical reasons.
const defaultRegion = "us-east-1"

cfg, err := config.LoadDefaultConfig(ctx, config.WithRegion(defaultRegion))
if err != nil {
return "", err
}
cli := s3.NewFromConfig(cfg)
loc, err := cli.GetBucketLocation(ctx, &s3.GetBucketLocationInput{Bucket: &bucket})
if err != nil {
return "", err
}
return cmp.Or(string(loc.LocationConstraint), defaultRegion), nil
return s3util.BucketRegion(ctx, bucket)
}

// vprintf acts as log.Printf if the --verbose flag is set; otherwise it
Expand Down
24 changes: 24 additions & 0 deletions internal/s3util/s3util.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,13 @@
package s3util

import (
"cmp"
"context"
"errors"
"os"

"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"
)

Expand All @@ -21,3 +25,23 @@ func IsNotExist(err error) bool {
}
return errors.Is(err, os.ErrNotExist)
}

// BucketRegion reports the specified region for the given bucket using the
// GetBucketLocation API.
func BucketRegion(ctx context.Context, bucket string) (string, error) {
// The default AWS region, which we use for resolving the bucket location
// and also serves as the fallback if the API reports an empty region name.
// The API returns "" for buckets in this region for historical reasons.
const defaultRegion = "us-east-1"

cfg, err := config.LoadDefaultConfig(ctx, config.WithRegion(defaultRegion))
if err != nil {
return "", err
}
cli := s3.NewFromConfig(cfg)
loc, err := cli.GetBucketLocation(ctx, &s3.GetBucketLocationInput{Bucket: &bucket})
if err != nil {
return "", err
}
return cmp.Or(string(loc.LocationConstraint), defaultRegion), nil
}

0 comments on commit 1432264

Please sign in to comment.