| 1 |
// Copyright 2018 The Go Cloud Development Kit Authors |
| 2 |
// |
| 3 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
// you may not use this file except in compliance with the License. |
| 5 |
// You may obtain a copy of the License at |
| 6 |
// |
| 7 |
// https://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
// |
| 9 |
// Unless required by applicable law or agreed to in writing, software |
| 10 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 |
// See the License for the specific language governing permissions and |
| 13 |
// limitations under the License. |
| 14 |
|
| 15 |
// Package memblob provides an in-memory blob implementation. |
| 16 |
// Use OpenBucket to construct a *blob.Bucket. |
| 17 |
// |
| 18 |
// # URLs |
| 19 |
// |
| 20 |
// For blob.OpenBucket memblob registers for the scheme "mem". |
| 21 |
// To customize the URL opener, or for more details on the URL format, |
| 22 |
// see URLOpener. |
| 23 |
// See https://gocloud.dev/concepts/urls/ for background information. |
| 24 |
// |
| 25 |
// # As |
| 26 |
// |
| 27 |
// memblob does not support any types for As. |
| 28 |
package memblob // import "gocloud.dev/blob/memblob" |
| 29 |
|
| 30 |
import ( |
| 31 |
"bytes" |
| 32 |
"context" |
| 33 |
"crypto/md5" |
| 34 |
"errors" |
| 35 |
"fmt" |
| 36 |
"gocloud.dev/internal/gcerr" |
| 37 |
"hash" |
| 38 |
"io" |
| 39 |
"maps" |
| 40 |
"net/url" |
| 41 |
"sort" |
| 42 |
"strings" |
| 43 |
"sync" |
| 44 |
"time" |
| 45 |
|
| 46 |
"gocloud.dev/blob" |
| 47 |
"gocloud.dev/blob/driver" |
| 48 |
"gocloud.dev/gcerrors" |
| 49 |
) |
| 50 |
|
| 51 |
const defaultPageSize = 1000 |
| 52 |
|
| 53 |
var ( |
| 54 |
errNotFound = errors.New("blob not found") |
| 55 |
errNotImplemented = errors.New("not implemented") |
| 56 |
) |
| 57 |
|
| 58 |
func init() { |
| 59 |
blob.DefaultURLMux().RegisterBucket(Scheme, &URLOpener{}) |
| 60 |
} |
| 61 |
|
| 62 |
// Scheme is the URL scheme memblob registers its URLOpener under on |
| 63 |
// blob.DefaultMux. |
| 64 |
const Scheme = "mem" |
| 65 |
|
| 66 |
// URLOpener opens URLs like "mem://". |
| 67 |
// |
| 68 |
// The following query parameters are supported: |
| 69 |
// - nomd5: Sets Options.MD5 to true; no value expected (e.g., "memblob://?nomd5"). |
| 70 |
type URLOpener struct{} |
| 71 |
|
| 72 |
// OpenBucketURL opens a blob.Bucket based on u. |
| 73 |
func (*URLOpener) OpenBucketURL(ctx context.Context, u *url.URL) (*blob.Bucket, error) { |
| 74 |
opts := Options{} |
| 75 |
for param := range u.Query() { |
| 76 |
if param == "nomd5" { |
| 77 |
opts.NoMD5 = true |
| 78 |
continue |
| 79 |
} |
| 80 |
return nil, fmt.Errorf("open bucket %v: invalid query parameter %q", u, param) |
| 81 |
} |
| 82 |
return OpenBucket(&opts), nil |
| 83 |
} |
| 84 |
|
| 85 |
// Options sets options for constructing a *blob.Bucket backed by memory. |
| 86 |
type Options struct { |
| 87 |
// Set to true to disable MD5 hashing. The MD5 Attribute won't be available, |
| 88 |
// but improves write performance. |
| 89 |
NoMD5 bool |
| 90 |
} |
| 91 |
|
| 92 |
type blobEntry struct { |
| 93 |
Content []byte |
| 94 |
Attributes *driver.Attributes |
| 95 |
} |
| 96 |
|
| 97 |
type bucket struct { |
| 98 |
options Options |
| 99 |
|
| 100 |
mu sync.Mutex |
| 101 |
blobs map[string]*blobEntry |
| 102 |
} |
| 103 |
|
| 104 |
// openBucket creates a driver.Bucket backed by memory. |
| 105 |
func openBucket(opts *Options) driver.Bucket { |
| 106 |
if opts == nil { |
| 107 |
opts = &Options{} |
| 108 |
} |
| 109 |
return &bucket{ |
| 110 |
options: *opts, |
| 111 |
blobs: map[string]*blobEntry{}, |
| 112 |
} |
| 113 |
} |
| 114 |
|
| 115 |
// OpenBucket creates a *blob.Bucket backed by memory. |
| 116 |
func OpenBucket(opts *Options) *blob.Bucket { |
| 117 |
return blob.NewBucket(openBucket(opts)) |
| 118 |
} |
| 119 |
|
| 120 |
func (b *bucket) Close() error { |
| 121 |
return nil |
| 122 |
} |
| 123 |
|
| 124 |
func (b *bucket) ErrorCode(err error) gcerrors.ErrorCode { |
| 125 |
switch err { |
| 126 |
case errNotFound: |
| 127 |
return gcerrors.NotFound |
| 128 |
case errNotImplemented: |
| 129 |
return gcerrors.Unimplemented |
| 130 |
default: |
| 131 |
return gcerrors.Unknown |
| 132 |
} |
| 133 |
} |
| 134 |
|
| 135 |
// ListPaged implements driver.ListPaged. |
| 136 |
// The implementation largely mirrors the one in fileblob. |
| 137 |
func (b *bucket) ListPaged(ctx context.Context, opts *driver.ListOptions) (*driver.ListPage, error) { |
| 138 |
b.mu.Lock() |
| 139 |
defer b.mu.Unlock() |
| 140 |
|
| 141 |
// pageToken is a returned NextPageToken, set below; it's the last key of the |
| 142 |
// previous page. |
| 143 |
var pageToken string |
| 144 |
if len(opts.PageToken) > 0 { |
| 145 |
pageToken = string(opts.PageToken) |
| 146 |
} |
| 147 |
pageSize := opts.PageSize |
| 148 |
if pageSize == 0 { |
| 149 |
pageSize = defaultPageSize |
| 150 |
} |
| 151 |
|
| 152 |
var keys []string |
| 153 |
for key := range b.blobs { |
| 154 |
keys = append(keys, key) |
| 155 |
} |
| 156 |
sort.Strings(keys) |
| 157 |
|
| 158 |
// If opts.Delimiter != "", lastPrefix contains the last "directory" key we |
| 159 |
// added. It is used to avoid adding it again; all files in this "directory" |
| 160 |
// are collapsed to the single directory entry. |
| 161 |
var lastPrefix string |
| 162 |
var result driver.ListPage |
| 163 |
for _, key := range keys { |
| 164 |
// Skip keys that don't match the Prefix. |
| 165 |
if !strings.HasPrefix(key, opts.Prefix) { |
| 166 |
continue |
| 167 |
} |
| 168 |
|
| 169 |
entry := b.blobs[key] |
| 170 |
obj := &driver.ListObject{ |
| 171 |
Key: key, |
| 172 |
ModTime: entry.Attributes.ModTime, |
| 173 |
Size: entry.Attributes.Size, |
| 174 |
MD5: entry.Attributes.MD5, |
| 175 |
} |
| 176 |
|
| 177 |
// If using Delimiter, collapse "directories". |
| 178 |
if opts.Delimiter != "" { |
| 179 |
// Strip the prefix, which may contain Delimiter. |
| 180 |
keyWithoutPrefix := key[len(opts.Prefix):] |
| 181 |
// See if the key still contains Delimiter. |
| 182 |
// If no, it's a file and we just include it. |
| 183 |
// If yes, it's a file in a "sub-directory" and we want to collapse |
| 184 |
// all files in that "sub-directory" into a single "directory" result. |
| 185 |
if idx := strings.Index(keyWithoutPrefix, opts.Delimiter); idx != -1 { |
| 186 |
prefix := opts.Prefix + keyWithoutPrefix[0:idx+len(opts.Delimiter)] |
| 187 |
// We've already included this "directory"; don't add it. |
| 188 |
if prefix == lastPrefix { |
| 189 |
continue |
| 190 |
} |
| 191 |
// Update the object to be a "directory". |
| 192 |
obj = &driver.ListObject{ |
| 193 |
Key: prefix, |
| 194 |
IsDir: true, |
| 195 |
} |
| 196 |
lastPrefix = prefix |
| 197 |
} |
| 198 |
} |
| 199 |
|
| 200 |
// If there's a pageToken, skip anything before it. |
| 201 |
if pageToken != "" && obj.Key <= pageToken { |
| 202 |
continue |
| 203 |
} |
| 204 |
|
| 205 |
// If we've already got a full page of results, set NextPageToken and return. |
| 206 |
if len(result.Objects) == pageSize { |
| 207 |
result.NextPageToken = []byte(result.Objects[pageSize-1].Key) |
| 208 |
return &result, nil |
| 209 |
} |
| 210 |
result.Objects = append(result.Objects, obj) |
| 211 |
} |
| 212 |
return &result, nil |
| 213 |
} |
| 214 |
|
| 215 |
// As implements driver.As. |
| 216 |
func (b *bucket) As(i any) bool { return false } |
| 217 |
|
| 218 |
// As implements driver.ErrorAs. |
| 219 |
func (b *bucket) ErrorAs(err error, i any) bool { return false } |
| 220 |
|
| 221 |
// Attributes implements driver.Attributes. |
| 222 |
func (b *bucket) Attributes(ctx context.Context, key string) (*driver.Attributes, error) { |
| 223 |
b.mu.Lock() |
| 224 |
defer b.mu.Unlock() |
| 225 |
|
| 226 |
entry, found := b.blobs[key] |
| 227 |
if !found { |
| 228 |
return nil, errNotFound |
| 229 |
} |
| 230 |
return entry.Attributes, nil |
| 231 |
} |
| 232 |
|
| 233 |
// NewRangeReader implements driver.NewRangeReader. |
| 234 |
func (b *bucket) NewRangeReader(ctx context.Context, key string, offset, length int64, opts *driver.ReaderOptions) (driver.Reader, error) { |
| 235 |
b.mu.Lock() |
| 236 |
defer b.mu.Unlock() |
| 237 |
|
| 238 |
entry, found := b.blobs[key] |
| 239 |
if !found { |
| 240 |
return nil, errNotFound |
| 241 |
} |
| 242 |
|
| 243 |
if opts.BeforeRead != nil { |
| 244 |
if err := opts.BeforeRead(func(any) bool { return false }); err != nil { |
| 245 |
return nil, err |
| 246 |
} |
| 247 |
} |
| 248 |
r := bytes.NewReader(entry.Content) |
| 249 |
if offset > 0 { |
| 250 |
if _, err := r.Seek(offset, io.SeekStart); err != nil { |
| 251 |
return nil, err |
| 252 |
} |
| 253 |
} |
| 254 |
var ior io.Reader = r |
| 255 |
if length >= 0 { |
| 256 |
ior = io.LimitReader(r, length) |
| 257 |
} |
| 258 |
return &reader{ |
| 259 |
r: ior, |
| 260 |
attrs: driver.ReaderAttributes{ |
| 261 |
ContentType: entry.Attributes.ContentType, |
| 262 |
ModTime: entry.Attributes.ModTime, |
| 263 |
Size: entry.Attributes.Size, |
| 264 |
}, |
| 265 |
}, nil |
| 266 |
} |
| 267 |
|
| 268 |
type reader struct { |
| 269 |
r io.Reader |
| 270 |
attrs driver.ReaderAttributes |
| 271 |
} |
| 272 |
|
| 273 |
func (r *reader) Read(p []byte) (int, error) { |
| 274 |
return r.r.Read(p) |
| 275 |
} |
| 276 |
|
| 277 |
func (r *reader) Download(w io.Writer) error { |
| 278 |
// This should always work because r.r was created from a bytes.Reader. |
| 279 |
// It's only not a WriterTo when we wrap it with a LimitReader, |
| 280 |
// which is guaranteed not to happen by the driver interface. |
| 281 |
_, err := r.r.(io.WriterTo).WriteTo(w) |
| 282 |
return err |
| 283 |
} |
| 284 |
|
| 285 |
func (r *reader) Close() error { |
| 286 |
return nil |
| 287 |
} |
| 288 |
|
| 289 |
func (r *reader) Attributes() *driver.ReaderAttributes { |
| 290 |
return &r.attrs |
| 291 |
} |
| 292 |
|
| 293 |
func (r *reader) As(i any) bool { return false } |
| 294 |
|
| 295 |
// NewTypedWriter implements driver.NewTypedWriter. |
| 296 |
func (b *bucket) NewTypedWriter(ctx context.Context, key, contentType string, opts *driver.WriterOptions) (driver.Writer, error) { |
| 297 |
if key == "" { |
| 298 |
return nil, errors.New("invalid key (empty string)") |
| 299 |
} |
| 300 |
b.mu.Lock() |
| 301 |
defer b.mu.Unlock() |
| 302 |
|
| 303 |
if opts.BeforeWrite != nil { |
| 304 |
if err := opts.BeforeWrite(func(any) bool { return false }); err != nil { |
| 305 |
return nil, err |
| 306 |
} |
| 307 |
} |
| 308 |
md := map[string]string{} |
| 309 |
maps.Copy(md, opts.Metadata) |
| 310 |
|
| 311 |
var md5hash hash.Hash |
| 312 |
if !b.options.NoMD5 { |
| 313 |
md5hash = md5.New() |
| 314 |
} |
| 315 |
return &writer{ |
| 316 |
ctx: ctx, |
| 317 |
b: b, |
| 318 |
key: key, |
| 319 |
contentType: contentType, |
| 320 |
metadata: md, |
| 321 |
opts: opts, |
| 322 |
md5hash: md5hash, |
| 323 |
ifNotExist: opts.IfNotExist, |
| 324 |
}, nil |
| 325 |
} |
| 326 |
|
| 327 |
type writer struct { |
| 328 |
ctx context.Context |
| 329 |
b *bucket |
| 330 |
key string |
| 331 |
contentType string |
| 332 |
metadata map[string]string |
| 333 |
opts *driver.WriterOptions |
| 334 |
buf bytes.Buffer |
| 335 |
// We compute the MD5 hash so that we can store it with the file attributes, |
| 336 |
// not for verification. May be null if disabled via Options.NoMD5. |
| 337 |
md5hash hash.Hash |
| 338 |
ifNotExist bool |
| 339 |
} |
| 340 |
|
| 341 |
func (w *writer) Write(p []byte) (n int, err error) { |
| 342 |
if w.md5hash != nil { |
| 343 |
if _, err := w.md5hash.Write(p); err != nil { |
| 344 |
return 0, err |
| 345 |
} |
| 346 |
} |
| 347 |
return w.buf.Write(p) |
| 348 |
} |
| 349 |
|
| 350 |
func (w *writer) Upload(r io.Reader) error { |
| 351 |
_, err := w.buf.ReadFrom(r) |
| 352 |
return err |
| 353 |
} |
| 354 |
|
| 355 |
func (w *writer) Close() error { |
| 356 |
// Check if the write was cancelled. |
| 357 |
if err := w.ctx.Err(); err != nil { |
| 358 |
return err |
| 359 |
} |
| 360 |
|
| 361 |
var md5sum []byte |
| 362 |
if w.md5hash != nil { |
| 363 |
md5sum = w.md5hash.Sum(nil) |
| 364 |
} |
| 365 |
content := w.buf.Bytes() |
| 366 |
now := time.Now() |
| 367 |
entry := &blobEntry{ |
| 368 |
Content: content, |
| 369 |
Attributes: &driver.Attributes{ |
| 370 |
CacheControl: w.opts.CacheControl, |
| 371 |
ContentDisposition: w.opts.ContentDisposition, |
| 372 |
ContentEncoding: w.opts.ContentEncoding, |
| 373 |
ContentLanguage: w.opts.ContentLanguage, |
| 374 |
ContentType: w.contentType, |
| 375 |
Metadata: w.metadata, |
| 376 |
Size: int64(len(content)), |
| 377 |
CreateTime: now, |
| 378 |
ModTime: now, |
| 379 |
MD5: md5sum, |
| 380 |
ETag: fmt.Sprintf("\"%x-%x\"", now.UnixNano(), len(content)), |
| 381 |
}, |
| 382 |
} |
| 383 |
w.b.mu.Lock() |
| 384 |
defer w.b.mu.Unlock() |
| 385 |
if prev := w.b.blobs[w.key]; prev != nil { |
| 386 |
if w.ifNotExist { |
| 387 |
err := fmt.Errorf("a blob already exists for key %q", w.key) |
| 388 |
return gcerr.New(gcerrors.FailedPrecondition, err, 1, "IfNotExist precondition failed") |
| 389 |
} |
| 390 |
entry.Attributes.CreateTime = prev.Attributes.CreateTime |
| 391 |
} |
| 392 |
w.b.blobs[w.key] = entry |
| 393 |
return nil |
| 394 |
} |
| 395 |
|
| 396 |
// Copy implements driver.Copy. |
| 397 |
func (b *bucket) Copy(ctx context.Context, dstKey, srcKey string, opts *driver.CopyOptions) error { |
| 398 |
b.mu.Lock() |
| 399 |
defer b.mu.Unlock() |
| 400 |
|
| 401 |
if opts.BeforeCopy != nil { |
| 402 |
if err := opts.BeforeCopy(func(any) bool { return false }); err != nil { |
| 403 |
return err |
| 404 |
} |
| 405 |
} |
| 406 |
v := b.blobs[srcKey] |
| 407 |
if v == nil { |
| 408 |
return errNotFound |
| 409 |
} |
| 410 |
b.blobs[dstKey] = v |
| 411 |
return nil |
| 412 |
} |
| 413 |
|
| 414 |
// Delete implements driver.Delete. |
| 415 |
func (b *bucket) Delete(ctx context.Context, key string) error { |
| 416 |
b.mu.Lock() |
| 417 |
defer b.mu.Unlock() |
| 418 |
|
| 419 |
if b.blobs[key] == nil { |
| 420 |
return errNotFound |
| 421 |
} |
| 422 |
delete(b.blobs, key) |
| 423 |
return nil |
| 424 |
} |
| 425 |
|
| 426 |
func (b *bucket) SignedURL(ctx context.Context, key string, opts *driver.SignedURLOptions) (string, error) { |
| 427 |
return "", errNotImplemented |
| 428 |
} |