-
Notifications
You must be signed in to change notification settings - Fork 9
/
wire.go
79 lines (65 loc) · 2.18 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
// 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 rds
import (
"context"
"encoding/json"
"flag"
"fmt"
awsrds "github.com/aws/aws-sdk-go-v2/service/rds"
"namespacelabs.dev/foundation/schema"
"namespacelabs.dev/foundation/universe/db/postgres"
"namespacelabs.dev/foundation/universe/db/postgres/rds/internal"
)
const InclusterEndpointFlag = "rds_postgresql_endpoint"
var (
inclusterEndpoint = flag.String(InclusterEndpointFlag, "", "Endpoint configuration.")
)
func getEndpoint(ctx context.Context, db *Database, deps ExtensionDeps) (*schema.Endpoint, error) {
if *inclusterEndpoint != "" {
var endpoint schema.Endpoint
if err := json.Unmarshal([]byte(*inclusterEndpoint), &endpoint); err != nil {
return nil, fmt.Errorf("failed to parse postgresql endpoint configuration: %w", err)
}
return &endpoint, nil
}
awsCfg, err := deps.ClientFactory.New(ctx)
if err != nil {
return nil, err
}
rdscli := awsrds.NewFromConfig(awsCfg)
id := internal.ClusterIdentifier(deps.ServerInfo.EnvName, db.Name)
desc, err := rdscli.DescribeDBClusters(ctx, &awsrds.DescribeDBClustersInput{
DBClusterIdentifier: &id,
})
if err != nil {
return nil, err
}
if len(desc.DBClusters) != 1 {
return nil, fmt.Errorf("expected one cluster with identifier %s, got %d", id, len(desc.DBClusters))
}
return &schema.Endpoint{
AllocatedName: *desc.DBClusters[0].Endpoint,
Port: &schema.Endpoint_Port{
ContainerPort: *desc.DBClusters[0].Port,
},
}, nil
}
func ProvideDatabase(ctx context.Context, db *Database, deps ExtensionDeps) (*postgres.DB, error) {
endpoint, err := getEndpoint(ctx, db, deps)
if err != nil {
return nil, err
}
return deps.Wire.ProvideDatabase(ctx, &postgres.Database{
Name: db.Name,
HostedAt: &postgres.Database_Endpoint{
Address: endpoint.AllocatedName,
Port: uint32(endpoint.Port.ContainerPort),
},
Credentials: &postgres.Database_Credentials{
User: &postgres.Database_Credentials_Secret{Value: "postgres"},
Password: &postgres.Database_Credentials_Secret{Value: deps.Creds.Password},
},
})
}