| 1 |
// Copyright 2023-2025 The NATS Authors |
| 2 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 3 |
// you may not use this file except in compliance with the License. |
| 4 |
// You may obtain a copy of the License at |
| 5 |
// |
| 6 |
// http://www.apache.org/licenses/LICENSE-2.0 |
| 7 |
// |
| 8 |
// Unless required by applicable law or agreed to in writing, software |
| 9 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 10 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 |
// See the License for the specific language governing permissions and |
| 12 |
// limitations under the License. |
| 13 |
|
| 14 |
package jetstream |
| 15 |
|
| 16 |
import ( |
| 17 |
"bytes" |
| 18 |
"context" |
| 19 |
"crypto/sha256" |
| 20 |
"encoding/base64" |
| 21 |
"encoding/json" |
| 22 |
"errors" |
| 23 |
"fmt" |
| 24 |
"hash" |
| 25 |
"io" |
| 26 |
"net" |
| 27 |
"os" |
| 28 |
"strings" |
| 29 |
"sync" |
| 30 |
"time" |
| 31 |
|
| 32 |
"github.com/nats-io/nats.go" |
| 33 |
"github.com/nats-io/nats.go/internal/parser" |
| 34 |
"github.com/nats-io/nuid" |
| 35 |
) |
| 36 |
|
| 37 |
type ( |
| 38 |
// ObjectStoreManager is used to manage object stores. It provides methods |
| 39 |
// CRUD operations on object stores. |
| 40 |
ObjectStoreManager interface { |
| 41 |
// ObjectStore will look up and bind to an existing object store |
| 42 |
// instance. |
| 43 |
// |
| 44 |
// If the object store with given name does not exist, ErrBucketNotFound |
| 45 |
// will be returned. |
| 46 |
ObjectStore(ctx context.Context, bucket string) (ObjectStore, error) |
| 47 |
|
| 48 |
// CreateObjectStore will create a new object store with the given |
| 49 |
// configuration. |
| 50 |
// |
| 51 |
// If the object store with given name already exists, ErrBucketExists |
| 52 |
// will be returned. |
| 53 |
CreateObjectStore(ctx context.Context, cfg ObjectStoreConfig) (ObjectStore, error) |
| 54 |
|
| 55 |
// UpdateObjectStore will update an existing object store with the given |
| 56 |
// configuration. |
| 57 |
// |
| 58 |
// If the object store with given name does not exist, ErrBucketNotFound |
| 59 |
// will be returned. |
| 60 |
UpdateObjectStore(ctx context.Context, cfg ObjectStoreConfig) (ObjectStore, error) |
| 61 |
|
| 62 |
// CreateOrUpdateObjectStore will create a new object store with the given |
| 63 |
// configuration if it does not exist, or update an existing object store |
| 64 |
// with the given configuration. |
| 65 |
CreateOrUpdateObjectStore(ctx context.Context, cfg ObjectStoreConfig) (ObjectStore, error) |
| 66 |
|
| 67 |
// DeleteObjectStore will delete the provided object store. |
| 68 |
// |
| 69 |
// If the object store with given name does not exist, ErrBucketNotFound |
| 70 |
// will be returned. |
| 71 |
DeleteObjectStore(ctx context.Context, bucket string) error |
| 72 |
|
| 73 |
// ObjectStoreNames is used to retrieve a list of bucket names. |
| 74 |
// It returns an ObjectStoreNamesLister exposing a channel to receive |
| 75 |
// the names of the object stores. |
| 76 |
// |
| 77 |
// The lister will always close the channel when done (either all names |
| 78 |
// have been read or an error occurred) and therefore can be used in a |
| 79 |
// for-range loop. |
| 80 |
ObjectStoreNames(ctx context.Context) ObjectStoreNamesLister |
| 81 |
|
| 82 |
// ObjectStores is used to retrieve a list of bucket statuses. |
| 83 |
// It returns an ObjectStoresLister exposing a channel to receive |
| 84 |
// the statuses of the object stores. |
| 85 |
// |
| 86 |
// The lister will always close the channel when done (either all statuses |
| 87 |
// have been read or an error occurred) and therefore can be used in a |
| 88 |
// for-range loop. |
| 89 |
ObjectStores(ctx context.Context) ObjectStoresLister |
| 90 |
} |
| 91 |
|
| 92 |
// ObjectStore contains methods to operate on an object store. |
| 93 |
// Using the ObjectStore interface, it is possible to: |
| 94 |
// |
| 95 |
// - Perform CRUD operations on objects (Get, Put, Delete). |
| 96 |
// Get and put expose convenience methods to work with |
| 97 |
// byte slices, strings and files, in addition to streaming [io.Reader] |
| 98 |
// - Get information about an object without retrieving it. |
| 99 |
// - Update the metadata of an object. |
| 100 |
// - Add links to other objects or object stores. |
| 101 |
// - Watch for updates to a store |
| 102 |
// - List information about objects in a store |
| 103 |
// - Retrieve status and configuration of an object store. |
| 104 |
ObjectStore interface { |
| 105 |
// Put will place the contents from the reader into a new object. If the |
| 106 |
// object already exists, it will be overwritten. The object name is |
| 107 |
// required and is taken from the ObjectMeta.Name field. |
| 108 |
// |
| 109 |
// The reader will be read until EOF. ObjectInfo will be returned, containing |
| 110 |
// the object's metadata, digest and instance information. |
| 111 |
Put(ctx context.Context, obj ObjectMeta, reader io.Reader) (*ObjectInfo, error) |
| 112 |
|
| 113 |
// PutBytes is convenience function to put a byte slice into this object |
| 114 |
// store under the given name. |
| 115 |
// |
| 116 |
// ObjectInfo will be returned, containing the object's metadata, digest |
| 117 |
// and instance information. |
| 118 |
PutBytes(ctx context.Context, name string, data []byte) (*ObjectInfo, error) |
| 119 |
|
| 120 |
// PutString is convenience function to put a string into this object |
| 121 |
// store under the given name. |
| 122 |
// |
| 123 |
// ObjectInfo will be returned, containing the object's metadata, digest |
| 124 |
// and instance information. |
| 125 |
PutString(ctx context.Context, name string, data string) (*ObjectInfo, error) |
| 126 |
|
| 127 |
// PutFile is convenience function to put a file contents into this |
| 128 |
// object store. The name of the object will be the path of the file. |
| 129 |
// |
| 130 |
// ObjectInfo will be returned, containing the object's metadata, digest |
| 131 |
// and instance information. |
| 132 |
PutFile(ctx context.Context, file string) (*ObjectInfo, error) |
| 133 |
|
| 134 |
// Get will pull the named object from the object store. If the object |
| 135 |
// does not exist, ErrObjectNotFound will be returned. |
| 136 |
// |
| 137 |
// The returned ObjectResult will contain the object's metadata and a |
| 138 |
// reader to read the object's contents. The reader will be closed when |
| 139 |
// all data has been read or an error occurs. |
| 140 |
// |
| 141 |
// A GetObjectShowDeleted option can be supplied to return an object |
| 142 |
// even if it was marked as deleted. |
| 143 |
Get(ctx context.Context, name string, opts ...GetObjectOpt) (ObjectResult, error) |
| 144 |
|
| 145 |
// GetBytes is a convenience function to pull an object from this object |
| 146 |
// store and return it as a byte slice. |
| 147 |
// |
| 148 |
// If the object does not exist, ErrObjectNotFound will be returned. |
| 149 |
// |
| 150 |
// A GetObjectShowDeleted option can be supplied to return an object |
| 151 |
// even if it was marked as deleted. |
| 152 |
GetBytes(ctx context.Context, name string, opts ...GetObjectOpt) ([]byte, error) |
| 153 |
|
| 154 |
// GetString is a convenience function to pull an object from this |
| 155 |
// object store and return it as a string. |
| 156 |
// |
| 157 |
// If the object does not exist, ErrObjectNotFound will be returned. |
| 158 |
// |
| 159 |
// A GetObjectShowDeleted option can be supplied to return an object |
| 160 |
// even if it was marked as deleted. |
| 161 |
GetString(ctx context.Context, name string, opts ...GetObjectOpt) (string, error) |
| 162 |
|
| 163 |
// GetFile is a convenience function to pull an object from this object |
| 164 |
// store and place it in a file. If the file already exists, it will be |
| 165 |
// overwritten, otherwise it will be created. |
| 166 |
// |
| 167 |
// If the object does not exist, ErrObjectNotFound will be returned. |
| 168 |
// A GetObjectShowDeleted option can be supplied to return an object |
| 169 |
// even if it was marked as deleted. |
| 170 |
GetFile(ctx context.Context, name, file string, opts ...GetObjectOpt) error |
| 171 |
|
| 172 |
// GetInfo will retrieve the current information for the object, containing |
| 173 |
// the object's metadata and instance information. |
| 174 |
// |
| 175 |
// If the object does not exist, ErrObjectNotFound will be returned. |
| 176 |
// |
| 177 |
// A GetObjectInfoShowDeleted option can be supplied to return an object |
| 178 |
// even if it was marked as deleted. |
| 179 |
GetInfo(ctx context.Context, name string, opts ...GetObjectInfoOpt) (*ObjectInfo, error) |
| 180 |
|
| 181 |
// UpdateMeta will update the metadata for the object. |
| 182 |
// |
| 183 |
// If the object does not exist, ErrUpdateMetaDeleted will be returned. |
| 184 |
// If the new name is different from the old name, and an object with the |
| 185 |
// new name already exists, ErrObjectAlreadyExists will be returned. |
| 186 |
UpdateMeta(ctx context.Context, name string, meta ObjectMeta) error |
| 187 |
|
| 188 |
// Delete will delete the named object from the object store. If the object |
| 189 |
// does not exist, ErrObjectNotFound will be returned. If the object is |
| 190 |
// already deleted, no error will be returned. |
| 191 |
// |
| 192 |
// All chunks for the object will be purged, and the object will be marked |
| 193 |
// as deleted. |
| 194 |
Delete(ctx context.Context, name string) error |
| 195 |
|
| 196 |
// AddLink will add a link to another object. A link is a reference to |
| 197 |
// another object. The provided name is the name of the link object. |
| 198 |
// The provided ObjectInfo is the info of the object being linked to. |
| 199 |
// |
| 200 |
// If an object with given name already exists, ErrObjectAlreadyExists |
| 201 |
// will be returned. |
| 202 |
// If object being linked to is deleted, ErrNoLinkToDeleted will be |
| 203 |
// returned. |
| 204 |
// If the provided object is a link, ErrNoLinkToLink will be returned. |
| 205 |
// If the provided object is nil or the name is empty, ErrObjectRequired |
| 206 |
// will be returned. |
| 207 |
AddLink(ctx context.Context, name string, obj *ObjectInfo) (*ObjectInfo, error) |
| 208 |
|
| 209 |
// AddBucketLink will add a link to another object store. A link is a |
| 210 |
// reference to another object store. The provided name is the name of |
| 211 |
// the link object. |
| 212 |
// The provided ObjectStore is the object store being linked to. |
| 213 |
// |
| 214 |
// If an object with given name already exists, ErrObjectAlreadyExists |
| 215 |
// will be returned. |
| 216 |
// If the provided object store is nil ErrBucketRequired will be returned. |
| 217 |
AddBucketLink(ctx context.Context, name string, bucket ObjectStore) (*ObjectInfo, error) |
| 218 |
|
| 219 |
// Seal will seal the object store, no further modifications will be allowed. |
| 220 |
Seal(ctx context.Context) error |
| 221 |
|
| 222 |
// Watch for any updates to objects in the store. By default, the watcher will send the latest |
| 223 |
// info for each object and all future updates. Watch will send a nil |
| 224 |
// entry when it has received all initial values. There are a few ways |
| 225 |
// to configure the watcher: |
| 226 |
// |
| 227 |
// - IncludeHistory will have the watcher send all historical information |
| 228 |
// for each object. |
| 229 |
// - IgnoreDeletes will have the watcher not pass any objects with |
| 230 |
// delete markers. |
| 231 |
// - UpdatesOnly will have the watcher only pass updates on objects |
| 232 |
// (without latest info when started). |
| 233 |
Watch(ctx context.Context, opts ...WatchOpt) (ObjectWatcher, error) |
| 234 |
|
| 235 |
// List will list information about objects in the store. |
| 236 |
// |
| 237 |
// If the object store is empty, ErrNoObjectsFound will be returned. |
| 238 |
List(ctx context.Context, opts ...ListObjectsOpt) ([]*ObjectInfo, error) |
| 239 |
|
| 240 |
// Status retrieves the status and configuration of the bucket. |
| 241 |
Status(ctx context.Context) (ObjectStoreStatus, error) |
| 242 |
} |
| 243 |
|
| 244 |
// ObjectWatcher is what is returned when doing a watch. It can be used to |
| 245 |
// retrieve updates to objects in a bucket. If not using UpdatesOnly option, |
| 246 |
// it will also send the latest value for each key. After all initial values |
| 247 |
// have been sent, a nil entry will be sent. Stop can be used to stop the |
| 248 |
// watcher and close the underlying channel. Watcher will not close the |
| 249 |
// channel until Stop is called or connection is closed. |
| 250 |
ObjectWatcher interface { |
| 251 |
Updates() <-chan *ObjectInfo |
| 252 |
Stop() error |
| 253 |
} |
| 254 |
|
| 255 |
// ObjectStoreConfig is the configuration for the object store. |
| 256 |
ObjectStoreConfig struct { |
| 257 |
// Bucket is the name of the object store. Bucket name has to be |
| 258 |
// unique and can only contain alphanumeric characters, dashes, and |
| 259 |
// underscores. |
| 260 |
Bucket string `json:"bucket"` |
| 261 |
|
| 262 |
// Description is an optional description for the object store. |
| 263 |
Description string `json:"description,omitempty"` |
| 264 |
|
| 265 |
// TTL is the maximum age of objects in the store. If an object is not |
| 266 |
// updated within this time, it will be removed from the store. |
| 267 |
// By default, objects do not expire. |
| 268 |
TTL time.Duration `json:"max_age,omitempty"` |
| 269 |
|
| 270 |
// MaxBytes is the maximum size of the object store. If not specified, |
| 271 |
// the default is -1 (unlimited). |
| 272 |
MaxBytes int64 `json:"max_bytes,omitempty"` |
| 273 |
|
| 274 |
// Storage is the type of storage to use for the object store. If not |
| 275 |
// specified, the default is FileStorage. |
| 276 |
Storage StorageType `json:"storage,omitempty"` |
| 277 |
|
| 278 |
// Replicas is the number of replicas to keep for the object store in |
| 279 |
// clustered jetstream. Defaults to 1, maximum is 5. |
| 280 |
Replicas int `json:"num_replicas,omitempty"` |
| 281 |
|
| 282 |
// Placement is used to declare where the object store should be placed via |
| 283 |
// tags and/or an explicit cluster name. |
| 284 |
Placement *Placement `json:"placement,omitempty"` |
| 285 |
|
| 286 |
// Compression enables the underlying stream compression. |
| 287 |
// NOTE: Compression is supported for nats-server 2.10.0+ |
| 288 |
Compression bool `json:"compression,omitempty"` |
| 289 |
|
| 290 |
// Bucket-specific metadata |
| 291 |
// NOTE: Metadata requires nats-server v2.10.0+ |
| 292 |
Metadata map[string]string `json:"metadata,omitempty"` |
| 293 |
} |
| 294 |
|
| 295 |
// ObjectStoresLister is used to retrieve a list of object stores. It returns |
| 296 |
// a channel to read the bucket store statuses from. The lister will always |
| 297 |
// close the channel when done (either all stores have been retrieved or an |
| 298 |
// error occurred) and therefore can be used in range loops. Stop can be |
| 299 |
// used to stop the lister when not all object stores have been read. |
| 300 |
ObjectStoresLister interface { |
| 301 |
Status() <-chan ObjectStoreStatus |
| 302 |
Error() error |
| 303 |
} |
| 304 |
|
| 305 |
// ObjectStoreNamesLister is used to retrieve a list of object store names. |
| 306 |
// It returns a channel to read the bucket names from. The lister will |
| 307 |
// always close the channel when done (either all stores have been retrieved |
| 308 |
// or an error occurred) and therefore can be used in range loops. Stop can |
| 309 |
// be used to stop the lister when not all bucket names have been read. |
| 310 |
ObjectStoreNamesLister interface { |
| 311 |
Name() <-chan string |
| 312 |
Error() error |
| 313 |
} |
| 314 |
|
| 315 |
// ObjectStoreStatus is run-time status about a bucket. |
| 316 |
ObjectStoreStatus interface { |
| 317 |
// Bucket returns the name of the object store. |
| 318 |
Bucket() string |
| 319 |
|
| 320 |
// Description is the description supplied when creating the bucket. |
| 321 |
Description() string |
| 322 |
|
| 323 |
// TTL indicates how long objects are kept in the bucket. |
| 324 |
TTL() time.Duration |
| 325 |
|
| 326 |
// Storage indicates the underlying JetStream storage technology used to |
| 327 |
// store data. |
| 328 |
Storage() StorageType |
| 329 |
|
| 330 |
// Replicas indicates how many storage replicas are kept for the data in |
| 331 |
// the bucket. |
| 332 |
Replicas() int |
| 333 |
|
| 334 |
// Sealed indicates the stream is sealed and cannot be modified in any |
| 335 |
// way. |
| 336 |
Sealed() bool |
| 337 |
|
| 338 |
// Size is the combined size of all data in the bucket including |
| 339 |
// metadata, in bytes. |
| 340 |
Size() uint64 |
| 341 |
|
| 342 |
// BackingStore indicates what technology is used for storage of the |
| 343 |
// bucket. Currently only JetStream is supported. |
| 344 |
BackingStore() string |
| 345 |
|
| 346 |
// Metadata is the user supplied metadata for the bucket. |
| 347 |
Metadata() map[string]string |
| 348 |
|
| 349 |
// IsCompressed indicates if the data is compressed on disk. |
| 350 |
IsCompressed() bool |
| 351 |
} |
| 352 |
|
| 353 |
// ObjectMetaOptions is used to set additional options when creating an object. |
| 354 |
ObjectMetaOptions struct { |
| 355 |
// Link contains information about a link to another object or object store. |
| 356 |
// It should not be set manually, but rather by using the AddLink or |
| 357 |
// AddBucketLink methods. |
| 358 |
Link *ObjectLink `json:"link,omitempty"` |
| 359 |
|
| 360 |
// ChunkSize is the maximum size of each chunk in bytes. If not specified, |
| 361 |
// the default is 128k. |
| 362 |
ChunkSize uint32 `json:"max_chunk_size,omitempty"` |
| 363 |
} |
| 364 |
|
| 365 |
// ObjectMeta is high level information about an object. |
| 366 |
ObjectMeta struct { |
| 367 |
// Name is the name of the object. The name is required when adding an |
| 368 |
// object and has to be unique within the object store. |
| 369 |
Name string `json:"name"` |
| 370 |
|
| 371 |
// Description is an optional description for the object. |
| 372 |
Description string `json:"description,omitempty"` |
| 373 |
|
| 374 |
// Headers is an optional set of user-defined headers for the object. |
| 375 |
Headers nats.Header `json:"headers,omitempty"` |
| 376 |
|
| 377 |
// Metadata is the user supplied metadata for the object. |
| 378 |
Metadata map[string]string `json:"metadata,omitempty"` |
| 379 |
|
| 380 |
// Additional options for the object. |
| 381 |
Opts *ObjectMetaOptions `json:"options,omitempty"` |
| 382 |
} |
| 383 |
|
| 384 |
// ObjectInfo contains ObjectMeta and additional information about an |
| 385 |
// object. |
| 386 |
ObjectInfo struct { |
| 387 |
// ObjectMeta contains high level information about the object. |
| 388 |
ObjectMeta |
| 389 |
|
| 390 |
// Bucket is the name of the object store. |
| 391 |
Bucket string `json:"bucket"` |
| 392 |
|
| 393 |
// NUID is the unique identifier for the object set when putting the |
| 394 |
// object into the store. |
| 395 |
NUID string `json:"nuid"` |
| 396 |
|
| 397 |
// Size is the size of the object in bytes. It only includes the size of |
| 398 |
// the object itself, not the metadata. |
| 399 |
Size uint64 `json:"size"` |
| 400 |
|
| 401 |
// ModTime is the last modification time of the object. |
| 402 |
ModTime time.Time `json:"mtime"` |
| 403 |
|
| 404 |
// Chunks is the number of chunks the object is split into. Maximum size |
| 405 |
// of each chunk can be specified in ObjectMetaOptions. |
| 406 |
Chunks uint32 `json:"chunks"` |
| 407 |
|
| 408 |
// Digest is the SHA-256 digest of the object. It is used to verify the |
| 409 |
// integrity of the object. |
| 410 |
Digest string `json:"digest,omitempty"` |
| 411 |
|
| 412 |
// Deleted indicates if the object is marked as deleted. |
| 413 |
Deleted bool `json:"deleted,omitempty"` |
| 414 |
} |
| 415 |
|
| 416 |
// ObjectLink is used to embed links to other buckets and objects. |
| 417 |
ObjectLink struct { |
| 418 |
// Bucket is the name of the object store the link is pointing to. |
| 419 |
Bucket string `json:"bucket"` |
| 420 |
|
| 421 |
// Name can be used to link to a single object. |
| 422 |
// If empty means this is a link to the whole store, like a directory. |
| 423 |
Name string `json:"name,omitempty"` |
| 424 |
} |
| 425 |
|
| 426 |
// ObjectResult will return the object info and a reader to read the object's |
| 427 |
// contents. The reader will be closed when all data has been read or an |
| 428 |
// error occurs. |
| 429 |
ObjectResult interface { |
| 430 |
io.ReadCloser |
| 431 |
Info() (*ObjectInfo, error) |
| 432 |
Error() error |
| 433 |
} |
| 434 |
|
| 435 |
// GetObjectOpt is used to set additional options when getting an object. |
| 436 |
GetObjectOpt func(opts *getObjectOpts) error |
| 437 |
|
| 438 |
// GetObjectInfoOpt is used to set additional options when getting object info. |
| 439 |
GetObjectInfoOpt func(opts *getObjectInfoOpts) error |
| 440 |
|
| 441 |
// ListObjectsOpt is used to set additional options when listing objects. |
| 442 |
ListObjectsOpt func(opts *listObjectOpts) error |
| 443 |
|
| 444 |
getObjectOpts struct { |
| 445 |
// Include deleted object in the result. |
| 446 |
showDeleted bool |
| 447 |
} |
| 448 |
|
| 449 |
getObjectInfoOpts struct { |
| 450 |
// Include deleted object in the result. |
| 451 |
showDeleted bool |
| 452 |
} |
| 453 |
|
| 454 |
listObjectOpts struct { |
| 455 |
// Include deleted objects in the result channel. |
| 456 |
showDeleted bool |
| 457 |
} |
| 458 |
|
| 459 |
obs struct { |
| 460 |
name string |
| 461 |
streamName string |
| 462 |
stream Stream |
| 463 |
pushJS nats.JetStreamContext |
| 464 |
js *jetStream |
| 465 |
} |
| 466 |
|
| 467 |
// ObjectResult impl. |
| 468 |
objResult struct { |
| 469 |
sync.Mutex |
| 470 |
info *ObjectInfo |
| 471 |
r io.ReadCloser |
| 472 |
err error |
| 473 |
ctx context.Context |
| 474 |
cancel context.CancelFunc |
| 475 |
digest hash.Hash |
| 476 |
} |
| 477 |
) |
| 478 |
|
| 479 |
const ( |
| 480 |
objNameTmpl = "OBJ_%s" // OBJ_<bucket> // stream name |
| 481 |
objAllChunksPreTmpl = "$O.%s.C.>" // $O.<bucket>.C.> // chunk stream subject |
| 482 |
objAllMetaPreTmpl = "$O.%s.M.>" // $O.<bucket>.M.> // meta stream subject |
| 483 |
objChunksPreTmpl = "$O.%s.C.%s" // $O.<bucket>.C.<object-nuid> // chunk message subject |
| 484 |
objMetaPreTmpl = "$O.%s.M.%s" // $O.<bucket>.M.<name-encoded> // meta message subject |
| 485 |
objNoPending = "0" |
| 486 |
objDefaultChunkSize = uint32(128 * 1024) // 128k |
| 487 |
objDigestType = "SHA-256=" |
| 488 |
objDigestTmpl = objDigestType + "%s" |
| 489 |
) |
| 490 |
|
| 491 |
func (js *jetStream) CreateObjectStore(ctx context.Context, cfg ObjectStoreConfig) (ObjectStore, error) { |
| 492 |
scfg, err := js.prepareObjectStoreConfig(cfg) |
| 493 |
if err != nil { |
| 494 |
return nil, err |
| 495 |
} |
| 496 |
|
| 497 |
stream, err := js.CreateStream(ctx, scfg) |
| 498 |
if err != nil { |
| 499 |
if errors.Is(err, ErrStreamNameAlreadyInUse) { |
| 500 |
// errors are joined so that backwards compatibility is retained |
| 501 |
// and previous checks for ErrStreamNameAlreadyInUse will still work. |
| 502 |
err = errors.Join(fmt.Errorf("%w: %s", ErrBucketExists, cfg.Bucket), err) |
| 503 |
} |
| 504 |
return nil, err |
| 505 |
} |
| 506 |
pushJS, err := js.legacyJetStream() |
| 507 |
if err != nil { |
| 508 |
return nil, err |
| 509 |
} |
| 510 |
|
| 511 |
return mapStreamToObjectStore(js, pushJS, cfg.Bucket, stream), nil |
| 512 |
} |
| 513 |
|
| 514 |
func (js *jetStream) UpdateObjectStore(ctx context.Context, cfg ObjectStoreConfig) (ObjectStore, error) { |
| 515 |
scfg, err := js.prepareObjectStoreConfig(cfg) |
| 516 |
if err != nil { |
| 517 |
return nil, err |
| 518 |
} |
| 519 |
|
| 520 |
// Attempt to update the stream. |
| 521 |
stream, err := js.UpdateStream(ctx, scfg) |
| 522 |
if err != nil { |
| 523 |
if errors.Is(err, ErrStreamNotFound) { |
| 524 |
return nil, fmt.Errorf("%w: %s", ErrBucketNotFound, cfg.Bucket) |
| 525 |
} |
| 526 |
return nil, err |
| 527 |
} |
| 528 |
pushJS, err := js.legacyJetStream() |
| 529 |
if err != nil { |
| 530 |
return nil, err |
| 531 |
} |
| 532 |
|
| 533 |
return mapStreamToObjectStore(js, pushJS, cfg.Bucket, stream), nil |
| 534 |
} |
| 535 |
|
| 536 |
func (js *jetStream) CreateOrUpdateObjectStore(ctx context.Context, cfg ObjectStoreConfig) (ObjectStore, error) { |
| 537 |
scfg, err := js.prepareObjectStoreConfig(cfg) |
| 538 |
if err != nil { |
| 539 |
return nil, err |
| 540 |
} |
| 541 |
|
| 542 |
stream, err := js.CreateOrUpdateStream(ctx, scfg) |
| 543 |
if err != nil { |
| 544 |
return nil, err |
| 545 |
} |
| 546 |
pushJS, err := js.legacyJetStream() |
| 547 |
if err != nil { |
| 548 |
return nil, err |
| 549 |
} |
| 550 |
|
| 551 |
return mapStreamToObjectStore(js, pushJS, cfg.Bucket, stream), nil |
| 552 |
} |
| 553 |
|
| 554 |
func (js *jetStream) prepareObjectStoreConfig(cfg ObjectStoreConfig) (StreamConfig, error) { |
| 555 |
if !validBucketRe.MatchString(cfg.Bucket) { |
| 556 |
return StreamConfig{}, ErrInvalidStoreName |
| 557 |
} |
| 558 |
|
| 559 |
name := cfg.Bucket |
| 560 |
chunks := fmt.Sprintf(objAllChunksPreTmpl, name) |
| 561 |
meta := fmt.Sprintf(objAllMetaPreTmpl, name) |
| 562 |
|
| 563 |
// We will set explicitly some values so that we can do comparison |
| 564 |
// if we get an "already in use" error and need to check if it is same. |
| 565 |
// See kv |
| 566 |
replicas := cfg.Replicas |
| 567 |
if replicas == 0 { |
| 568 |
replicas = 1 |
| 569 |
} |
| 570 |
maxBytes := cfg.MaxBytes |
| 571 |
if maxBytes == 0 { |
| 572 |
maxBytes = -1 |
| 573 |
} |
| 574 |
var compression StoreCompression |
| 575 |
if cfg.Compression { |
| 576 |
compression = S2Compression |
| 577 |
} |
| 578 |
scfg := StreamConfig{ |
| 579 |
Name: fmt.Sprintf(objNameTmpl, name), |
| 580 |
Description: cfg.Description, |
| 581 |
Subjects: []string{chunks, meta}, |
| 582 |
MaxAge: cfg.TTL, |
| 583 |
MaxBytes: maxBytes, |
| 584 |
Storage: cfg.Storage, |
| 585 |
Replicas: replicas, |
| 586 |
Placement: cfg.Placement, |
| 587 |
Discard: DiscardNew, |
| 588 |
AllowRollup: true, |
| 589 |
AllowDirect: true, |
| 590 |
Metadata: cfg.Metadata, |
| 591 |
Compression: compression, |
| 592 |
} |
| 593 |
|
| 594 |
return scfg, nil |
| 595 |
} |
| 596 |
|
| 597 |
// ObjectStore will look up and bind to an existing object store instance. |
| 598 |
func (js *jetStream) ObjectStore(ctx context.Context, bucket string) (ObjectStore, error) { |
| 599 |
if !validBucketRe.MatchString(bucket) { |
| 600 |
return nil, ErrInvalidStoreName |
| 601 |
} |
| 602 |
|
| 603 |
streamName := fmt.Sprintf(objNameTmpl, bucket) |
| 604 |
stream, err := js.Stream(ctx, streamName) |
| 605 |
if err != nil { |
| 606 |
if errors.Is(err, ErrStreamNotFound) { |
| 607 |
err = ErrBucketNotFound |
| 608 |
} |
| 609 |
return nil, err |
| 610 |
} |
| 611 |
pushJS, err := js.legacyJetStream() |
| 612 |
if err != nil { |
| 613 |
return nil, err |
| 614 |
} |
| 615 |
return mapStreamToObjectStore(js, pushJS, bucket, stream), nil |
| 616 |
} |
| 617 |
|
| 618 |
// DeleteObjectStore will delete the underlying stream for the named object. |
| 619 |
func (js *jetStream) DeleteObjectStore(ctx context.Context, bucket string) error { |
| 620 |
if !validBucketRe.MatchString(bucket) { |
| 621 |
return ErrInvalidStoreName |
| 622 |
} |
| 623 |
stream := fmt.Sprintf(objNameTmpl, bucket) |
| 624 |
if err := js.DeleteStream(ctx, stream); err != nil { |
| 625 |
if errors.Is(err, ErrStreamNotFound) { |
| 626 |
err = errors.Join(fmt.Errorf("%w: %s", ErrBucketNotFound, bucket), err) |
| 627 |
} |
| 628 |
return err |
| 629 |
} |
| 630 |
return nil |
| 631 |
} |
| 632 |
|
| 633 |
func encodeName(name string) string { |
| 634 |
return base64.URLEncoding.EncodeToString([]byte(name)) |
| 635 |
} |
| 636 |
|
| 637 |
// Put will place the contents from the reader into this object-store. |
| 638 |
func (obs *obs) Put(ctx context.Context, meta ObjectMeta, r io.Reader) (*ObjectInfo, error) { |
| 639 |
if meta.Name == "" { |
| 640 |
return nil, ErrBadObjectMeta |
| 641 |
} |
| 642 |
|
| 643 |
if meta.Opts == nil { |
| 644 |
meta.Opts = &ObjectMetaOptions{ChunkSize: objDefaultChunkSize} |
| 645 |
} else if meta.Opts.Link != nil { |
| 646 |
return nil, ErrLinkNotAllowed |
| 647 |
} else if meta.Opts.ChunkSize == 0 { |
| 648 |
meta.Opts.ChunkSize = objDefaultChunkSize |
| 649 |
} |
| 650 |
|
| 651 |
// Create the new nuid so chunks go on a new subject if the name is re-used |
| 652 |
newnuid := nuid.Next() |
| 653 |
|
| 654 |
// These will be used in more than one place |
| 655 |
chunkSubj := fmt.Sprintf(objChunksPreTmpl, obs.name, newnuid) |
| 656 |
|
| 657 |
// Grab existing meta info (einfo). Ok to be found or not found, any other error is a problem |
| 658 |
// Chunks on the old nuid can be cleaned up at the end |
| 659 |
einfo, err := obs.GetInfo(ctx, meta.Name, GetObjectInfoShowDeleted()) // GetInfo will encode the name |
| 660 |
if err != nil && err != ErrObjectNotFound { |
| 661 |
return nil, err |
| 662 |
} |
| 663 |
|
| 664 |
// For async error handling |
| 665 |
var perr error |
| 666 |
var mu sync.Mutex |
| 667 |
setErr := func(err error) { |
| 668 |
mu.Lock() |
| 669 |
defer mu.Unlock() |
| 670 |
perr = err |
| 671 |
} |
| 672 |
getErr := func() error { |
| 673 |
mu.Lock() |
| 674 |
defer mu.Unlock() |
| 675 |
return perr |
| 676 |
} |
| 677 |
|
| 678 |
opts := []JetStreamOpt{ |
| 679 |
WithPublishAsyncErrHandler(func(js JetStream, _ *nats.Msg, err error) { setErr(err) }), |
| 680 |
} |
| 681 |
|
| 682 |
// if context deadline is not set, use default JetStream timeout (per publish) |
| 683 |
if _, ok := ctx.Deadline(); !ok { |
| 684 |
opts = append(opts, WithPublishAsyncTimeout(obs.js.opts.DefaultTimeout)) |
| 685 |
} |
| 686 |
|
| 687 |
// Create our own JS context to handle errors etc. |
| 688 |
pubJS, err := New(obs.js.conn, opts...) |
| 689 |
if err != nil { |
| 690 |
return nil, err |
| 691 |
} |
| 692 |
|
| 693 |
defer pubJS.(*jetStream).cleanupReplySub() |
| 694 |
|
| 695 |
purgePartial := func() { |
| 696 |
// wait until all pubs are complete or up to default timeout before attempting purge |
| 697 |
select { |
| 698 |
case <-pubJS.PublishAsyncComplete(): |
| 699 |
case <-ctx.Done(): |
| 700 |
} |
| 701 |
_ = obs.stream.Purge(ctx, WithPurgeSubject(chunkSubj)) |
| 702 |
} |
| 703 |
|
| 704 |
m, h := nats.NewMsg(chunkSubj), sha256.New() |
| 705 |
chunk, sent, total := make([]byte, meta.Opts.ChunkSize), 0, uint64(0) |
| 706 |
|
| 707 |
// set up the info object. The chunk upload sets the size and digest |
| 708 |
info := &ObjectInfo{Bucket: obs.name, NUID: newnuid, ObjectMeta: meta} |
| 709 |
|
| 710 |
for r != nil { |
| 711 |
if ctx != nil { |
| 712 |
select { |
| 713 |
case <-ctx.Done(): |
| 714 |
if ctx.Err() == context.Canceled { |
| 715 |
err = ctx.Err() |
| 716 |
} else { |
| 717 |
err = nats.ErrTimeout |
| 718 |
} |
| 719 |
default: |
| 720 |
} |
| 721 |
if err != nil { |
| 722 |
purgePartial() |
| 723 |
return nil, err |
| 724 |
} |
| 725 |
} |
| 726 |
|
| 727 |
// Actual read. |
| 728 |
// TODO(dlc) - Deadline? |
| 729 |
n, readErr := r.Read(chunk) |
| 730 |
|
| 731 |
// Handle all non EOF errors |
| 732 |
if readErr != nil && readErr != io.EOF { |
| 733 |
purgePartial() |
| 734 |
return nil, readErr |
| 735 |
} |
| 736 |
|
| 737 |
// Add chunk only if we received data |
| 738 |
if n > 0 { |
| 739 |
// Chunk processing. |
| 740 |
m.Data = chunk[:n] |
| 741 |
h.Write(m.Data) |
| 742 |
|
| 743 |
// Send msg itself. |
| 744 |
if _, err := pubJS.PublishMsgAsync(m); err != nil { |
| 745 |
purgePartial() |
| 746 |
return nil, err |
| 747 |
} |
| 748 |
if err := getErr(); err != nil { |
| 749 |
purgePartial() |
| 750 |
return nil, err |
| 751 |
} |
| 752 |
// Update totals. |
| 753 |
sent++ |
| 754 |
total += uint64(n) |
| 755 |
} |
| 756 |
|
| 757 |
// EOF Processing. |
| 758 |
if readErr == io.EOF { |
| 759 |
// Place meta info. |
| 760 |
info.Size, info.Chunks = uint64(total), uint32(sent) |
| 761 |
info.Digest = GetObjectDigestValue(h) |
| 762 |
break |
| 763 |
} |
| 764 |
} |
| 765 |
|
| 766 |
// Prepare the meta message |
| 767 |
metaSubj := fmt.Sprintf(objMetaPreTmpl, obs.name, encodeName(meta.Name)) |
| 768 |
mm := nats.NewMsg(metaSubj) |
| 769 |
mm.Header.Set(MsgRollup, MsgRollupSubject) |
| 770 |
mm.Data, err = json.Marshal(info) |
| 771 |
if err != nil { |
| 772 |
if r != nil { |
| 773 |
purgePartial() |
| 774 |
} |
| 775 |
return nil, err |
| 776 |
} |
| 777 |
|
| 778 |
// Publish the meta message. |
| 779 |
_, err = pubJS.PublishMsgAsync(mm) |
| 780 |
if err != nil { |
| 781 |
if r != nil { |
| 782 |
purgePartial() |
| 783 |
} |
| 784 |
return nil, err |
| 785 |
} |
| 786 |
|
| 787 |
// Wait for all to be processed. |
| 788 |
select { |
| 789 |
case <-pubJS.PublishAsyncComplete(): |
| 790 |
if err := getErr(); err != nil { |
| 791 |
if r != nil { |
| 792 |
purgePartial() |
| 793 |
} |
| 794 |
return nil, err |
| 795 |
} |
| 796 |
case <-ctx.Done(): |
| 797 |
return nil, nats.ErrTimeout |
| 798 |
} |
| 799 |
|
| 800 |
info.ModTime = time.Now().UTC() // This time is not actually the correct time |
| 801 |
|
| 802 |
// Delete any original chunks. |
| 803 |
if einfo != nil && !einfo.Deleted { |
| 804 |
echunkSubj := fmt.Sprintf(objChunksPreTmpl, obs.name, einfo.NUID) |
| 805 |
_ = obs.stream.Purge(ctx, WithPurgeSubject(echunkSubj)) |
| 806 |
} |
| 807 |
|
| 808 |
// TODO would it be okay to do this to return the info with the correct time? |
| 809 |
// With the understanding that it is an extra call to the server. |
| 810 |
// Otherwise the time the user gets back is the client time, not the server time. |
| 811 |
// return obs.GetInfo(info.Name) |
| 812 |
|
| 813 |
return info, nil |
| 814 |
} |
| 815 |
|
| 816 |
// GetObjectDigestValue calculates the base64 value of hashed data |
| 817 |
func GetObjectDigestValue(data hash.Hash) string { |
| 818 |
sha := data.Sum(nil) |
| 819 |
return fmt.Sprintf(objDigestTmpl, base64.URLEncoding.EncodeToString(sha[:])) |
| 820 |
} |
| 821 |
|
| 822 |
// DecodeObjectDigest decodes base64 hash |
| 823 |
func DecodeObjectDigest(data string) ([]byte, error) { |
| 824 |
digest := strings.SplitN(data, "=", 2) |
| 825 |
if len(digest) != 2 { |
| 826 |
return nil, ErrInvalidDigestFormat |
| 827 |
} |
| 828 |
return base64.URLEncoding.DecodeString(digest[1]) |
| 829 |
} |
| 830 |
|
| 831 |
func (info *ObjectInfo) isLink() bool { |
| 832 |
return info.ObjectMeta.Opts != nil && info.ObjectMeta.Opts.Link != nil |
| 833 |
} |
| 834 |
|
| 835 |
// Get will pull the object from the underlying stream. |
| 836 |
func (obs *obs) Get(ctx context.Context, name string, opts ...GetObjectOpt) (ObjectResult, error) { |
| 837 |
ctx, cancel := obs.js.wrapContextWithoutDeadline(ctx) |
| 838 |
var o getObjectOpts |
| 839 |
for _, opt := range opts { |
| 840 |
if opt != nil { |
| 841 |
if err := opt(&o); err != nil { |
| 842 |
return nil, err |
| 843 |
} |
| 844 |
} |
| 845 |
} |
| 846 |
infoOpts := make([]GetObjectInfoOpt, 0) |
| 847 |
if o.showDeleted { |
| 848 |
infoOpts = append(infoOpts, GetObjectInfoShowDeleted()) |
| 849 |
} |
| 850 |
|
| 851 |
// Grab meta info. |
| 852 |
info, err := obs.GetInfo(ctx, name, infoOpts...) |
| 853 |
if err != nil { |
| 854 |
return nil, err |
| 855 |
} |
| 856 |
if info.NUID == "" { |
| 857 |
return nil, ErrBadObjectMeta |
| 858 |
} |
| 859 |
|
| 860 |
// Check for object links. If single objects we do a pass through. |
| 861 |
if info.isLink() { |
| 862 |
if info.ObjectMeta.Opts.Link.Name == "" { |
| 863 |
return nil, ErrCantGetBucket |
| 864 |
} |
| 865 |
|
| 866 |
// is the link in the same bucket? |
| 867 |
lbuck := info.ObjectMeta.Opts.Link.Bucket |
| 868 |
if lbuck == obs.name { |
| 869 |
return obs.Get(ctx, info.ObjectMeta.Opts.Link.Name) |
| 870 |
} |
| 871 |
|
| 872 |
// different bucket |
| 873 |
lobs, err := obs.js.ObjectStore(ctx, lbuck) |
| 874 |
if err != nil { |
| 875 |
return nil, err |
| 876 |
} |
| 877 |
return lobs.Get(ctx, info.ObjectMeta.Opts.Link.Name) |
| 878 |
} |
| 879 |
|
| 880 |
result := &objResult{info: info, ctx: ctx, cancel: cancel} |
| 881 |
if info.Size == 0 { |
| 882 |
return result, nil |
| 883 |
} |
| 884 |
|
| 885 |
pr, pw := net.Pipe() |
| 886 |
result.r = pr |
| 887 |
|
| 888 |
gotErr := func(m *nats.Msg, err error) { |
| 889 |
pw.Close() |
| 890 |
m.Sub.Unsubscribe() |
| 891 |
result.setErr(err) |
| 892 |
} |
| 893 |
|
| 894 |
// For calculating sum256 |
| 895 |
result.digest = sha256.New() |
| 896 |
|
| 897 |
processChunk := func(m *nats.Msg) { |
| 898 |
var err error |
| 899 |
if ctx != nil { |
| 900 |
select { |
| 901 |
case <-ctx.Done(): |
| 902 |
if ctx.Err() == context.Canceled { |
| 903 |
err = ctx.Err() |
| 904 |
} else { |
| 905 |
err = nats.ErrTimeout |
| 906 |
} |
| 907 |
default: |
| 908 |
} |
| 909 |
if err != nil { |
| 910 |
gotErr(m, err) |
| 911 |
return |
| 912 |
} |
| 913 |
} |
| 914 |
|
| 915 |
tokens, err := parser.GetMetadataFields(m.Reply) |
| 916 |
if err != nil { |
| 917 |
gotErr(m, err) |
| 918 |
return |
| 919 |
} |
| 920 |
|
| 921 |
// Write to our pipe. |
| 922 |
for b := m.Data; len(b) > 0; { |
| 923 |
n, err := pw.Write(b) |
| 924 |
if err != nil { |
| 925 |
gotErr(m, err) |
| 926 |
return |
| 927 |
} |
| 928 |
b = b[n:] |
| 929 |
} |
| 930 |
// Update sha256 |
| 931 |
result.digest.Write(m.Data) |
| 932 |
|
| 933 |
// Check if we are done. |
| 934 |
if tokens[parser.AckNumPendingTokenPos] == objNoPending { |
| 935 |
pw.Close() |
| 936 |
m.Sub.Unsubscribe() |
| 937 |
} |
| 938 |
} |
| 939 |
|
| 940 |
chunkSubj := fmt.Sprintf(objChunksPreTmpl, obs.name, info.NUID) |
| 941 |
streamName := fmt.Sprintf(objNameTmpl, obs.name) |
| 942 |
subscribeOpts := []nats.SubOpt{ |
| 943 |
nats.OrderedConsumer(), |
| 944 |
nats.Context(ctx), |
| 945 |
nats.BindStream(streamName), |
| 946 |
} |
| 947 |
_, err = obs.pushJS.Subscribe(chunkSubj, processChunk, subscribeOpts...) |
| 948 |
if err != nil { |
| 949 |
return nil, err |
| 950 |
} |
| 951 |
|
| 952 |
return result, nil |
| 953 |
} |
| 954 |
|
| 955 |
// Delete will delete the object. |
| 956 |
func (obs *obs) Delete(ctx context.Context, name string) error { |
| 957 |
// Grab meta info. |
| 958 |
info, err := obs.GetInfo(ctx, name, GetObjectInfoShowDeleted()) |
| 959 |
if err != nil { |
| 960 |
return err |
| 961 |
} |
| 962 |
if info.NUID == "" { |
| 963 |
return ErrBadObjectMeta |
| 964 |
} |
| 965 |
|
| 966 |
// Place a rollup delete marker and publish the info |
| 967 |
info.Deleted = true |
| 968 |
info.Size, info.Chunks, info.Digest = 0, 0, "" |
| 969 |
|
| 970 |
if err = publishMeta(ctx, info, obs.js); err != nil { |
| 971 |
return err |
| 972 |
} |
| 973 |
|
| 974 |
// Purge chunks for the object. |
| 975 |
chunkSubj := fmt.Sprintf(objChunksPreTmpl, obs.name, info.NUID) |
| 976 |
return obs.stream.Purge(ctx, WithPurgeSubject(chunkSubj)) |
| 977 |
} |
| 978 |
|
| 979 |
func publishMeta(ctx context.Context, info *ObjectInfo, js *jetStream) error { |
| 980 |
// marshal the object into json, don't store an actual time |
| 981 |
info.ModTime = time.Time{} |
| 982 |
data, err := json.Marshal(info) |
| 983 |
if err != nil { |
| 984 |
return err |
| 985 |
} |
| 986 |
|
| 987 |
// Prepare and publish the message. |
| 988 |
mm := nats.NewMsg(fmt.Sprintf(objMetaPreTmpl, info.Bucket, encodeName(info.ObjectMeta.Name))) |
| 989 |
mm.Header.Set(MsgRollup, MsgRollupSubject) |
| 990 |
mm.Data = data |
| 991 |
if _, err := js.PublishMsg(ctx, mm); err != nil { |
| 992 |
return err |
| 993 |
} |
| 994 |
|
| 995 |
// set the ModTime in case it's returned to the user, even though it's not the correct time. |
| 996 |
info.ModTime = time.Now().UTC() |
| 997 |
return nil |
| 998 |
} |
| 999 |
|
| 1000 |
// AddLink will add a link to another object if it's not deleted and not another link |
| 1001 |
// name is the name of this link object |
| 1002 |
// obj is what is being linked too |
| 1003 |
func (obs *obs) AddLink(ctx context.Context, name string, obj *ObjectInfo) (*ObjectInfo, error) { |
| 1004 |
if name == "" { |
| 1005 |
return nil, ErrNameRequired |
| 1006 |
} |
| 1007 |
|
| 1008 |
// TODO Handle stale info |
| 1009 |
|
| 1010 |
if obj == nil || obj.Name == "" { |
| 1011 |
return nil, ErrObjectRequired |
| 1012 |
} |
| 1013 |
if obj.Deleted { |
| 1014 |
return nil, ErrNoLinkToDeleted |
| 1015 |
} |
| 1016 |
if obj.isLink() { |
| 1017 |
return nil, ErrNoLinkToLink |
| 1018 |
} |
| 1019 |
|
| 1020 |
// If object with link's name is found, error. |
| 1021 |
// If link with link's name is found, that's okay to overwrite. |
| 1022 |
// If there was an error that was not ErrObjectNotFound, error. |
| 1023 |
einfo, err := obs.GetInfo(ctx, name, GetObjectInfoShowDeleted()) |
| 1024 |
if einfo != nil { |
| 1025 |
if !einfo.isLink() { |
| 1026 |
return nil, ErrObjectAlreadyExists |
| 1027 |
} |
| 1028 |
} else if err != ErrObjectNotFound { |
| 1029 |
return nil, err |
| 1030 |
} |
| 1031 |
|
| 1032 |
// create the meta for the link |
| 1033 |
meta := &ObjectMeta{ |
| 1034 |
Name: name, |
| 1035 |
Opts: &ObjectMetaOptions{Link: &ObjectLink{Bucket: obj.Bucket, Name: obj.Name}}, |
| 1036 |
} |
| 1037 |
info := &ObjectInfo{Bucket: obs.name, NUID: nuid.Next(), ModTime: time.Now().UTC(), ObjectMeta: *meta} |
| 1038 |
|
| 1039 |
// put the link object |
| 1040 |
if err = publishMeta(ctx, info, obs.js); err != nil { |
| 1041 |
return nil, err |
| 1042 |
} |
| 1043 |
|
| 1044 |
return info, nil |
| 1045 |
} |
| 1046 |
|
| 1047 |
// AddBucketLink will add a link to another object store. |
| 1048 |
func (ob *obs) AddBucketLink(ctx context.Context, name string, bucket ObjectStore) (*ObjectInfo, error) { |
| 1049 |
if name == "" { |
| 1050 |
return nil, ErrNameRequired |
| 1051 |
} |
| 1052 |
if bucket == nil { |
| 1053 |
return nil, ErrBucketRequired |
| 1054 |
} |
| 1055 |
bos, ok := bucket.(*obs) |
| 1056 |
if !ok { |
| 1057 |
return nil, ErrBucketMalformed |
| 1058 |
} |
| 1059 |
|
| 1060 |
// If object with link's name is found, error. |
| 1061 |
// If link with link's name is found, that's okay to overwrite. |
| 1062 |
// If there was an error that was not ErrObjectNotFound, error. |
| 1063 |
einfo, err := ob.GetInfo(ctx, name, GetObjectInfoShowDeleted()) |
| 1064 |
if einfo != nil { |
| 1065 |
if !einfo.isLink() { |
| 1066 |
return nil, ErrObjectAlreadyExists |
| 1067 |
} |
| 1068 |
} else if err != ErrObjectNotFound { |
| 1069 |
return nil, err |
| 1070 |
} |
| 1071 |
|
| 1072 |
// create the meta for the link |
| 1073 |
meta := &ObjectMeta{ |
| 1074 |
Name: name, |
| 1075 |
Opts: &ObjectMetaOptions{Link: &ObjectLink{Bucket: bos.name}}, |
| 1076 |
} |
| 1077 |
info := &ObjectInfo{Bucket: ob.name, NUID: nuid.Next(), ObjectMeta: *meta} |
| 1078 |
|
| 1079 |
// put the link object |
| 1080 |
err = publishMeta(ctx, info, ob.js) |
| 1081 |
if err != nil { |
| 1082 |
return nil, err |
| 1083 |
} |
| 1084 |
|
| 1085 |
return info, nil |
| 1086 |
} |
| 1087 |
|
| 1088 |
// PutBytes is convenience function to put a byte slice into this object store. |
| 1089 |
func (obs *obs) PutBytes(ctx context.Context, name string, data []byte) (*ObjectInfo, error) { |
| 1090 |
return obs.Put(ctx, ObjectMeta{Name: name}, bytes.NewReader(data)) |
| 1091 |
} |
| 1092 |
|
| 1093 |
// GetBytes is a convenience function to pull an object from this object store and return it as a byte slice. |
| 1094 |
func (obs *obs) GetBytes(ctx context.Context, name string, opts ...GetObjectOpt) ([]byte, error) { |
| 1095 |
result, err := obs.Get(ctx, name, opts...) |
| 1096 |
if err != nil { |
| 1097 |
return nil, err |
| 1098 |
} |
| 1099 |
defer result.Close() |
| 1100 |
|
| 1101 |
var b bytes.Buffer |
| 1102 |
if _, err := b.ReadFrom(result); err != nil { |
| 1103 |
return nil, err |
| 1104 |
} |
| 1105 |
return b.Bytes(), nil |
| 1106 |
} |
| 1107 |
|
| 1108 |
// PutString is convenience function to put a string into this object store. |
| 1109 |
func (obs *obs) PutString(ctx context.Context, name string, data string) (*ObjectInfo, error) { |
| 1110 |
return obs.Put(ctx, ObjectMeta{Name: name}, strings.NewReader(data)) |
| 1111 |
} |
| 1112 |
|
| 1113 |
// GetString is a convenience function to pull an object from this object store and return it as a string. |
| 1114 |
func (obs *obs) GetString(ctx context.Context, name string, opts ...GetObjectOpt) (string, error) { |
| 1115 |
result, err := obs.Get(ctx, name, opts...) |
| 1116 |
if err != nil { |
| 1117 |
return "", err |
| 1118 |
} |
| 1119 |
defer result.Close() |
| 1120 |
|
| 1121 |
var b bytes.Buffer |
| 1122 |
if _, err := b.ReadFrom(result); err != nil { |
| 1123 |
return "", err |
| 1124 |
} |
| 1125 |
return b.String(), nil |
| 1126 |
} |
| 1127 |
|
| 1128 |
// PutFile is convenience function to put a file into an object store. |
| 1129 |
func (obs *obs) PutFile(ctx context.Context, file string) (*ObjectInfo, error) { |
| 1130 |
f, err := os.Open(file) |
| 1131 |
if err != nil { |
| 1132 |
return nil, err |
| 1133 |
} |
| 1134 |
defer f.Close() |
| 1135 |
return obs.Put(ctx, ObjectMeta{Name: file}, f) |
| 1136 |
} |
| 1137 |
|
| 1138 |
// GetFile is a convenience function to pull and object and place in a file. |
| 1139 |
func (obs *obs) GetFile(ctx context.Context, name, file string, opts ...GetObjectOpt) error { |
| 1140 |
// Expect file to be new. |
| 1141 |
f, err := os.OpenFile(file, os.O_WRONLY|os.O_CREATE, 0600) |
| 1142 |
if err != nil { |
| 1143 |
return err |
| 1144 |
} |
| 1145 |
defer f.Close() |
| 1146 |
|
| 1147 |
result, err := obs.Get(ctx, name, opts...) |
| 1148 |
if err != nil { |
| 1149 |
os.Remove(f.Name()) |
| 1150 |
return err |
| 1151 |
} |
| 1152 |
defer result.Close() |
| 1153 |
|
| 1154 |
// Stream copy to the file. |
| 1155 |
_, err = io.Copy(f, result) |
| 1156 |
return err |
| 1157 |
} |
| 1158 |
|
| 1159 |
// GetInfo will retrieve the current information for the object. |
| 1160 |
func (obs *obs) GetInfo(ctx context.Context, name string, opts ...GetObjectInfoOpt) (*ObjectInfo, error) { |
| 1161 |
// Grab last meta value we have. |
| 1162 |
if name == "" { |
| 1163 |
return nil, ErrNameRequired |
| 1164 |
} |
| 1165 |
var o getObjectInfoOpts |
| 1166 |
for _, opt := range opts { |
| 1167 |
if opt != nil { |
| 1168 |
if err := opt(&o); err != nil { |
| 1169 |
return nil, err |
| 1170 |
} |
| 1171 |
} |
| 1172 |
} |
| 1173 |
|
| 1174 |
metaSubj := fmt.Sprintf(objMetaPreTmpl, obs.name, encodeName(name)) // used as data in a JS API call |
| 1175 |
|
| 1176 |
m, err := obs.stream.GetLastMsgForSubject(ctx, metaSubj) |
| 1177 |
if err != nil { |
| 1178 |
if errors.Is(err, ErrMsgNotFound) { |
| 1179 |
err = ErrObjectNotFound |
| 1180 |
} |
| 1181 |
if errors.Is(err, ErrStreamNotFound) { |
| 1182 |
err = ErrBucketNotFound |
| 1183 |
} |
| 1184 |
return nil, err |
| 1185 |
} |
| 1186 |
var info ObjectInfo |
| 1187 |
if err := json.Unmarshal(m.Data, &info); err != nil { |
| 1188 |
return nil, ErrBadObjectMeta |
| 1189 |
} |
| 1190 |
if !o.showDeleted && info.Deleted { |
| 1191 |
return nil, ErrObjectNotFound |
| 1192 |
} |
| 1193 |
info.ModTime = m.Time |
| 1194 |
return &info, nil |
| 1195 |
} |
| 1196 |
|
| 1197 |
// UpdateMeta will update the meta for the object. |
| 1198 |
func (obs *obs) UpdateMeta(ctx context.Context, name string, meta ObjectMeta) error { |
| 1199 |
// Grab the current meta. |
| 1200 |
info, err := obs.GetInfo(ctx, name) |
| 1201 |
if err != nil { |
| 1202 |
if errors.Is(err, ErrObjectNotFound) { |
| 1203 |
return ErrUpdateMetaDeleted |
| 1204 |
} |
| 1205 |
return err |
| 1206 |
} |
| 1207 |
|
| 1208 |
// If the new name is different from the old, and it exists, error |
| 1209 |
// If there was an error that was not ErrObjectNotFound, error. |
| 1210 |
if name != meta.Name { |
| 1211 |
existingInfo, err := obs.GetInfo(ctx, meta.Name, GetObjectInfoShowDeleted()) |
| 1212 |
if err != nil && !errors.Is(err, ErrObjectNotFound) { |
| 1213 |
return err |
| 1214 |
} |
| 1215 |
if err == nil && !existingInfo.Deleted { |
| 1216 |
return ErrObjectAlreadyExists |
| 1217 |
} |
| 1218 |
} |
| 1219 |
|
| 1220 |
// Update Meta prevents update of ObjectMetaOptions (Link, ChunkSize) |
| 1221 |
// These should only be updated internally when appropriate. |
| 1222 |
info.Name = meta.Name |
| 1223 |
info.Description = meta.Description |
| 1224 |
info.Headers = meta.Headers |
| 1225 |
info.Metadata = meta.Metadata |
| 1226 |
|
| 1227 |
// Prepare the meta message |
| 1228 |
if err = publishMeta(ctx, info, obs.js); err != nil { |
| 1229 |
return err |
| 1230 |
} |
| 1231 |
|
| 1232 |
// did the name of this object change? We just stored the meta under the new name |
| 1233 |
// so delete the meta from the old name via purge stream for subject |
| 1234 |
if name != meta.Name { |
| 1235 |
metaSubj := fmt.Sprintf(objMetaPreTmpl, obs.name, encodeName(name)) |
| 1236 |
return obs.stream.Purge(ctx, WithPurgeSubject(metaSubj)) |
| 1237 |
} |
| 1238 |
|
| 1239 |
return nil |
| 1240 |
} |
| 1241 |
|
| 1242 |
// Seal will seal the object store, no further modifications will be allowed. |
| 1243 |
func (obs *obs) Seal(ctx context.Context) error { |
| 1244 |
si, err := obs.stream.Info(ctx) |
| 1245 |
if err != nil { |
| 1246 |
return err |
| 1247 |
} |
| 1248 |
// Seal the stream from being able to take on more messages. |
| 1249 |
cfg := si.Config |
| 1250 |
cfg.Sealed = true |
| 1251 |
_, err = obs.js.UpdateStream(ctx, cfg) |
| 1252 |
return err |
| 1253 |
} |
| 1254 |
|
| 1255 |
// Implementation for Watch |
| 1256 |
type objWatcher struct { |
| 1257 |
updates chan *ObjectInfo |
| 1258 |
sub *nats.Subscription |
| 1259 |
} |
| 1260 |
|
| 1261 |
// Updates returns the interior channel. |
| 1262 |
func (w *objWatcher) Updates() <-chan *ObjectInfo { |
| 1263 |
if w == nil { |
| 1264 |
return nil |
| 1265 |
} |
| 1266 |
return w.updates |
| 1267 |
} |
| 1268 |
|
| 1269 |
// Stop will unsubscribe from the watcher. |
| 1270 |
func (w *objWatcher) Stop() error { |
| 1271 |
if w == nil { |
| 1272 |
return nil |
| 1273 |
} |
| 1274 |
return w.sub.Unsubscribe() |
| 1275 |
} |
| 1276 |
|
| 1277 |
// Watch for changes in the underlying store and receive meta information updates. |
| 1278 |
func (obs *obs) Watch(ctx context.Context, opts ...WatchOpt) (ObjectWatcher, error) { |
| 1279 |
var o watchOpts |
| 1280 |
for _, opt := range opts { |
| 1281 |
if opt != nil { |
| 1282 |
if err := opt.configureWatcher(&o); err != nil { |
| 1283 |
return nil, err |
| 1284 |
} |
| 1285 |
} |
| 1286 |
} |
| 1287 |
|
| 1288 |
var initDoneMarker bool |
| 1289 |
|
| 1290 |
w := &objWatcher{updates: make(chan *ObjectInfo, 32)} |
| 1291 |
|
| 1292 |
update := func(m *nats.Msg) { |
| 1293 |
var info ObjectInfo |
| 1294 |
if err := json.Unmarshal(m.Data, &info); err != nil { |
| 1295 |
return // TODO(dlc) - Communicate this upwards? |
| 1296 |
} |
| 1297 |
meta, err := m.Metadata() |
| 1298 |
if err != nil { |
| 1299 |
return |
| 1300 |
} |
| 1301 |
|
| 1302 |
if !o.ignoreDeletes || !info.Deleted { |
| 1303 |
info.ModTime = meta.Timestamp |
| 1304 |
w.updates <- &info |
| 1305 |
} |
| 1306 |
|
| 1307 |
// if UpdatesOnly is set, no not send nil to the channel |
| 1308 |
// as it would always be triggered after initializing the watcher |
| 1309 |
if !initDoneMarker && meta.NumPending == 0 { |
| 1310 |
initDoneMarker = true |
| 1311 |
w.updates <- nil |
| 1312 |
} |
| 1313 |
} |
| 1314 |
|
| 1315 |
allMeta := fmt.Sprintf(objAllMetaPreTmpl, obs.name) |
| 1316 |
_, err := obs.stream.GetLastMsgForSubject(ctx, allMeta) |
| 1317 |
// if there are no messages on the stream and we are not watching |
| 1318 |
// updates only, send nil to the channel to indicate that the initial |
| 1319 |
// watch is done |
| 1320 |
if !o.updatesOnly { |
| 1321 |
if errors.Is(err, ErrMsgNotFound) { |
| 1322 |
initDoneMarker = true |
| 1323 |
w.updates <- nil |
| 1324 |
} |
| 1325 |
} else { |
| 1326 |
// if UpdatesOnly was used, mark initialization as complete |
| 1327 |
initDoneMarker = true |
| 1328 |
} |
| 1329 |
|
| 1330 |
// Used ordered consumer to deliver results. |
| 1331 |
streamName := fmt.Sprintf(objNameTmpl, obs.name) |
| 1332 |
subOpts := []nats.SubOpt{nats.OrderedConsumer(), nats.BindStream(streamName)} |
| 1333 |
if !o.includeHistory { |
| 1334 |
subOpts = append(subOpts, nats.DeliverLastPerSubject()) |
| 1335 |
} |
| 1336 |
if o.updatesOnly { |
| 1337 |
subOpts = append(subOpts, nats.DeliverNew()) |
| 1338 |
} |
| 1339 |
subOpts = append(subOpts, nats.Context(ctx)) |
| 1340 |
sub, err := obs.pushJS.Subscribe(allMeta, update, subOpts...) |
| 1341 |
if err != nil { |
| 1342 |
return nil, err |
| 1343 |
} |
| 1344 |
sub.SetClosedHandler(func(_ string) { |
| 1345 |
close(w.updates) |
| 1346 |
}) |
| 1347 |
w.sub = sub |
| 1348 |
return w, nil |
| 1349 |
} |
| 1350 |
|
| 1351 |
// List will list all the objects in this store. |
| 1352 |
func (obs *obs) List(ctx context.Context, opts ...ListObjectsOpt) ([]*ObjectInfo, error) { |
| 1353 |
var o listObjectOpts |
| 1354 |
for _, opt := range opts { |
| 1355 |
if opt != nil { |
| 1356 |
if err := opt(&o); err != nil { |
| 1357 |
return nil, err |
| 1358 |
} |
| 1359 |
} |
| 1360 |
} |
| 1361 |
watchOpts := make([]WatchOpt, 0) |
| 1362 |
if !o.showDeleted { |
| 1363 |
watchOpts = append(watchOpts, IgnoreDeletes()) |
| 1364 |
} |
| 1365 |
watcher, err := obs.Watch(ctx, watchOpts...) |
| 1366 |
if err != nil { |
| 1367 |
return nil, err |
| 1368 |
} |
| 1369 |
defer watcher.Stop() |
| 1370 |
|
| 1371 |
var objs []*ObjectInfo |
| 1372 |
updates := watcher.Updates() |
| 1373 |
Updates: |
| 1374 |
for { |
| 1375 |
select { |
| 1376 |
case entry := <-updates: |
| 1377 |
if entry == nil { |
| 1378 |
break Updates |
| 1379 |
} |
| 1380 |
objs = append(objs, entry) |
| 1381 |
case <-ctx.Done(): |
| 1382 |
return nil, ctx.Err() |
| 1383 |
} |
| 1384 |
} |
| 1385 |
if len(objs) == 0 { |
| 1386 |
return nil, ErrNoObjectsFound |
| 1387 |
} |
| 1388 |
return objs, nil |
| 1389 |
} |
| 1390 |
|
| 1391 |
// ObjectBucketStatus represents status of a Bucket, implements ObjectStoreStatus |
| 1392 |
type ObjectBucketStatus struct { |
| 1393 |
nfo *StreamInfo |
| 1394 |
bucket string |
| 1395 |
} |
| 1396 |
|
| 1397 |
// Bucket is the name of the bucket |
| 1398 |
func (s *ObjectBucketStatus) Bucket() string { return s.bucket } |
| 1399 |
|
| 1400 |
// Description is the description supplied when creating the bucket |
| 1401 |
func (s *ObjectBucketStatus) Description() string { return s.nfo.Config.Description } |
| 1402 |
|
| 1403 |
// TTL indicates how long objects are kept in the bucket |
| 1404 |
func (s *ObjectBucketStatus) TTL() time.Duration { return s.nfo.Config.MaxAge } |
| 1405 |
|
| 1406 |
// Storage indicates the underlying JetStream storage technology used to store data |
| 1407 |
func (s *ObjectBucketStatus) Storage() StorageType { return s.nfo.Config.Storage } |
| 1408 |
|
| 1409 |
// Replicas indicates how many storage replicas are kept for the data in the bucket |
| 1410 |
func (s *ObjectBucketStatus) Replicas() int { return s.nfo.Config.Replicas } |
| 1411 |
|
| 1412 |
// Sealed indicates the stream is sealed and cannot be modified in any way |
| 1413 |
func (s *ObjectBucketStatus) Sealed() bool { return s.nfo.Config.Sealed } |
| 1414 |
|
| 1415 |
// Size is the combined size of all data in the bucket including metadata, in bytes |
| 1416 |
func (s *ObjectBucketStatus) Size() uint64 { return s.nfo.State.Bytes } |
| 1417 |
|
| 1418 |
// BackingStore indicates what technology is used for storage of the bucket |
| 1419 |
func (s *ObjectBucketStatus) BackingStore() string { return "JetStream" } |
| 1420 |
|
| 1421 |
// Metadata is the metadata supplied when creating the bucket |
| 1422 |
func (s *ObjectBucketStatus) Metadata() map[string]string { return s.nfo.Config.Metadata } |
| 1423 |
|
| 1424 |
// StreamInfo is the stream info retrieved to create the status |
| 1425 |
func (s *ObjectBucketStatus) StreamInfo() *StreamInfo { return s.nfo } |
| 1426 |
|
| 1427 |
// IsCompressed indicates if the data is compressed on disk |
| 1428 |
func (s *ObjectBucketStatus) IsCompressed() bool { return s.nfo.Config.Compression != NoCompression } |
| 1429 |
|
| 1430 |
// Status retrieves run-time status about a bucket |
| 1431 |
func (obs *obs) Status(ctx context.Context) (ObjectStoreStatus, error) { |
| 1432 |
nfo, err := obs.stream.Info(ctx) |
| 1433 |
if err != nil { |
| 1434 |
return nil, err |
| 1435 |
} |
| 1436 |
|
| 1437 |
status := &ObjectBucketStatus{ |
| 1438 |
nfo: nfo, |
| 1439 |
bucket: obs.name, |
| 1440 |
} |
| 1441 |
|
| 1442 |
return status, nil |
| 1443 |
} |
| 1444 |
|
| 1445 |
// Read impl. |
| 1446 |
func (o *objResult) Read(p []byte) (n int, err error) { |
| 1447 |
o.Lock() |
| 1448 |
defer o.Unlock() |
| 1449 |
readDeadline := time.Now().Add(defaultAPITimeout) |
| 1450 |
if ctx := o.ctx; ctx != nil { |
| 1451 |
if deadline, ok := ctx.Deadline(); ok { |
| 1452 |
readDeadline = deadline |
| 1453 |
} |
| 1454 |
select { |
| 1455 |
case <-ctx.Done(): |
| 1456 |
if ctx.Err() == context.Canceled { |
| 1457 |
o.err = ctx.Err() |
| 1458 |
} else { |
| 1459 |
o.err = nats.ErrTimeout |
| 1460 |
} |
| 1461 |
default: |
| 1462 |
} |
| 1463 |
} |
| 1464 |
if o.err != nil { |
| 1465 |
return 0, o.err |
| 1466 |
} |
| 1467 |
if o.r == nil { |
| 1468 |
return 0, io.EOF |
| 1469 |
} |
| 1470 |
|
| 1471 |
r := o.r.(net.Conn) |
| 1472 |
_ = r.SetReadDeadline(readDeadline) |
| 1473 |
n, err = r.Read(p) |
| 1474 |
if err, ok := err.(net.Error); ok && err.Timeout() { |
| 1475 |
if ctx := o.ctx; ctx != nil { |
| 1476 |
select { |
| 1477 |
case <-ctx.Done(): |
| 1478 |
if ctx.Err() == context.Canceled { |
| 1479 |
return 0, ctx.Err() |
| 1480 |
} else { |
| 1481 |
return 0, nats.ErrTimeout |
| 1482 |
} |
| 1483 |
default: |
| 1484 |
err = nil |
| 1485 |
} |
| 1486 |
} |
| 1487 |
} |
| 1488 |
if err == io.EOF { |
| 1489 |
// Make sure the digest matches. |
| 1490 |
sha := o.digest.Sum(nil) |
| 1491 |
rsha, decodeErr := DecodeObjectDigest(o.info.Digest) |
| 1492 |
if decodeErr != nil { |
| 1493 |
o.err = decodeErr |
| 1494 |
return 0, o.err |
| 1495 |
} |
| 1496 |
if !bytes.Equal(sha[:], rsha) { |
| 1497 |
o.err = ErrDigestMismatch |
| 1498 |
return 0, o.err |
| 1499 |
} |
| 1500 |
} |
| 1501 |
return n, err |
| 1502 |
} |
| 1503 |
|
| 1504 |
// Close impl. |
| 1505 |
func (o *objResult) Close() error { |
| 1506 |
o.Lock() |
| 1507 |
defer o.Unlock() |
| 1508 |
if o.cancel != nil { |
| 1509 |
o.cancel() |
| 1510 |
} |
| 1511 |
if o.r == nil { |
| 1512 |
return nil |
| 1513 |
} |
| 1514 |
return o.r.Close() |
| 1515 |
} |
| 1516 |
|
| 1517 |
func (o *objResult) setErr(err error) { |
| 1518 |
o.Lock() |
| 1519 |
defer o.Unlock() |
| 1520 |
o.err = err |
| 1521 |
} |
| 1522 |
|
| 1523 |
func (o *objResult) Info() (*ObjectInfo, error) { |
| 1524 |
o.Lock() |
| 1525 |
defer o.Unlock() |
| 1526 |
return o.info, o.err |
| 1527 |
} |
| 1528 |
|
| 1529 |
func (o *objResult) Error() error { |
| 1530 |
o.Lock() |
| 1531 |
defer o.Unlock() |
| 1532 |
return o.err |
| 1533 |
} |
| 1534 |
|
| 1535 |
// ObjectStoreNames is used to retrieve a list of bucket names |
| 1536 |
func (js *jetStream) ObjectStoreNames(ctx context.Context) ObjectStoreNamesLister { |
| 1537 |
res := &obsLister{ |
| 1538 |
obsNames: make(chan string), |
| 1539 |
} |
| 1540 |
l := &streamLister{js: js} |
| 1541 |
streamsReq := streamsRequest{ |
| 1542 |
Subject: fmt.Sprintf(objAllChunksPreTmpl, "*"), |
| 1543 |
} |
| 1544 |
|
| 1545 |
go func() { |
| 1546 |
defer close(res.obsNames) |
| 1547 |
for { |
| 1548 |
page, err := l.streamNames(ctx, streamsReq) |
| 1549 |
if err != nil && !errors.Is(err, ErrEndOfData) { |
| 1550 |
res.err = err |
| 1551 |
return |
| 1552 |
} |
| 1553 |
for _, name := range page { |
| 1554 |
if !strings.HasPrefix(name, "OBJ_") { |
| 1555 |
continue |
| 1556 |
} |
| 1557 |
res.obsNames <- strings.TrimPrefix(name, "OBJ_") |
| 1558 |
} |
| 1559 |
if errors.Is(err, ErrEndOfData) { |
| 1560 |
return |
| 1561 |
} |
| 1562 |
} |
| 1563 |
}() |
| 1564 |
|
| 1565 |
return res |
| 1566 |
} |
| 1567 |
|
| 1568 |
// ObjectStores is used to retrieve a list of bucket statuses |
| 1569 |
func (js *jetStream) ObjectStores(ctx context.Context) ObjectStoresLister { |
| 1570 |
res := &obsLister{ |
| 1571 |
obs: make(chan ObjectStoreStatus), |
| 1572 |
} |
| 1573 |
l := &streamLister{js: js} |
| 1574 |
streamsReq := streamsRequest{ |
| 1575 |
Subject: fmt.Sprintf(objAllChunksPreTmpl, "*"), |
| 1576 |
} |
| 1577 |
go func() { |
| 1578 |
defer close(res.obs) |
| 1579 |
for { |
| 1580 |
page, err := l.streamInfos(ctx, streamsReq) |
| 1581 |
if err != nil && !errors.Is(err, ErrEndOfData) { |
| 1582 |
res.err = err |
| 1583 |
return |
| 1584 |
} |
| 1585 |
for _, info := range page { |
| 1586 |
if !strings.HasPrefix(info.Config.Name, "OBJ_") { |
| 1587 |
continue |
| 1588 |
} |
| 1589 |
res.obs <- &ObjectBucketStatus{ |
| 1590 |
nfo: info, |
| 1591 |
bucket: strings.TrimPrefix(info.Config.Name, "OBJ_"), |
| 1592 |
} |
| 1593 |
} |
| 1594 |
if errors.Is(err, ErrEndOfData) { |
| 1595 |
return |
| 1596 |
} |
| 1597 |
} |
| 1598 |
}() |
| 1599 |
|
| 1600 |
return res |
| 1601 |
} |
| 1602 |
|
| 1603 |
type obsLister struct { |
| 1604 |
obs chan ObjectStoreStatus |
| 1605 |
obsNames chan string |
| 1606 |
err error |
| 1607 |
} |
| 1608 |
|
| 1609 |
func (ol *obsLister) Status() <-chan ObjectStoreStatus { |
| 1610 |
return ol.obs |
| 1611 |
} |
| 1612 |
|
| 1613 |
func (ol *obsLister) Name() <-chan string { |
| 1614 |
return ol.obsNames |
| 1615 |
} |
| 1616 |
|
| 1617 |
func (ol *obsLister) Error() error { |
| 1618 |
return ol.err |
| 1619 |
} |
| 1620 |
|
| 1621 |
func mapStreamToObjectStore(js *jetStream, pushJS nats.JetStreamContext, bucket string, stream Stream) *obs { |
| 1622 |
info := stream.CachedInfo() |
| 1623 |
|
| 1624 |
obs := &obs{ |
| 1625 |
name: bucket, |
| 1626 |
js: js, |
| 1627 |
pushJS: pushJS, |
| 1628 |
streamName: info.Config.Name, |
| 1629 |
stream: stream, |
| 1630 |
} |
| 1631 |
|
| 1632 |
return obs |
| 1633 |
} |