-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathadapter.go
240 lines (217 loc) · 5.98 KB
/
adapter.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
package cloudstoragefs
import (
"bytes"
"cloud.google.com/go/storage"
"context"
"fmt"
"github.com/pkg6/gfs"
"google.golang.org/api/option"
"io"
"net/url"
"os"
"sync"
)
// Adapter
// api key https://console.cloud.google.com/apis/dashboard
//
// CredentialsFile
// 1. IAM和管理->服务账号->创建账号->密钥->添加密钥->密钥类型json->创建
//
// 2. Cloud Storage->创建->指定存储桶的名称【test】->点击桶列表中【test】
//
// https://cloud.google.com/storage/docs/access-control/iam-roles?hl=zh-cn
// 3. 写入权限:权限->授予访问权限->添加主账号(allUsers)->分配角色(Storage Admin)
//
// https://cloud.google.com/storage/docs/access-control/making-data-public?hl=zh-cn
// 4. 访问权限:权限->授予访问权限->添加主账号(allUsers)->分配角色(Storage Object Viewer)
type Adapter struct {
bucket string
Config *Config
ctx context.Context
lock *sync.Mutex
closeTimeoutCancel []func()
storageClient *storage.Client
}
func New(config gfs.IAdapterConfig) gfs.IAdapter {
return config.NewAdapter()
}
func NewGCS(config *Config) *Adapter {
var credentials bool
if config.CredentialsFile != "" {
config.Option = append(config.Option, option.WithCredentialsFile(config.CredentialsFile))
credentials = true
}
if !credentials {
config.Option = append(config.Option, option.WithCredentialsJSON([]byte(config.CredentialsJSON)))
credentials = true
}
a := &Adapter{Config: config}
if a.Config.WithTimeout == 0 {
a.Config.WithTimeout = DefaultWithTimeout
}
a.ctx = context.Background()
a.lock = &sync.Mutex{}
return a
}
func (a *Adapter) DiskName() string {
return gfs.DiskNameGoogleCloudCloudStorage
}
func (a *Adapter) Client() (*storage.Client, error) {
var err error
a.storageClient, err = storage.NewClient(a.ctx, a.Config.Option...)
if err != nil {
return nil, err
}
return a.storageClient, err
}
func (a *Adapter) Bucket(bucket string) gfs.IAdapter {
a.bucket = bucket
return a
}
func (a *Adapter) StorageObject(object string) (*storage.ObjectHandle, error) {
client, err := a.Client()
if err != nil {
return nil, err
}
obj := client.Bucket(a.Config.UseBucket(a.bucket)).Object(object).If(
storage.Conditions{DoesNotExist: true},
)
return obj, nil
}
func (a *Adapter) StorageObjectTimeout(object string) (*storage.ObjectHandle, context.Context, error) {
objectHandle, err := a.StorageObject(object)
if err != nil {
return nil, a.ctx, err
}
ctx, cancel := context.WithTimeout(a.ctx, a.Config.WithTimeout)
a.closeTimeoutCancel = append(a.closeTimeoutCancel, cancel)
return objectHandle, ctx, nil
}
func (a *Adapter) GetMetadata(object string) (*storage.ObjectAttrs, error) {
obj, ctx, err := a.StorageObjectTimeout(object)
defer a.Close()
if err != nil {
return nil, err
}
return obj.Attrs(ctx)
}
func (a *Adapter) CopyObject(source, destination string, deleteSource bool) (bool, error) {
src, ctx, err := a.StorageObjectTimeout(source)
defer a.Close()
if err != nil {
return false, err
}
dst, _, err := a.StorageObjectTimeout(source)
defer a.Close()
if err != nil {
return false, err
}
if _, err := dst.CopierFrom(src).Run(ctx); err != nil {
return false, fmt.Errorf("Object(%q).CopierFrom(%q).Run: %w", source, destination, err)
}
if deleteSource {
defer func() {
_ = src.Delete(ctx)
}()
}
return true, nil
}
func (a *Adapter) URL(path string) (*url.URL, error) {
return a.Config.URL(path)
}
func (a *Adapter) Exist(path string) (bool, error) {
size, err := a.Size(path)
if size > 0 && err == nil {
return true, nil
}
return false, err
}
func (a *Adapter) WriteReader(path string, reader io.Reader) error {
obj, ctx, err := a.StorageObjectTimeout(path)
defer a.Close()
if err != nil {
return fmt.Errorf("storage.storageObject: %w", err)
}
// Upload an object with storage.Writer.
wc := obj.NewWriter(ctx)
wc.ChunkSize = 0 // note retries are not supported for chunk size 0.
if _, err = io.Copy(wc, reader); err != nil {
return fmt.Errorf("io.Copy: %w", err)
}
// Data can continue to be added to the file until the writer is closed.
if err := wc.Close(); err != nil {
return fmt.Errorf("Writer.Close: %w", err)
}
return nil
}
func (a *Adapter) Write(path string, contents []byte) error {
return a.WriteReader(path, bytes.NewBuffer(contents))
}
func (a *Adapter) WriteStream(path, resource string) error {
f, err := os.Open(resource)
if err != nil {
return fmt.Errorf("os.Open: %w", err)
}
return a.WriteReader(path, f)
}
func (a *Adapter) Read(path string) ([]byte, error) {
obj, ctx, err := a.StorageObjectTimeout(path)
defer a.Close()
if err != nil {
return nil, err
}
rc, err := obj.NewReader(ctx)
if err != nil {
return nil, fmt.Errorf("Object(%q).NewReader: %w", path, err)
}
defer rc.Close()
data, err := io.ReadAll(rc)
if err != nil {
return nil, fmt.Errorf("io.ReadAll: %w", err)
}
return data, nil
}
func (a *Adapter) Delete(path string) (int64, error) {
obj, ctx, err := a.StorageObjectTimeout(path)
defer a.Close()
if err != nil {
return 0, err
}
err = obj.Delete(ctx)
if err != nil {
return 0, err
}
return 1, nil
}
func (a *Adapter) Size(path string) (int64, error) {
metadata, err := a.GetMetadata(path)
if err != nil {
return 0, err
}
return metadata.Size, nil
}
func (a *Adapter) Update(path string, contents []byte) error {
return fmt.Errorf("update implement me")
}
func (a *Adapter) UpdateStream(path, resource string) error {
return fmt.Errorf("update implement me")
}
func (a *Adapter) MimeType(path string) (string, error) {
metadata, err := a.GetMetadata(path)
if err != nil {
return "", err
}
return metadata.ContentType, nil
}
func (a *Adapter) Move(source, destination string) (bool, error) {
return a.CopyObject(source, destination, true)
}
func (a *Adapter) Copy(source, destination string) (bool, error) {
return a.CopyObject(source, destination, false)
}
func (a *Adapter) Close() {
for _, f := range a.closeTimeoutCancel {
f()
}
_ = a.storageClient.Close()
}