Debian Codegraph @

object.go

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