-
-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathblob.go
More file actions
230 lines (196 loc) · 5.72 KB
/
Copy pathblob.go
File metadata and controls
230 lines (196 loc) · 5.72 KB
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
package storage
import (
"context"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"runtime"
"strings"
"time"
"gocloud.dev/blob"
_ "gocloud.dev/blob/azureblob"
_ "gocloud.dev/blob/fileblob"
_ "gocloud.dev/blob/gcsblob"
_ "gocloud.dev/blob/s3blob"
"gocloud.dev/gcerrors"
)
const osWindows = "windows"
// Blob implements Storage using gocloud.dev/blob.
// Supports local filesystem (file://) and S3 (s3://) URLs.
type Blob struct {
bucket *blob.Bucket
url string
}
// OpenBucket opens a blob bucket from a URL.
//
// Supported URL schemes:
// - file:///path/to/dir - Local filesystem storage
// - s3://bucket-name - Amazon S3 (uses AWS_* environment variables)
// - s3://bucket-name?region=us-east-1&endpoint=http://localhost:9000 - S3-compatible (MinIO, etc.)
// - gs://bucket-name - Google Cloud Storage (uses Application Default Credentials;
// supports Workload Identity on GKE/GCE without any extra configuration)
// - azblob://container-name - Azure Blob Storage
//
// For local filesystem, the directory is created if it doesn't exist.
func OpenBucket(ctx context.Context, urlStr string) (*Blob, error) {
// Handle file:// URLs specially to create the directory
if strings.HasPrefix(urlStr, "file://") {
path := strings.TrimPrefix(urlStr, "file://")
// Handle file:/// (three slashes) for absolute paths
if strings.HasPrefix(path, "/") && runtime.GOOS != osWindows {
// Unix: file:///path -> /path
// path is already correct
} else if strings.HasPrefix(path, "/") && runtime.GOOS == osWindows {
// Windows: file:///C:/path -> C:/path
path = strings.TrimPrefix(path, "/")
}
// Convert forward slashes to native path separators for filesystem operations
nativePath := filepath.FromSlash(path)
// Ensure directory exists
if err := os.MkdirAll(nativePath, dirPermissions); err != nil {
return nil, fmt.Errorf("creating directory: %w", err)
}
// fileblob requires an absolute path with forward slashes
absPath, err := filepath.Abs(nativePath)
if err != nil {
return nil, fmt.Errorf("resolving path: %w", err)
}
// Convert back to URL format with forward slashes
urlPath := filepath.ToSlash(absPath)
if runtime.GOOS == osWindows {
// Windows needs file:///C:/path format
urlStr = "file:///" + urlPath
} else {
urlStr = "file://" + urlPath
}
// Create temp files next to the final path instead of in os.TempDir.
// This avoids "invalid cross-device link" errors from os.Rename when
// the bucket directory and os.TempDir are on different filesystems
// (e.g. Docker volume mounts).
urlStr += "?no_tmp_dir=true"
}
bucket, err := blob.OpenBucket(ctx, urlStr)
if err != nil {
return nil, fmt.Errorf("opening bucket: %w", err)
}
return &Blob{bucket: bucket, url: urlStr}, nil
}
func (b *Blob) Store(ctx context.Context, path string, r io.Reader) (int64, string, error) {
// Compute hash while writing
h := sha256.New()
tee := io.TeeReader(r, h)
opts := &blob.WriterOptions{}
w, err := b.bucket.NewWriter(ctx, path, opts)
if err != nil {
return 0, "", fmt.Errorf("creating writer: %w", err)
}
size, err := io.Copy(w, tee)
if err != nil {
_ = w.Close()
return 0, "", fmt.Errorf("writing content: %w", err)
}
if err := w.Close(); err != nil {
return 0, "", fmt.Errorf("closing writer: %w", err)
}
hash := hex.EncodeToString(h.Sum(nil))
return size, hash, nil
}
func (b *Blob) Open(ctx context.Context, path string) (io.ReadCloser, error) {
r, err := b.bucket.NewReader(ctx, path, nil)
if err != nil {
if isNotExist(err) {
return nil, ErrNotFound
}
return nil, fmt.Errorf("opening reader: %w", err)
}
return r, nil
}
func (b *Blob) Exists(ctx context.Context, path string) (bool, error) {
exists, err := b.bucket.Exists(ctx, path)
if err != nil {
return false, fmt.Errorf("checking existence: %w", err)
}
return exists, nil
}
func (b *Blob) Delete(ctx context.Context, path string) error {
err := b.bucket.Delete(ctx, path)
if err != nil && !isNotExist(err) {
return fmt.Errorf("deleting object: %w", err)
}
return nil
}
func (b *Blob) SignedURL(ctx context.Context, path string, expiry time.Duration) (string, error) {
url, err := b.bucket.SignedURL(ctx, path, &blob.SignedURLOptions{
Method: http.MethodGet,
Expiry: expiry,
})
if err != nil {
if gcerrors.Code(err) == gcerrors.Unimplemented {
return "", ErrSignedURLUnsupported
}
return "", fmt.Errorf("signing URL: %w", err)
}
return url, nil
}
func (b *Blob) Size(ctx context.Context, path string) (int64, error) {
attrs, err := b.bucket.Attributes(ctx, path)
if err != nil {
if isNotExist(err) {
return 0, ErrNotFound
}
return 0, fmt.Errorf("getting attributes: %w", err)
}
return attrs.Size, nil
}
func (b *Blob) UsedSpace(ctx context.Context) (int64, error) {
var total int64
iter := b.bucket.List(nil)
for {
obj, err := iter.Next(ctx)
if err == io.EOF {
break
}
if err != nil {
return 0, fmt.Errorf("listing objects: %w", err)
}
total += obj.Size
}
return total, nil
}
// ListPrefix returns object metadata for keys under a prefix.
func (b *Blob) ListPrefix(ctx context.Context, prefix string) ([]ObjectInfo, error) {
iter := b.bucket.List(&blob.ListOptions{Prefix: prefix})
objects := make([]ObjectInfo, 0)
for {
obj, err := iter.Next(ctx)
if err == io.EOF {
break
}
if err != nil {
return nil, fmt.Errorf("listing objects: %w", err)
}
if obj.IsDir {
continue
}
info := ObjectInfo{
Path: obj.Key,
Size: obj.Size,
ModTime: obj.ModTime,
}
objects = append(objects, info)
}
return objects, nil
}
func (b *Blob) Close() error {
return b.bucket.Close()
}
func (b *Blob) URL() string {
return b.url
}
func isNotExist(err error) bool {
return gcerrors.Code(err) == gcerrors.NotFound
}