-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathgsstore.go
312 lines (257 loc) · 8.25 KB
/
gsstore.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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
package dstore
import (
"context"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
"strings"
"cloud.google.com/go/storage"
"github.com/googleapis/gax-go/v2"
"go.uber.org/zap"
"google.golang.org/api/googleapi"
"google.golang.org/api/iterator"
)
//
// Google Storage Store
var warnSilenced = os.Getenv("DSTORE_WARN_SILENCED") == "true"
type GSStore struct {
baseURL *url.URL
client *storage.Client
userProject string
*commonStore
}
func NewGSStore(baseURL *url.URL, extension, compressionType string, overwrite bool, opts ...Option) (*GSStore, error) {
ctx := context.Background()
return newGSStoreContext(ctx, baseURL, extension, compressionType, overwrite, opts...)
}
func (s *GSStore) Clone(ctx context.Context, opts ...Option) (Store, error) {
return newGSStoreContext(ctx, s.baseURL, s.extension, s.compressionType, s.overwrite, opts...)
}
func newGSStoreContext(ctx context.Context, baseURL *url.URL, extension, compressionType string, overwrite bool, opts ...Option) (*GSStore, error) {
client, err := storage.NewClient(ctx)
if err != nil {
return nil, err
}
userProject := baseURL.Query().Get("project")
client.SetRetry(storage.WithBackoff(gax.Backoff{}))
conf := config{}
for _, opt := range opts {
opt.apply(&conf)
}
common := &commonStore{
compressionType: compressionType,
extension: extension,
overwrite: overwrite,
uncompressedReadCallback: conf.uncompressedReadCallback,
compressedReadCallback: conf.compressedReadCallback,
uncompressedWriteCallback: conf.uncompressedWriteCallback,
compressedWriteCallback: conf.compressedWriteCallback,
}
return &GSStore{
baseURL: baseURL,
client: client,
commonStore: common,
userProject: userProject,
}, nil
}
func (s *GSStore) SubStore(subFolder string) (Store, error) {
url, err := url.Parse(s.baseURL.String())
if err != nil {
return nil, fmt.Errorf("gs store parsing base url: %w", err)
}
url.Path = path.Join(url.Path, subFolder)
return &GSStore{
baseURL: url,
client: s.client,
commonStore: s.commonStore,
userProject: s.userProject,
}, nil
}
func (s *GSStore) bucket() *storage.BucketHandle {
if s.userProject != "" {
return s.client.Bucket(s.baseURL.Host).UserProject(s.userProject)
}
return s.client.Bucket(s.baseURL.Host)
}
func (s *GSStore) BaseURL() *url.URL {
return s.baseURL
}
func (s *GSStore) ObjectPath(name string) string {
return path.Join(strings.TrimLeft(s.baseURL.Path, "/"), s.pathWithExt(name))
}
func (s *GSStore) ObjectURL(name string) string {
return fmt.Sprintf("%s/%s", strings.TrimRight(s.baseURL.String(), "/"), strings.TrimLeft(s.pathWithExt(name), "/"))
}
func (s *GSStore) toBaseName(filename string) string {
return strings.TrimPrefix(strings.TrimSuffix(filename, s.pathWithExt("")), strings.TrimLeft(s.baseURL.Path, "/")+"/")
}
func (s *GSStore) CopyObject(ctx context.Context, src, dest string) error {
srcPath := s.ObjectPath(src)
srcObj := s.bucket().Object(srcPath)
destPath := s.ObjectPath(dest)
_, err := s.bucket().Object(destPath).CopierFrom(srcObj).Run(ctx)
return err
}
func (s *GSStore) WriteObject(ctx context.Context, base string, f io.Reader) (err error) {
ctx = withFileName(ctx, base)
ctx = withStoreType(ctx, "gstore")
ctx = withLogger(ctx, zlog, tracer)
path := s.ObjectPath(base)
object := s.bucket().Object(path)
if !s.overwrite {
object = object.If(storage.Conditions{DoesNotExist: true})
}
w := object.NewWriter(ctx)
w.ContentType = "application/octet-stream"
w.CacheControl = "public, max-age=86400"
if err := s.compressedCopy(ctx, w, f); err != nil {
return err
}
if err := w.Close(); err != nil {
if s.overwrite {
return err
}
silenced := silencePreconditionError(err)
if warnSilenced {
zlog.Info("silenced precondition error", zap.Error(err), zap.NamedError("silenced", silenced), zap.String("path", path))
}
return silenced
}
return nil
}
func silencePreconditionError(err error) error {
if e, ok := err.(*googleapi.Error); ok {
if e.Code == http.StatusPreconditionFailed {
return nil
}
}
return err
}
func (s *GSStore) OpenObject(ctx context.Context, name string) (out io.ReadCloser, err error) {
ctx = withStoreType(ctx, "gstore")
ctx = withLogger(ctx, zlog, tracer)
path := s.ObjectPath(name)
ctx = withFileName(ctx, path)
if tracer.Enabled() {
zlog.Debug("opening dstore file", zap.String("path", path))
}
reader, err := s.bucket().Object(path).NewReader(ctx)
if err != nil {
if err == storage.ErrObjectNotExist {
return nil, ErrNotFound
}
return nil, err
}
out, err = s.uncompressedReader(ctx, reader)
if tracer.Enabled() {
out = wrapReadCloser(out, func() {
zlog.Debug("closing dstore file", zap.String("path", path))
})
}
return
}
func (s *GSStore) DeleteObject(ctx context.Context, base string) error {
path := s.ObjectPath(base)
err := s.bucket().Object(path).Delete(ctx)
if errors.Is(err, storage.ErrObjectNotExist) {
return ErrNotFound
}
return err
}
func (s *GSStore) FileExists(ctx context.Context, base string) (bool, error) {
path := s.ObjectPath(base)
_, err := s.bucket().Object(path).Attrs(ctx)
if err != nil {
if err == storage.ErrObjectNotExist {
return false, nil
}
return false, err
}
return true, nil
}
func (s *GSStore) ObjectAttributes(ctx context.Context, base string) (*ObjectAttributes, error) {
path := s.ObjectPath(base)
attrs, err := s.bucket().Object(path).Attrs(ctx)
if err != nil {
if err == storage.ErrObjectNotExist {
return nil, ErrNotFound
}
return nil, err
}
return &ObjectAttributes{
LastModified: attrs.Updated,
Size: attrs.Size,
}, nil
}
func (s *GSStore) PushLocalFile(ctx context.Context, localFile, toBaseName string) error {
remove, err := pushLocalFile(ctx, s, localFile, toBaseName)
if err != nil {
return err
}
return remove()
}
func (s *GSStore) ListFiles(ctx context.Context, prefix string, max int) ([]string, error) {
return listFiles(ctx, s, prefix, max)
}
func (s *GSStore) Walk(ctx context.Context, prefix string, f func(filename string) (err error)) error {
return s.WalkFromTo(ctx, prefix, "", "", f)
}
func (s *GSStore) WalkFromTo(ctx context.Context, prefix, startingPoint, exclusiveEndPoint string, f func(filename string) (err error)) error {
q := &storage.Query{}
q.SetAttrSelection([]string{"Name"}) // only fetch the name, 25% faster
q.Prefix = strings.TrimLeft(s.baseURL.Path, "/") + "/"
if prefix != "" {
q.Prefix = filepath.Join(q.Prefix, prefix)
// join cleans the string and will remove the trailing / in the prefix if present.
// adding it back to prevent false positive matches
if prefix[len(prefix)-1:] == "/" {
q.Prefix = q.Prefix + "/"
}
}
if startingPoint != "" {
if !strings.HasPrefix(startingPoint, prefix) {
return fmt.Errorf("starting point %q must start with prefix %q", startingPoint, prefix)
}
// "startingPoint" is known to start with "prefix" (checked when entering function), but our the prefix received do
// not contain the "baseURL" which is required because it contains the "path" of the store. So we remove the
// "original prefix" from the "startingPoint" and append it to the real "final" prefix instead.
relativeStartingPoint := strings.TrimPrefix(startingPoint, prefix)
q.StartOffset = filepath.Join(q.Prefix, relativeStartingPoint)
}
if exclusiveEndPoint != "" {
if !strings.HasPrefix(exclusiveEndPoint, prefix) {
return fmt.Errorf("exclusive end point %q must start with prefix %q", exclusiveEndPoint, prefix)
}
// same adjustment as above
relativeEndPoint := strings.TrimPrefix(exclusiveEndPoint, prefix)
q.EndOffset = filepath.Join(q.Prefix, relativeEndPoint)
}
if tracer.Enabled() {
zlog.Info("walking files from", zap.String("original_prefix", prefix), zap.String("prefix", q.Prefix), zap.String("start_offset", q.StartOffset))
}
it := s.bucket().Objects(ctx, q)
for {
attrs, err := it.Next()
if err == iterator.Done {
break
}
if err != nil {
return err
}
if err := f(s.toBaseName(attrs.Name)); err != nil {
if errors.Is(err, StopIteration) {
return nil
}
return err
}
}
return nil
}
func (s *GSStore) WalkFrom(ctx context.Context, prefix, startingPoint string, f func(filename string) (err error)) error {
return s.WalkFromTo(ctx, prefix, startingPoint, "", f)
}