forked from GoogleCloudPlatform/microservices-demo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
catalog_loader.go
151 lines (126 loc) · 4.22 KB
/
catalog_loader.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
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
// Copyright 2024 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"bytes"
"context"
"fmt"
"net"
"os"
"strings"
"cloud.google.com/go/alloydbconn"
secretmanager "cloud.google.com/go/secretmanager/apiv1"
"cloud.google.com/go/secretmanager/apiv1/secretmanagerpb"
pb "github.com/GoogleCloudPlatform/microservices-demo/src/productcatalogservice/genproto"
"github.com/golang/protobuf/jsonpb"
"github.com/jackc/pgx/v5/pgxpool"
)
func loadCatalog(catalog *pb.ListProductsResponse) error {
catalogMutex.Lock()
defer catalogMutex.Unlock()
if os.Getenv("ALLOYDB_CLUSTER_NAME") != "" {
log.Info("Loading catalog from AlloyDB...")
return loadCatalogFromAlloyDB(catalog)
}
log.Info("Loading catalog from local products.json file...")
return loadCatalogFromLocalFile(catalog)
}
func loadCatalogFromLocalFile(catalog *pb.ListProductsResponse) error {
catalogJSON, err := os.ReadFile("products.json")
if err != nil {
log.Fatalf("failed to open product catalog json file: %v", err)
return err
}
if err := jsonpb.Unmarshal(bytes.NewReader(catalogJSON), catalog); err != nil {
log.Warnf("failed to parse the catalog JSON: %v", err)
return err
}
log.Info("successfully parsed product catalog json")
return nil
}
func getSecretPayload(project, secret, version string) (string, error) {
ctx := context.Background()
client, err := secretmanager.NewClient(ctx)
if err != nil {
return "", err
}
defer client.Close()
req := &secretmanagerpb.AccessSecretVersionRequest{
Name: fmt.Sprintf("projects/%s/secrets/%s/versions/%s", project, secret, version),
}
// Call the API.
result, err := client.AccessSecretVersion(ctx, req)
if err != nil {
return "", err
}
return string(result.Payload.Data), nil
}
func loadCatalogFromAlloyDB(catalog *pb.ListProductsResponse) error {
projectID := os.Getenv("PROJECT_ID")
region := os.Getenv("REGION")
pgClusterName := os.Getenv("ALLOYDB_CLUSTER_NAME")
pgInstanceName := os.Getenv("ALLOYDB_INSTANCE_NAME")
pgDatabaseName := os.Getenv("ALLOYDB_DATABASE_NAME")
pgTableName := os.Getenv("ALLOYDB_TABLE_NAME")
pgSecretName := os.Getenv("ALLOYDB_SECRET_NAME")
pgPassword, err := getSecretPayload(projectID, pgSecretName, "latest")
if err != nil {
return err
}
dialer, err := alloydbconn.NewDialer(context.Background())
if err != nil {
return err
}
cleanup := func() error { return dialer.Close() }
defer cleanup()
dsn := fmt.Sprintf(
"user=%s password=%s dbname=%s sslmode=disable",
"postgres", pgPassword, pgDatabaseName,
)
config, err := pgxpool.ParseConfig(dsn)
if err != nil {
return err
}
pgInstanceURI := fmt.Sprintf("projects/%s/locations/%s/clusters/%s/instances/%s", projectID, region, pgClusterName, pgInstanceName)
config.ConnConfig.DialFunc = func(ctx context.Context, _ string, _ string) (net.Conn, error) {
return dialer.Dial(ctx, pgInstanceURI)
}
pool, err := pgxpool.NewWithConfig(context.Background(), config)
if err != nil {
return err
}
defer pool.Close()
query := "SELECT id, name, description, picture, price_usd_currency_code, price_usd_units, price_usd_nanos, categories FROM " + pgTableName
rows, err := pool.Query(context.Background(), query)
if err != nil {
return err
}
defer rows.Close()
catalog.Products = catalog.Products[:0]
for rows.Next() {
product := &pb.Product{}
product.PriceUsd = &pb.Money{}
var categories string
err = rows.Scan(&product.Id, &product.Name, &product.Description,
&product.Picture, &product.PriceUsd.CurrencyCode, &product.PriceUsd.Units,
&product.PriceUsd.Nanos, &categories)
if err != nil {
return err
}
categories = strings.ToLower(categories)
product.Categories = strings.Split(categories, ",")
catalog.Products = append(catalog.Products, product)
}
return nil
}