forked from thomaspoignant/go-feature-flag
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathretriever.go
80 lines (63 loc) · 1.88 KB
/
retriever.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
package gcstorageretriever
import (
"bytes"
"context"
"crypto/md5" //nolint: gosec
"fmt"
"io"
"cloud.google.com/go/storage"
"google.golang.org/api/option"
)
// Retriever is a configuration struct for a Google Cloud Storage retriever.
type Retriever struct {
// Bucket is the name of your Google Cloud Storage Bucket.
Bucket string
// Object is the name of your file in your bucket.
Object string
// Options are Google Cloud Api options needed for downloading
// your feature flag configuration file.
Options []option.ClientOption
// Internal field used to cache the file data.
cache []byte
// Internal MD5 hash of cache
md5 []byte
// Internal field used to fetch metadata of the file.
obj *storage.ObjectHandle
}
func (retriever *Retriever) Retrieve(ctx context.Context) (content []byte, err error) {
if retriever.obj == nil {
// Create GC Storage Client.
client, err := storage.NewClient(ctx, retriever.Options...)
if err != nil {
return nil, err
}
// Construct Object.
retriever.obj = client.Bucket(retriever.Bucket).Object(retriever.Object)
}
// Fetch the metadata of the remote file.
attrs, err := retriever.obj.Attrs(ctx)
if err != nil {
return nil, err
}
// When local and remote hashes match, return cached data.
if bytes.Equal(attrs.MD5, retriever.md5) {
return retriever.cache, nil
}
// When cache is outdated download file and create Reader to read from it.
reader, err := retriever.obj.NewReader(ctx)
if err != nil {
return nil, err
}
defer reader.Close()
// Read all contents from the Reader.
content, err = io.ReadAll(reader)
if err != nil {
return nil,
fmt.Errorf("unable to read from GCP Object %s in Bucket %s, error: %s", retriever.Bucket, retriever.Object, err)
}
// Update Cache along with its hash.
retriever.cache = content
md5Hash := md5.Sum(content) //nolint: gosec
retriever.md5 = md5Hash[:]
return content, nil
}