github.com/niedbalski/juju@v0.0.0-20190215020005-8ff100488e47/state/globalclock/reader.go (about)

     1  // Copyright 2017 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package globalclock
     5  
     6  import (
     7  	"time"
     8  
     9  	"github.com/juju/errors"
    10  	"gopkg.in/mgo.v2"
    11  )
    12  
    13  // Reader provides a means of reading the global clock time.
    14  //
    15  // Reader is not goroutine-safe.
    16  type Reader struct {
    17  	config ReaderConfig
    18  }
    19  
    20  // NewReader returns a new Reader using the supplied config, or an error.
    21  //
    22  // Readers will not function past the lifetime of their configured Mongo.
    23  func NewReader(config ReaderConfig) (*Reader, error) {
    24  	if err := config.validate(); err != nil {
    25  		return nil, errors.Trace(err)
    26  	}
    27  	r := &Reader{config: config}
    28  	return r, nil
    29  }
    30  
    31  // Now returns the current global time.
    32  func (r *Reader) Now() (time.Time, error) {
    33  	coll, closer := r.config.Mongo.GetCollection(r.config.Collection)
    34  	defer closer()
    35  
    36  	t, err := readClock(coll)
    37  	if errors.Cause(err) == mgo.ErrNotFound {
    38  		// No time written yet. When it is written
    39  		// for the first time, it'll be globalEpoch.
    40  		t = globalEpoch
    41  	} else if err != nil {
    42  		return time.Time{}, errors.Trace(err)
    43  	}
    44  	return t, nil
    45  }