-
Notifications
You must be signed in to change notification settings - Fork 9
/
wire.go
87 lines (74 loc) · 2.64 KB
/
wire.go
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
// Copyright 2022 Namespace Labs Inc; All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
package s3
import (
"context"
"flag"
"fmt"
"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"
"namespacelabs.dev/foundation/std/go/core"
fns3 "namespacelabs.dev/foundation/universe/aws/s3"
)
var (
localstackEndpoint = flag.String("localstack_endpoint", "", "Localstack endpoint configuration.")
)
type LocalstackConfig struct {
Region, LocalstackEndpoint string
}
func createLocalStackConfig(ctx context.Context, c LocalstackConfig) (aws.Config, error) {
customResolver := aws.EndpointResolverWithOptionsFunc(func(service, region string, options ...interface{}) (aws.Endpoint, error) {
return aws.Endpoint{
PartitionID: "aws",
URL: c.LocalstackEndpoint,
SigningRegion: region,
}, nil
})
var opts []func(*config.LoadOptions) error
// Specify a custom resolver to be able to point to localstack's endpoint.
opts = append(opts, config.WithEndpointResolverWithOptions(customResolver))
if c.Region != "" {
opts = append(opts, config.WithRegion(c.Region))
}
cfg, err := config.LoadDefaultConfig(ctx, opts...)
if err != nil {
return aws.Config{}, fmt.Errorf("failed to load AWS config with error: %w, for endpoint %s", err, *localstackEndpoint)
}
return cfg, nil
}
func CreateLocalstackS3Client(ctx context.Context, config LocalstackConfig) (*s3.Client, error) {
cfg, err := createLocalStackConfig(ctx, config)
if err != nil {
return nil, err
}
s3client := s3.NewFromConfig(cfg, func(o *s3.Options) {
// Make sure the bucket is encoded into the URL after domain is resolved, not as a subdomain.
// TODO UsePathStyle is deprecated - use it only if localstack is used before we can dynamically add DNS entries.
o.UsePathStyle = true
})
return s3client, nil
}
func ProvideBucket(ctx context.Context, config *BucketConfig, deps ExtensionDeps) (*fns3.Bucket, error) {
s3client, err := CreateLocalstackS3Client(ctx,
LocalstackConfig{
Region: config.Region,
LocalstackEndpoint: *localstackEndpoint,
})
if err != nil {
return nil, err
}
// Asynchronously wait until a database connection is ready.
deps.ReadinessCheck.Register(
fmt.Sprintf("localstack readiness: %s", core.InstantiationPathFromContext(ctx)),
core.CheckAtStartupFunc(
func(ctx context.Context) error {
_, err := s3client.ListBuckets(ctx, &s3.ListBucketsInput{})
return err
}))
return &fns3.Bucket{
BucketName: config.BucketName,
S3Client: s3client,
}, nil
}